forked from dleemiller/WordLlama
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrain.py
210 lines (180 loc) · 7.17 KB
/
train.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
# ruff: noqa: E402
import os
# Set environment variables
# os.environ["CUDA_LAUNCH_BLOCKING"] = "1"
os.environ["TORCH_USE_CUDA_DSA"] = "1"
os.environ["TOKENIZERS_PARALLELISM"] = "false"
os.environ["HF_DATASETS_TRUST_REMOTE_CODE"] = "1"
import torch
import tqdm
import safetensors.torch
from datetime import datetime
from pathlib import Path
from sentence_transformers import (
SentenceTransformerTrainingArguments,
SentenceTransformer,
)
from sentence_transformers.training_args import MultiDatasetBatchSamplers
from wordllama import load_training, Config
from wordllama.config import WordLlamaModel
from wordllama.embedding.word_llama_embedding import WordLlamaEmbedding
from wordllama.trainers.reduce_dimension import ReduceDimension
from wordllama.adapters import AvgPool, WeightedProjector, Binarizer
from dataset_loader import load_datasets
class ReduceDimensionConfig:
"""Configuration for Dimension Reduction."""
def __init__(
self,
config_name: str,
saving: bool = False,
binarize: bool = False,
norm: bool = False,
):
self.config = getattr(Config, config_name)
self.config_name = config_name
# Load Matryoshka dimensions from config
self.matryoshka_dims = self.config.matryoshka.dims
# Load tokenizer kwargs from config
self.tokenizer_kwargs = self.config.tokenizer.model_dump()
training_args = self.config.training
self.model_path = f"{config_name}.safetensors"
self.device = "cuda"
self.binarize = binarize
self.binarize_ste = training_args.binarizer_ste
self.norm = norm
self.model = self.build_model()
# Load training datasets
if not saving:
self.training_datasets = load_datasets()
# Load training arguments from config
self.training_args = SentenceTransformerTrainingArguments(
output_dir=f"{training_args.output_dir}_{datetime.now().strftime('%Y-%m-%d_%H-%M-%S')}",
num_train_epochs=training_args.num_train_epochs,
per_device_train_batch_size=training_args.per_device_train_batch_size,
warmup_steps=training_args.warmup_steps,
evaluation_strategy=training_args.evaluation_strategy,
eval_steps=training_args.eval_steps,
save_steps=training_args.save_steps,
fp16=training_args.fp16,
include_num_input_tokens_seen=training_args.include_num_input_tokens_seen,
learning_rate=training_args.learning_rate,
multi_dataset_batch_sampler=(
MultiDatasetBatchSamplers.PROPORTIONAL
if training_args.multi_dataset_batch_sampler == "PROPORTIONAL"
else MultiDatasetBatchSamplers.ROUND_ROBIN
),
)
def build_model(self) -> SentenceTransformer:
wl = load_training(self.model_path, self.config)
wl.tokenizer_kwargs = self.tokenizer_kwargs
max_dim = max(self.matryoshka_dims)
# setup modules for sentence transformer
# best results using weighted projector
modules = [
wl,
WeightedProjector(
self.config.model.dim,
max_dim,
tokenizer=wl.tokenizer,
n_vocab=self.config.model.n_vocab,
),
AvgPool(norm=self.norm),
]
# if binarizing, set
if self.binarize:
modules.append(Binarizer(ste=self.binarize_ste))
# train
return SentenceTransformer(modules=modules, device=self.device)
def save(self, checkpoint: Path, outdir: Path):
"""
Saves model reduced model weights for each dimension in matryoshka_dims.
"""
wl = load_training(self.model_path, self.config).eval()
# load the projector weights
max_dim = max(self.matryoshka_dims)
proj_path = (
checkpoint / "1_WeightedProjector" / "weighted_projector.safetensors"
)
proj = WeightedProjector(
self.config.model.dim,
max_dim,
n_vocab=self.config.model.n_vocab,
tokenizer=wl.tokenizer,
)
safetensors.torch.load_model(proj, proj_path)
# inference the trained model
with torch.no_grad():
x = proj(
{
"token_embeddings": wl.embedding.weight,
"token_ids": torch.arange(self.config.model.n_vocab),
}
)
for dims in tqdm.tqdm(self.matryoshka_dims):
class TmpConfig:
model = WordLlamaModel(
n_vocab=self.config.model.n_vocab,
dim=dims,
hf_model_id=self.config.model.hf_model_id,
pad_token=self.config.model.pad_token,
)
target = WordLlamaEmbedding(TmpConfig)
# truncate the matryoshka embedding dimension to the target
target.embedding.weight = torch.nn.Parameter(x["x"][:, 0:dims])
# save file
outfile = outdir / f"{self.config_name}_{dims}.safetensors"
print(f"Saving to: {outfile}")
safetensors.torch.save_model(target.half(), outfile)
if __name__ == "__main__":
import argparse
# Set up the argument parser
parser = argparse.ArgumentParser(
description="Train a weighted projection model using sentence transformers and Matryoshka Embeddings"
)
subparsers = parser.add_subparsers(dest="command", help="Sub-command help")
# Add a sub-parser for the 'train' command
parser_train = subparsers.add_parser("train", help="Train the model")
parser_train.add_argument(
"--config",
type=str,
required=True,
help="Name of your configuration (eg. [your_config].toml)",
)
parser_train.add_argument(
"--binarize",
action="store_true",
default=False,
help="Train with binarization using straight through estimator",
)
parser_train.add_argument(
"--norm", action="store_true", default=False, help="Norm after pooling"
)
# Add a sub-parser for the 'save' command
parser_save = subparsers.add_parser("save", help="Save the model")
parser_save.add_argument(
"--config",
type=str,
required=True,
help="Name of your configuration (eg. [your_config].toml)",
)
parser_save.add_argument(
"--checkpoint", type=str, required=True, help="Path to the checkpoint"
)
parser_save.add_argument(
"--outdir", type=str, required=True, help="Directory to save the models"
)
# Parse the arguments
args = parser.parse_args()
config_name = args.config
# Execute based on the command
if args.command == "train":
config = ReduceDimensionConfig(
config_name, binarize=args.binarize, norm=args.norm
)
trainer = ReduceDimension(config)
trainer.train()
elif args.command == "save":
config = ReduceDimensionConfig(config_name, saving=True)
config.save(checkpoint=Path(args.checkpoint), outdir=Path(args.outdir))
else:
parser.print_help()