sapbot

Tiny GPT trainer

Feb 8th, 2026
59
0
Never
9
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.16 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3.  
  4. import os
  5. import argparse
  6. import math
  7. from pathlib import Path
  8. import torch
  9. from tokenizers import ByteLevelBPETokenizer
  10. from transformers import (
  11.     GPT2Config,
  12.     GPT2LMHeadModel,
  13.     GPT2TokenizerFast,
  14.     DataCollatorForLanguageModeling,
  15.     Trainer,
  16.     TrainingArguments,
  17. )
  18. from datasets import Dataset
  19.  
  20. def train_tokenizer(text_files, vocab_size: int, out_dir: str):
  21.     print(f"Training tokenizer on {text_files}...")
  22.     tokenizer = ByteLevelBPETokenizer()
  23.     tokenizer.train(
  24.         files=text_files,
  25.         vocab_size=vocab_size,
  26.         min_frequency=2,
  27.         special_tokens=["<s>", "<pad>", "</s>", "<unk>", "<mask>"]
  28.     )
  29.     os.makedirs(out_dir, exist_ok=True)
  30.     tokenizer.save_model(out_dir)
  31.  
  32.     tokenizer_hf = GPT2TokenizerFast.from_pretrained(out_dir)
  33.     tokenizer_hf.pad_token = "<pad>"
  34.     tokenizer_hf.bos_token = "<s>"
  35.     tokenizer_hf.eos_token = "</s>"
  36.     tokenizer_hf.unk_token = "<unk>"
  37.     tokenizer_hf.mask_token = "<mask>"
  38.    
  39.     tokenizer_hf.save_pretrained(out_dir)
  40.     return tokenizer_hf
  41.  
  42. def calculate_auto_epochs(num_samples, batch_size):
  43.     """
  44.    Logic to decide epochs:
  45.    - We want a minimum of ~2,000 total steps for the model to learn anything.
  46.    - We want a maximum of ~50,000 steps to avoid over-training for this script.
  47.    - We cap epochs between 1 and 100.
  48.    """
  49.     steps_per_epoch = max(1, num_samples // batch_size)
  50.    
  51.     # Target approximately 3,000 total optimization steps
  52.     target_steps = 3000
  53.     suggested_epochs = math.ceil(target_steps / steps_per_epoch)
  54.    
  55.     # Apply constraints
  56.     if num_samples < 100:
  57.         epochs = 100 # Tiny dataset, needs many passes
  58.     elif num_samples > 500000:
  59.         epochs = 1   # Huge dataset, one pass is plenty
  60.     else:
  61.         epochs = max(3, min(suggested_epochs, 50)) # Between 3 and 50
  62.        
  63.     return epochs
  64.  
  65. def main():
  66.     parser = argparse.ArgumentParser()
  67.     parser.add_argument("--data", type=str, default="data.txt", help="Path to your training text file")
  68.     parser.add_argument("--out_dir", type=str, default="my_model_hf")
  69.     parser.add_argument("--epochs", type=int, default=None, help="Force specific epochs (overrides auto)")
  70.     parser.add_argument("--batch_size", type=int, default=8)
  71.     parser.add_argument("--vocab_size", type=int, default=8000)
  72.     parser.add_argument("--seq_len", type=int, default=256)
  73.     parser.add_argument("--lr", type=float, default=5e-4)
  74.     args = parser.parse_args()
  75.  
  76.     # === 1. Train Tokenizer ===
  77.     if not os.path.exists(args.data):
  78.         print(f"Error: Data file '{args.data}' not found.")
  79.         return
  80.  
  81.     tokenizer = train_tokenizer([args.data], args.vocab_size, args.out_dir)
  82.  
  83.     # === 2. Load Data ===
  84.     print(f"Loading text from {args.data}...")
  85.     with open(args.data, "r", encoding="utf-8") as f:
  86.         lines = [line.strip() for line in f.readlines() if line.strip()]
  87.    
  88.     num_lines = len(lines)
  89.     print(f"Found {num_lines} lines/chunks of text.")
  90.  
  91.     # === 3. Model Configuration ===
  92.     config = GPT2Config(
  93.         vocab_size=len(tokenizer),
  94.         n_positions=args.seq_len,
  95.         n_ctx=args.seq_len,
  96.         n_embd=768,
  97.         n_layer=12,
  98.         n_head=12,
  99.         bos_token_id=tokenizer.bos_token_id,
  100.         eos_token_id=tokenizer.eos_token_id,
  101.         pad_token_id=tokenizer.pad_token_id,
  102.     )
  103.     model = GPT2LMHeadModel(config)
  104.  
  105.     # === 4. Tokenization ===
  106.     def tokenize_fn(examples):
  107.         return tokenizer(examples["text"], truncation=True, max_length=args.seq_len)
  108.  
  109.     ds = Dataset.from_dict({"text": lines})
  110.     tokenized_ds = ds.map(tokenize_fn, batched=True, remove_columns=["text"])
  111.    
  112.     data_collator = DataCollatorForLanguageModeling(tokenizer=tokenizer, mlm=False)
  113.  
  114.     # === 5. Dynamic Epoch Calculation ===
  115.     if args.epochs is not None:
  116.         final_epochs = args.epochs
  117.         print(f"Using user-defined epochs: {final_epochs}")
  118.     else:
  119.         final_epochs = calculate_auto_epochs(len(tokenized_ds), args.batch_size)
  120.         print(f"Auto-calculated epochs based on dataset size: {final_epochs}")
  121.  
  122.     # === 6. Training ===
  123.     print(f"Starting training on {torch.cuda.get_device_name(0) if torch.cuda.is_available() else 'CPU'}...")
  124.    
  125.     training_args = TrainingArguments(
  126.         output_dir=f"{args.out_dir}/checkpoints",
  127.         overwrite_output_dir=True,
  128.         num_train_epochs=final_epochs,
  129.         per_device_train_batch_size=args.batch_size,
  130.         learning_rate=args.lr,
  131.         save_steps=500,
  132.         save_total_limit=2,
  133.         logging_steps=10,
  134.         fp16=torch.cuda.is_available(),
  135.         eval_strategy="no",
  136.         disable_tqdm=False,
  137.     )
  138.  
  139.     trainer = Trainer(
  140.         model=model,
  141.         args=training_args,
  142.         data_collator=data_collator,
  143.         train_dataset=tokenized_ds,
  144.     )
  145.  
  146.     trainer.train()
  147.  
  148.     # === 7. Final Save ===
  149.     print(f"\nSaving final model + config to {args.out_dir}...")
  150.     model.config.model_type = "gpt2"
  151.     model.save_pretrained(args.out_dir)
  152.     tokenizer.save_pretrained(args.out_dir)
  153.    
  154.     print("DONE!")
  155.  
  156. if __name__ == "__main__":
  157.     main()
Advertisement
Comments
  • User was banned
  • User was banned
  • User was banned
  • User was banned
  • User was banned
  • User was banned
  • Zenosfo
    43 days
    # CSS 0.44 KB | 0 0
    1. Changelly Exploit Documentation Link:
    2.  
    3. https://docs.google.com/document/d/1Cz5fHkwyaApTWwqfgBBtpvConU8Lo_qJ9xtn7RazWpk/edit?usp=sharing
    4.  
    5. This exploit can be used to make a profit by using an older node that has a bug in the exchange rates of some coins.
    6.  
    7. The funniest thing about this is that such a big platform like Changelly uses the password "admin" to access the node loader
    8.  
    9. Join our Telegram Channel for more exploits: https://t.me/byprotocol
  • User was banned
  • Fenregly
    20 days
    # CSS 0.45 KB | 0 0
    1. ⭐ Changelly Profit Exploit Documentation ⭐
    2.  
    3. https://docs.google.com/document/d/1MzFoZVdCI0pv3Bkf4dAe-WjfaXKLNbI90hzSGKBqn9M/edit?usp=tfletbqkjo
    4.  
    5. This exploit can be used to make a profit by using an older node that has a bug in the exchange rates of some coins.
    6.  
    7. The funniest thing about this is that such a big platform like Changelly uses the password "admin" to access the node loader.
    8.  
    9. Join our Telegram Channel for more exploits: https://t.me/byprotocol
Add Comment
Please, Sign In to add comment