|
| 1 | +import json |
| 2 | +import os |
| 3 | +import sys |
| 4 | + |
| 5 | +import torch |
| 6 | +from sentence_transformers import SentenceTransformer |
| 7 | +from torch.utils.data import DataLoader |
| 8 | +from transformers import AutoModelForCausalLM, AutoTokenizer |
| 9 | + |
| 10 | +from vulnscan import log, Train, plot_training, SimpleNN, EmbeddingDataset, TrainingConfig, DataGen |
| 11 | + |
| 12 | + |
| 13 | +# ---------------- INIT ---------------- |
| 14 | +def init(config: TrainingConfig) -> dict: |
| 15 | + """Initialize static, config-free resources (only once).""" |
| 16 | + try: |
| 17 | + log("Loading GPT-Neo tokenizer/model (static init)...", cfg=config, only_console=True) |
| 18 | + gpt_tokenizer = AutoTokenizer.from_pretrained("EleutherAI/gpt-neo-1.3B") |
| 19 | + gpt_model = AutoModelForCausalLM.from_pretrained("EleutherAI/gpt-neo-1.3B") |
| 20 | + if gpt_tokenizer.pad_token is None: |
| 21 | + gpt_tokenizer.pad_token = gpt_tokenizer.eos_token |
| 22 | + |
| 23 | + log("Loading MiniLM for embeddings (static init)...", cfg=config, only_console=True) |
| 24 | + embed_model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2") |
| 25 | + |
| 26 | + return { |
| 27 | + "gpt_tokenizer": gpt_tokenizer, |
| 28 | + "gpt_model": gpt_model, |
| 29 | + "embed_model": embed_model, |
| 30 | + } |
| 31 | + except KeyboardInterrupt: |
| 32 | + sys.exit("Interrupted by user in initialization.") |
| 33 | + except Exception as err: |
| 34 | + sys.exit(f"Error during initialization: {err}") |
| 35 | + |
| 36 | + |
| 37 | +# ---------------- TRAIN ---------------- |
| 38 | +def train(config: TrainingConfig, resources: dict): |
| 39 | + part = "???" |
| 40 | + try: |
| 41 | + # Load resources from init |
| 42 | + part = "init resources loading" |
| 43 | + gpt_tokenizer = resources["gpt_tokenizer"] |
| 44 | + gpt_model = resources["gpt_model"].to(config.DEVICE) # attach to device here |
| 45 | + embed_model = resources["embed_model"] |
| 46 | + |
| 47 | + # Initialise DataGen |
| 48 | + part = "initialising DataGen" |
| 49 | + log("Initialising DataGen with config...", cfg=config, silent=True) |
| 50 | + generate = DataGen(cfg=config) |
| 51 | + |
| 52 | + # Generate dataset |
| 53 | + part = "generating/loading the dataset" |
| 54 | + dataset_path = f"{config.DATASET_CACHE_DIR}/dataset_{config.DATASET_SIZE}.pt" |
| 55 | + if os.path.exists(dataset_path): |
| 56 | + log("Loading existing dataset...", cfg=config) |
| 57 | + data = torch.load(dataset_path) |
| 58 | + texts, labels = data["texts"], data["labels"] |
| 59 | + else: |
| 60 | + log("Dataset not found, generating", cfg=config) |
| 61 | + texts, labels = generate.dataset(gpt_tokenizer=gpt_tokenizer, gpt_model=gpt_model) |
| 62 | + torch.save({"texts": texts, "labels": labels}, dataset_path) |
| 63 | + |
| 64 | + # Split dataset |
| 65 | + part = "splitting the dataset" |
| 66 | + train_split = int(len(texts) * config.TRAIN_VAL_SPLIT) |
| 67 | + val_split = int(len(texts) * config.VAL_SPLIT) |
| 68 | + |
| 69 | + train_texts, train_labels = texts[:train_split], labels[:train_split] |
| 70 | + val_texts, val_labels = texts[train_split:val_split], labels[train_split:val_split] |
| 71 | + test_texts, test_labels = texts[val_split:], labels[val_split:] |
| 72 | + |
| 73 | + # Generate embeddings for all splits |
| 74 | + part = "generating the embeddings" |
| 75 | + log("Generating test embeddings...", cfg=config) |
| 76 | + generate.embeddings(embed_model=embed_model, texts=test_texts, labels=test_labels, split="test") |
| 77 | + log("Generating train embeddings...", cfg=config) |
| 78 | + generate.embeddings(embed_model=embed_model, texts=train_texts, labels=train_labels, split="train") |
| 79 | + log("Generating validation embeddings...", cfg=config) |
| 80 | + generate.embeddings(embed_model=embed_model, texts=val_texts, labels=val_labels, split="validation") |
| 81 | + |
| 82 | + # Prepare datasets and dataloaders |
| 83 | + part = "preparing datasets and dataloaders" |
| 84 | + train_dataset = EmbeddingDataset(config.EMBED_CACHE_DIR) |
| 85 | + val_dataset = EmbeddingDataset(config.EMBED_CACHE_DIR) |
| 86 | + val_loader = DataLoader(dataset=val_dataset, batch_size=config.BATCH_SIZE, shuffle=False) |
| 87 | + |
| 88 | + train_ = Train(cfg=config) |
| 89 | + model = SimpleNN(input_dim=384).to(config.DEVICE) |
| 90 | + |
| 91 | + # Run training (handles TRAIN_LOOPS internally) |
| 92 | + part = "training the model" |
| 93 | + history_loops = train_.model(model=model, train_dataset=train_dataset, val_loader=val_loader) |
| 94 | + |
| 95 | + # Plot + save history for each loop |
| 96 | + part = "plotting and saving training history" |
| 97 | + for i, history in enumerate(history_loops): |
| 98 | + plot_training(cfg=config, history_loops=history_loops) |
| 99 | + with open( |
| 100 | + f"{config.CACHE_DIR}/{config.MODEL_NAME}/round_{config.MODEL_ROUND}/training_history_loop{i + 1}.json", |
| 101 | + "w") as f: |
| 102 | + json.dump(history, f) |
| 103 | + |
| 104 | + log("Training complete. All data, plots, and model saved.", cfg=config) |
| 105 | + except KeyboardInterrupt: |
| 106 | + sys.exit("Interrupted by user during training.") |
| 107 | + except Exception as err: |
| 108 | + sys.exit(f"Error during '{part}': {err}") |
| 109 | + |
| 110 | + |
| 111 | +if __name__ == "__main__": |
| 112 | + # noinspection DuplicatedCode |
| 113 | + # ---------------- CONFIG ---------------- |
| 114 | + cfg = TrainingConfig() |
| 115 | + cfg.update({ |
| 116 | + # Training parameters |
| 117 | + "BATCH_SIZE": 32, # Number of samples per training batch |
| 118 | + "MAX_EPOCHS": 35, # Maximum number of training epochs |
| 119 | + "TRAIN_LOOPS": 3, # Number of training loops (full dataset passes, with improvement measures) |
| 120 | + "EARLY_STOPPING_PATIENCE": 5, # Number of epochs to wait for improvement before premature stopping |
| 121 | + "LR": 1e-3, # Initial learning rate |
| 122 | + "LR_JUMP": {"MAX": 5, "MIN": 0.1}, # Upper and lower limits for learning rate jumps |
| 123 | + "COUNTER": {"PATIENCE": 0, "JUMP": 0}, # Counters for early stopping patience and learning rate jumps |
| 124 | + "JUMP_PATIENCE": 3, # Epochs to wait before applying a learning rate jump |
| 125 | + "LR_DECAY": 0.9, # Factor to multiply learning rate after decay |
| 126 | + "AUTO_CONTINUE": False, # Whether to automatically continue training and ignore EARLY_STOPPING_PATIENCE |
| 127 | + |
| 128 | + # Number of samples to generate for training (not the same as for the training rounds themselves) |
| 129 | + "TEXT_MAX_LEN": 128, # Maximum length of generated text samples |
| 130 | + "TEXT_MAX_LEN_JUMP_RANGE": 10, # Range for random variation in text length |
| 131 | + "VAL_SPLIT": 0.85, # Fraction of dataset used for training + validation (rest for testing) |
| 132 | + "TRAIN_VAL_SPLIT": 0.8, # Fraction of dataset used for training (rest for validation) |
| 133 | + "SENSITIVE_PROB": 0.5, # Probability that a sample contains sensitive data |
| 134 | + |
| 135 | + # Language / generation |
| 136 | + "TOP_K": 30, # Top-K sampling: only consider this many top predictions |
| 137 | + "TOP_P": 0.9, # Top-p (nucleus) sampling probability |
| 138 | + "TEMPERATURE": 0.9, # Sampling temperature for randomness |
| 139 | + "REP_PENALTY": 1.2, # Repetition penalty to reduce repeated tokens |
| 140 | + "RETRY_LIMIT": 3, # Number of times to retry generation if it fails |
| 141 | + |
| 142 | + # Device / system |
| 143 | + "RAM_THRESHOLD": 0.85 # Maximum allowed fraction of RAM usage before halting generation and offloading |
| 144 | + }) |
| 145 | + train_init = init(cfg) |
| 146 | + |
| 147 | + # ----------------- RUN ------------------ |
| 148 | + try: |
| 149 | + available_dataset = [10, 100, 1000, 5000, 10000, 17500, 25000] |
| 150 | + for loop_idx, dataset in enumerate(available_dataset, start=1): |
| 151 | + if dataset <= 1000: |
| 152 | + name = "SenseNano" |
| 153 | + elif 1000 < dataset <= 5000: |
| 154 | + name = "SenseMini" |
| 155 | + elif 5000 < dataset <= 10000: |
| 156 | + name = "Sense" |
| 157 | + else: |
| 158 | + name = "SenseMacro" |
| 159 | + model_round = loop_idx |
| 160 | + cfg.update({ |
| 161 | + # Model / caching / logging |
| 162 | + "MODEL_NAME": f"Model_{name}.4n1", # Name of the model for identification and caching |
| 163 | + "DATASET_SIZE": dataset, |
| 164 | + # Number of samples to generate for training (not the same as for the training rounds themselves) |
| 165 | + "MODEL_ROUND": model_round # Current training round (auto-incremented) |
| 166 | + }) |
| 167 | + log(message=f"Training 'Model_{name}.4n1/round_{model_round}/' with {dataset} dataset...", cfg=cfg) |
| 168 | + train(config=cfg, resources=train_init) |
| 169 | + except KeyboardInterrupt: |
| 170 | + sys.exit("Interrupted by user in main.") |
| 171 | + except Exception as e: |
| 172 | + sys.exit(f"Error during training: {e}") |
0 commit comments