simon-pltk commited on
Commit
17bde88
·
verified ·
1 Parent(s): ae2f80d

Upload folder using huggingface_hub

Browse files
README.md ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: pytorch
3
+ tags:
4
+ - gpt2
5
+ - prontoqa
6
+ - latent-reasoning
7
+ - chain-of-thought
8
+ - distillation
9
+ - codi
10
+ license: mit
11
+ ---
12
+
13
+ # CODI — GPT-2 ProntoQA (Latent Reasoning)
14
+
15
+ A **CODI** (Chain-of-thought Distillation) model trained on ProntoQA for latent
16
+ chain-of-thought reasoning. The model wraps GPT-2 with LoRA adapters and a
17
+ distillation objective that compresses explicit chain-of-thought steps into
18
+ latent embeddings.
19
+
20
+ ## Quick Start
21
+
22
+ ```bash
23
+ pip install transformers peft huggingface_hub torch
24
+ ```
25
+
26
+ ```python
27
+ from huggingface_hub import snapshot_download
28
+ import sys
29
+
30
+ # Download the model
31
+ local_dir = snapshot_download("simon-pltk/codi-gpt2-prontoqa-latent")
32
+
33
+ # Load it
34
+ sys.path.insert(0, local_dir)
35
+ from load_model import load_codi_model
36
+
37
+ model = load_codi_model(local_dir, device="cuda")
38
+ ```
39
+
40
+ ## Architecture
41
+
42
+ CODI is a custom `torch.nn.Module` that:
43
+
44
+ 1. Wraps a base GPT-2 model loaded via `AutoModelForCausalLM`
45
+ 2. Applies LoRA adapters (rank=128, alpha=16) for parameter-efficient tuning
46
+ 3. Generates latent embeddings that replace explicit chain-of-thought tokens
47
+ 4. Uses a layer-wise distillation loss (SmoothL1) to align the student
48
+ (latent) representations with a teacher (explicit CoT) across all layers
49
+
50
+ ## Training Details
51
+
52
+ | Parameter | Value |
53
+ |-----------|-------|
54
+ | Base model | GPT-2 (124M) |
55
+ | Dataset | ProntoQA |
56
+ | Epochs | 50 |
57
+ | Learning rate | 0.003 |
58
+ | Seed | 11 |
59
+ | Num latent tokens | 5 |
60
+ | LoRA rank | 128 |
61
+ | Distill loss | SmoothL1 |
62
+
63
+ ### Final Metrics
64
+
65
+ | Metric | Start | End |
66
+ |--------|-------|-----|
67
+ | CE Loss | 6.6610 | 0.1202 |
68
+ | Distill Loss | 0.2742 | 0.0759 |
69
+ | Ref CE Loss | 1.5432 | 0.0113 |
70
+ | Total Loss | 8.4784 | 0.1931 |
71
+
72
+ ## Files
73
+
74
+ | File | Description |
75
+ |------|-------------|
76
+ | `pytorch_model.bin` | Full CODI state dict (base model + LoRA + projection) |
77
+ | `model.py` | CODI class definition and dataclass configs |
78
+ | `load_model.py` | **Entrypoint** — helper to reconstruct and load the model |
79
+ | `codi_config.json` | Model metadata and training hyperparameters |
80
+ | `training_args.bin` | Original HuggingFace TrainingArguments |
added_tokens.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ {
2
+ "[PAD]": 50257
3
+ }
codi_config.json ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model_type": "codi",
3
+ "base_model": "gpt2",
4
+ "architecture": "CODI",
5
+ "description": "Custom CODI wrapper around GPT-2 with LoRA, projection layers, and distillation for latent chain-of-thought reasoning on ProntoQA.",
6
+ "training_details": {
7
+ "dataset": "ProntoQA",
8
+ "epochs": 50,
9
+ "learning_rate": 0.003,
10
+ "seed": 11,
11
+ "num_latent": 5,
12
+ "final_ce_loss": 0.1202,
13
+ "final_distill_loss": 0.0759,
14
+ "final_ref_ce_loss": 0.0113,
15
+ "final_total_loss": 0.1931
16
+ }
17
+ }
load_model.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Entrypoint for loading the CODI model from this repository.
3
+
4
+ Usage:
5
+ from huggingface_hub import snapshot_download
6
+ local_dir = snapshot_download("YOUR_USERNAME/codi-gpt2-prontoqa-latent")
7
+
8
+ import sys
9
+ sys.path.insert(0, local_dir)
10
+ from load_model import load_codi_model
11
+
12
+ model = load_codi_model(local_dir, device="cuda")
13
+ """
14
+ import os
15
+ import torch
16
+ from huggingface_hub import snapshot_download
17
+ from model import CODI, ModelArguments, TrainingArguments
18
+ from peft import LoraConfig
19
+
20
+
21
+ def load_codi_model(repo_id_or_path, device="cuda", dtype=torch.float16):
22
+ """
23
+ Load a CODI model from a HuggingFace repo or local directory.
24
+
25
+ Args:
26
+ repo_id_or_path: HF repo id (e.g. "user/repo") or local directory path.
27
+ device: Device to load the model on.
28
+ dtype: Data type for the model weights.
29
+
30
+ Returns:
31
+ CODI model with loaded weights, in eval mode.
32
+ """
33
+ # Download if needed
34
+ if os.path.isdir(repo_id_or_path):
35
+ local_dir = repo_id_or_path
36
+ else:
37
+ print(f"Downloading from {repo_id_or_path}...")
38
+ local_dir = snapshot_download(repo_id=repo_id_or_path)
39
+
40
+ weights_path = os.path.join(local_dir, "pytorch_model.bin")
41
+
42
+ # Reconstruct the model with the same args used during training
43
+ model_args = ModelArguments(
44
+ model_name_or_path="gpt2",
45
+ train=False,
46
+ full_precision=True,
47
+ )
48
+
49
+ training_args = TrainingArguments(
50
+ output_dir="./tmp",
51
+ num_latent=5,
52
+ use_lora=True,
53
+ use_prj=False,
54
+ bf16=False,
55
+ fix_attn_mask=False,
56
+ print_loss=False,
57
+ distill_loss_type="smooth_l1",
58
+ distill_loss_factor=1.0,
59
+ ref_loss_factor=1.0,
60
+ )
61
+
62
+ lora_config = LoraConfig(
63
+ r=128,
64
+ lora_alpha=16,
65
+ lora_dropout=0.05,
66
+ target_modules=["c_attn", "c_proj", "c_fc"], # GPT-2 attention modules
67
+ )
68
+
69
+ # Build the model skeleton, then load trained weights
70
+ model = CODI(model_args, training_args, lora_config)
71
+
72
+ print(f"Loading weights from {weights_path}...")
73
+ state_dict = torch.load(weights_path, map_location="cpu")
74
+ model.load_state_dict(state_dict)
75
+
76
+ model = model.to(device=device, dtype=dtype)
77
+ model.eval()
78
+ print("Model loaded successfully.")
79
+ return model
80
+
81
+
82
+ if __name__ == "__main__":
83
+ import sys
84
+ repo = sys.argv[1] if len(sys.argv) > 1 else "."
85
+ model = load_codi_model(repo)
86
+ print(f"Model type: {type(model).__name__}")
87
+ print(f"Parameters: {sum(p.numel() for p in model.parameters()):,}")
merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
model.py ADDED
@@ -0,0 +1,411 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import transformers
2
+ from transformers import AutoModelForCausalLM, AutoTokenizer, AutoConfig, GPTNeoXForCausalLM
3
+ import os
4
+ import torch
5
+ import torch.nn as nn
6
+ import torch.nn.functional as F
7
+ import random
8
+ from dataclasses import dataclass, field
9
+ from typing import Optional
10
+ from peft import (
11
+ get_peft_model,
12
+ PeftModel,
13
+ PeftConfig
14
+ )
15
+ from torch.nn.functional import gelu
16
+ import math
17
+ from safetensors.torch import load_file
18
+ from transformers.modeling_outputs import ModelOutput
19
+ import random
20
+ import copy
21
+
22
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
23
+
24
+
25
+ @dataclass
26
+ class ModelArguments:
27
+ model_name_or_path: str = field(default="mistralai/Mistral-7B-Instruct-v0.2")
28
+ separate_decoder_name: str = field(default="")
29
+ lora_r: int = field(default=128, metadata={"help": "lora rank"})
30
+ lora_dropout: float = field(default=0.05, metadata={"help": "lora dropout"})
31
+ full_precision: bool = field(default=True, metadata={"help": "whether use int4 for the base model"})
32
+ train: bool = field(
33
+ default=True,
34
+ metadata={
35
+ "help": "if true, the model ckpt will be initialized for training; else, it's for inference"
36
+ },
37
+ )
38
+ lora_init: bool = field(
39
+ default=False,
40
+ metadata={"help": "True: Use zero and gaussian initialization; False: Load adapters from LoftQ in HF hub."},
41
+ )
42
+ token: Optional[str] = field(
43
+ default=None,
44
+ metadata={"help": "HF token to access to private models, e.g., meta-llama"},
45
+ )
46
+ adapter_name_or_path: Optional[str] = field(
47
+ default=None,
48
+ metadata={"help": "Path to the LoRA adapter. Used in evaluation or resuming from the checkpoint."},
49
+ )
50
+ lora_alpha: int = field(
51
+ default=16,
52
+ metadata={"help": "LoftQ does not require this config. Used for QLoRA."},
53
+ )
54
+ ckpt_dir: Optional[str] = field(default=None, metadata={"help": "checkpoint dir for inference."})
55
+
56
+ @dataclass
57
+ class DataArguments:
58
+ data_name: str = field(
59
+ default=None, metadata={"help": "Path to the training data."}
60
+ )
61
+ debug_data: bool = field(
62
+ default=False,
63
+ metadata={
64
+ "help": "Enable debug dataset to quickly verify the training process"
65
+ },
66
+ )
67
+ batch_size: int = field(default=1, metadata={"help": "batch size during inference"})
68
+
69
+ @dataclass
70
+ class TrainingArguments(transformers.TrainingArguments):
71
+ cache_dir: Optional[str] = field(default=None)
72
+ optim: str = field(default="adamw_torch")
73
+ model_max_length: int = field(
74
+ default=28000,
75
+ metadata={
76
+ "help": "Maximum sequence length. Sequences will be right padded (and possibly truncated)."
77
+ },
78
+ )
79
+ restore_from: str = field(
80
+ default="",
81
+ metadata={
82
+ "help": "The checkpoint that should be restored from for fine-tuning"
83
+ },
84
+ )
85
+ per_device_train_batch_size: int = field(
86
+ default=1,
87
+ )
88
+ per_device_eval_batch_size: int = field(
89
+ default=1,
90
+ )
91
+ expt_name: str = field(
92
+ default="default",
93
+ metadata={"help": "Experiment name"},
94
+ )
95
+ icot_train_path: str = field(default="/users/k24020023/efficient_cot/icae/code/coconut/icot_gsm8k/train.txt", metadata={"help":"The training data path"})
96
+ num_latent: int = field(default=5, metadata={"help": "The number of latent for training or inference."})
97
+ use_lora: bool = field(default=True, metadata={"help": "Use lora or not."})
98
+ greedy: bool = field(default=False, metadata={"help": "Greedy decoding during inference."})
99
+ exp_mode: bool = field(default=False, metadata={"help": "Use partial number of data. for debugging."})
100
+ exp_data_num: int = field(default=10000, metadata={"help": "The number of data used in exp mode"})
101
+ use_prj: bool = field(default=False, metadata={"help": "Use a prj module after the llm for latent generation."})
102
+ prj_dim: int = field(default=2048, metadata={"help": "The hidden dim of the projection module."})
103
+ prj_dropout: float = field(default=0.0, metadata={"help": "Dropout ratio of the projection module."})
104
+ prj_no_ln: bool = field(default=False, metadata={"help": "Remove the Layer Norm layer for the projection module."})
105
+ distill_loss_div_std: bool = field(default=False, metadata={"help": "Divide the distillation loss by a std for normallisation."})
106
+ distill_loss_type: str = field(default="smooth_l1", metadata={"help": "Specify the distillation loss. Use smoothL1 by default."})
107
+ distill_loss_factor: float = field(default=1.0, metadata={"help": "A multiplier of the distillation loss."})
108
+ ref_loss_factor: float = field(default=1.0, metadata={"help": "A multiplier of the distillation loss."})
109
+ inf_latent_iterations: int = field(default=1, metadata={"help": ""})
110
+ inf_num_iterations: int = field(default=5, metadata={"help": "Run multiple times during inference"})
111
+ remove_eos: bool = field(default=False, metadata={"help": "Do not add <eos> as a delimiter to split QA."})
112
+ print_ref_model_stats: bool = field(default=False, metadata={"help": "Print some stats for the teacher task."})
113
+ include_last_cot: bool = field(default=False, metadata={"help": "Include the last CoT step in the training data."})
114
+ fix_attn_mask: bool = field(default=False, metadata={"help": "Correct a bug about attention mask."})
115
+ log_full: bool = field(default=False, metadata={"help": "Log all losses."})
116
+ print_loss: bool = field(default=True)
117
+ max_token_num: int = field(default=1000, metadata={"help": "Limit the longest data to avoid OOM."})
118
+
119
+ def print_trainable_parameters(model):
120
+ trainable_parameters = 0
121
+ all_param = 0
122
+ for _, param in model.named_parameters():
123
+ all_param += param.numel()
124
+ if param.requires_grad:
125
+ trainable_parameters += param.numel()
126
+ print(
127
+ f"trainable params: {trainable_parameters} || all params: {all_param} || trainable%: {100 * trainable_parameters / all_param}"
128
+ )
129
+ # for name, param in model.named_parameters():
130
+ # if param.requires_grad:
131
+ # print(name, param.shape)
132
+
133
+
134
+ def freeze_model(model):
135
+ for _, param in model.named_parameters():
136
+ param.requires_grad = False
137
+
138
+ class CODI(torch.nn.Module):
139
+ def __init__(self, model_args, training_args, lora_config):
140
+ super().__init__()
141
+ self.model_args = model_args
142
+ self.training_args = training_args
143
+ self.model_name = model_args.model_name_or_path
144
+ model_wrapper_class = AutoModelForCausalLM
145
+ if model_args.full_precision:
146
+ self.codi = model_wrapper_class.from_pretrained(
147
+ self.model_name,
148
+ torch_dtype=(
149
+ torch.float16 if training_args.bf16 is False else torch.bfloat16
150
+ ),
151
+ use_flash_attention_2=False,
152
+ resume_download=True,
153
+ )
154
+ else:
155
+ self.codi = model_wrapper_class.from_pretrained(
156
+ self.model_name,
157
+ torch_dtype=(
158
+ torch.float16 if training_args.bf16 is False else torch.bfloat16
159
+ ),
160
+ use_flash_attention_2=False,
161
+ resume_download=True,
162
+ quantization_config=transformers.BitsAndBytesConfig(
163
+ load_in_4bit=True,
164
+ bnb_4bit_compute_dtype=torch.bfloat16,
165
+ bnb_4bit_use_double_quant=False,
166
+ bnb_4bit_quant_type='nf4',
167
+ )
168
+ )
169
+
170
+
171
+ ori_vocab_size = self.codi.config.vocab_size
172
+ self.training = self.model_args.train
173
+
174
+ # special tokens to enclose the latent embeddings
175
+ self.pad_token_id = ori_vocab_size
176
+ self.bot_id = ori_vocab_size + 1
177
+ self.eot_id = ori_vocab_size + 2
178
+
179
+ self.codi.resize_token_embeddings(
180
+ ori_vocab_size + 3
181
+ ) # dummy values for mem tokens
182
+
183
+ self.dim = self.codi.config.hidden_size
184
+ self.num_latent = training_args.num_latent
185
+ self.tokenizer = AutoTokenizer.from_pretrained(self.model_name, use_fast=False)
186
+
187
+ # LoRA
188
+ if training_args.use_lora:
189
+ self.codi = get_peft_model(self.codi, lora_config)
190
+
191
+ # Projection Layer
192
+ self.use_prj = training_args.use_prj
193
+ self.prj_no_ln = training_args.prj_no_ln
194
+ if training_args.use_prj:
195
+ self.prj = nn.Sequential(
196
+ nn.Dropout(training_args.prj_dropout),
197
+ nn.Linear(self.dim, training_args.prj_dim),
198
+ nn.GELU(),
199
+ nn.Linear(training_args.prj_dim, self.dim),
200
+ )
201
+ if not self.prj_no_ln:
202
+ self.prj.add_module("ln", nn.LayerNorm(self.dim))
203
+
204
+ # Losses
205
+ self.print_loss = training_args.print_loss
206
+ self.ref_loss_factor = training_args.ref_loss_factor
207
+
208
+ # Cross Entropy Loss
209
+ self.loss_fct = nn.CrossEntropyLoss(ignore_index=-100)
210
+
211
+ # Distillation Loss
212
+ self.distill_loss_div_std = training_args.distill_loss_div_std
213
+ self.distill_loss_type = training_args.distill_loss_type
214
+ self.distill_loss_factor = training_args.distill_loss_factor
215
+ if self.distill_loss_type == "smooth_l1":
216
+ self.distill_loss_fct = nn.SmoothL1Loss()
217
+ elif self.distill_loss_type == "l2":
218
+ self.distill_loss_fct = nn.MSELoss()
219
+ else:
220
+ raise NotImplementedError
221
+
222
+ # general
223
+ self.fix_attn_mask = training_args.fix_attn_mask
224
+
225
+ if self.tokenizer.pad_token_id is None:
226
+ self.tokenizer.add_special_tokens({'pad_token': '[PAD]'})
227
+ self.tokenizer.pad_token_id = self.pad_token_id
228
+
229
+ if self.training:
230
+ self.init()
231
+
232
+ def get_embd(self, model, model_name):
233
+ try:
234
+ if "pythia" in model_name:
235
+ return model.get_base_model().gpt_neox.embed_in
236
+ elif "gpt2" in model_name:
237
+ try:
238
+ return model.get_base_model().transformer.wte
239
+ except Exception: # no lora
240
+ return model.transformer.wte
241
+ else:
242
+ try:
243
+ return model.get_base_model().model.embed_tokens
244
+ except Exception: # no lora
245
+ return model.model.embed_tokens
246
+ except AttributeError:
247
+ if "pythia" in model_name:
248
+ return model.gpt_neox.embed_in
249
+ raise NotImplementedError
250
+
251
+ def init(self):
252
+ print_trainable_parameters(self)
253
+ if (
254
+ self.training_args.restore_from is not None
255
+ and self.training_args.restore_from != ""
256
+ ):
257
+ print(
258
+ f"Loading from the pretrained checkpoint: {self.training_args.restore_from}..."
259
+ )
260
+ state_dict = load_file(self.training_args.restore_from)
261
+ self.load_state_dict(state_dict)
262
+ print(f"Finished loading from {self.training_args.restore_from}")
263
+
264
+ def forward(
265
+ self,
266
+ encoder_input_ids: torch.LongTensor = None,
267
+ decoder_input_ids: torch.LongTensor = None,
268
+ ref_input_ids: torch.LongTensor = None,
269
+ labels: Optional[torch.LongTensor] = None,
270
+ encoder_attention_mask: Optional[torch.LongTensor] = None,
271
+ ref_answer_position: Optional[torch.LongTensor] = None,
272
+ model_answer_position: Optional[torch.LongTensor] = None,
273
+ ref_attention_mask: Optional[torch.LongTensor] = None,
274
+ ref_labels: torch.LongTensor = None,
275
+ step: int = None,
276
+ step_ratio: float = None
277
+ ):
278
+ if not self.fix_attn_mask:
279
+ ref_attention_mask = None
280
+
281
+ # Encode the question
282
+ past_key_values = None
283
+ outputs = self.codi(input_ids=encoder_input_ids, use_cache=True, output_hidden_states=True, past_key_values=past_key_values, attention_mask=encoder_attention_mask)
284
+ past_key_values = outputs.past_key_values
285
+ latent_embd = outputs.hidden_states[-1][:, -1, :].unsqueeze(1) # as the next input
286
+ if self.use_prj:
287
+ latent_embd = self.prj(latent_embd)
288
+
289
+ len_pred_loss = 0
290
+ dynamic_mask = None
291
+ if self.fix_attn_mask:
292
+ dynamic_mask = torch.ones((encoder_attention_mask.size(0), self.num_latent), device=ref_labels.device)
293
+
294
+ # Iterate over the latent embeddings
295
+ distill_loss_total = 0
296
+ ce_loss_total = 0
297
+
298
+ with torch.no_grad():
299
+ ref_outputs = self.codi(input_ids=ref_input_ids, output_hidden_states=True, attention_mask=ref_attention_mask)
300
+ ref_outputs_with_grad = self.codi(input_ids=ref_input_ids, output_hidden_states=True, attention_mask=ref_attention_mask)
301
+
302
+ # Formatting for deprecated exps
303
+ ref_outputs_list = [ref_outputs]
304
+ ref_input_ids = [ref_input_ids]
305
+
306
+ # Process the position tensor
307
+ # Normalise the position definition
308
+ if "llama" in self.model_name.lower() or "qwen" in self.model_name.lower(): # there is one more token standing for " "
309
+ model_answer_position = model_answer_position + 1
310
+ ref_answer_position = ref_answer_position + 1
311
+
312
+ # For DEBUG: Print the probability of the teacher task to predict the correct answer
313
+ if self.training_args.print_ref_model_stats:
314
+ for i, (ref_inputs, ref_outputs) in enumerate(zip(ref_input_ids, ref_outputs_list)):
315
+ # evalutae the reference model
316
+ if len(ref_outputs_list) > 1:
317
+ pos = ref_answer_position[i]
318
+ else:
319
+ pos = ref_answer_position
320
+ ref_probs = torch.nn.functional.softmax(ref_outputs.logits, dim=-1)
321
+ input_positions = (pos-1).unsqueeze(1).unsqueeze(1).expand(-1, -1, ref_probs.size(2))
322
+ ref_probs_at_positions = ref_probs.gather(1, input_positions)
323
+ probe_positions_positions = pos.unsqueeze(1)
324
+ probe_positions = ref_inputs.gather(1, probe_positions_positions).unsqueeze(1)
325
+ ref_probs_of_target = ref_probs_at_positions.gather(2, probe_positions)
326
+ print(f'stage{i}: mean of the prob of the target token: {ref_probs_of_target.mean()}')
327
+
328
+ # the model answer position is the position of the eot token to predict the first token of the response
329
+ model_answer_position = model_answer_position - 1
330
+ ref_answer_position = ref_answer_position -1
331
+
332
+ num_latent = self.num_latent
333
+ if self.num_latent != 0:
334
+ for i in range(num_latent):
335
+ # Implicit CoT generation
336
+ outputs = self.codi(inputs_embeds=latent_embd, use_cache=True, output_hidden_states=True, past_key_values=past_key_values)
337
+ past_key_values = outputs.past_key_values
338
+ latent_embd = outputs.hidden_states[-1][:, -1, :].unsqueeze(1)
339
+ if self.use_prj:
340
+ latent_embd = self.prj(latent_embd)
341
+
342
+ # Calculate the distillation loss
343
+ if i == num_latent - 1: # the last latent embedding
344
+ # Decode the final answer in natural language
345
+ embds = self.get_embd(self.codi, self.model_name)(decoder_input_ids)
346
+
347
+ if dynamic_mask is not None: # Prevent attending the paddings
348
+ decoder_mask = torch.ones((embds.size(0), embds.size(1)), dtype=torch.bool).to(dynamic_mask)
349
+ dynamic_mask = torch.cat((encoder_attention_mask, dynamic_mask, decoder_mask), dim=1)
350
+ dynamic_mask = dynamic_mask.bool()
351
+ # Student task's output
352
+ outputs = self.codi(inputs_embeds=embds, use_cache=True, output_hidden_states=True, past_key_values=past_key_values, attention_mask=dynamic_mask)
353
+ # Teacher task's output
354
+ ref_outputs = ref_outputs_list[0]
355
+
356
+ distill_loss = 0
357
+ # Calculate distillation loss between the teacher's logits and the student's logits for every layer
358
+ for j, (out, ref_out) in enumerate(zip(outputs.hidden_states, ref_outputs.hidden_states)):
359
+ ref_selected = ref_out.gather(1, ref_answer_position.unsqueeze(-1).unsqueeze(-1).expand(-1, -1, ref_out.size(-1)))
360
+ out_selected = out.gather(1, model_answer_position.unsqueeze(-1).unsqueeze(-1).expand(-1, -1, out.size(-1)))
361
+
362
+ distill_loss_tmp = self.distill_loss_fct(out_selected, ref_selected.detach())
363
+
364
+ if self.distill_loss_div_std:
365
+ if self.distill_loss_type == 'l2':
366
+ distill_loss_tmp /= ref_selected.std()
367
+ distill_loss_tmp /= ref_selected.std()
368
+ distill_loss += distill_loss_tmp
369
+
370
+ distill_loss /= len(outputs.hidden_states)
371
+
372
+ if self.print_loss:
373
+ print(f'latent{i}: distill_loss={distill_loss}')
374
+
375
+ distill_loss_total += distill_loss
376
+
377
+ # Calculate the CE loss for the student task
378
+ if i == num_latent - 1:
379
+ logits = outputs.logits
380
+ effective_logits = logits[:, :-1, :]
381
+ effective_logits = effective_logits.reshape(-1, logits.size(-1))
382
+ target_ids = labels[:, 1:].reshape(-1)
383
+ ce_loss = self.loss_fct(effective_logits, target_ids)
384
+ ce_loss_total += ce_loss
385
+
386
+ # Calculate the CE loss for the teacher task
387
+ ref_ce_loss = 0
388
+ ref_logits = ref_outputs_with_grad.logits
389
+ effective_ref_logits = ref_logits[:, :-1, :]
390
+ effective_ref_logits = effective_ref_logits.reshape(-1, ref_logits.size(-1))
391
+ ref_target_ids = ref_labels[:, 1:].reshape(-1)
392
+ ref_ce_loss = self.loss_fct(effective_ref_logits, ref_target_ids)
393
+ ref_ce_loss *= self.ref_loss_factor
394
+
395
+ # Weigh the distillation loss
396
+ distill_loss *= self.distill_loss_factor
397
+ distill_loss_total *= self.distill_loss_factor
398
+
399
+ if self.print_loss:
400
+ print(f'loss={ce_loss+distill_loss}, ce_loss={ce_loss}, distill_loss={distill_loss}, ce_loss_total={ce_loss_total}, distill_loss_total={distill_loss_total}, ref_ce_loss={ref_ce_loss}')
401
+
402
+ loss = ce_loss_total + distill_loss_total + ref_ce_loss
403
+
404
+ if ce_loss_total != 0:
405
+ ce_loss_total = ce_loss_total.detach().item()
406
+ if distill_loss_total != 0:
407
+ distill_loss_total = distill_loss_total.detach().item()
408
+ if ref_ce_loss != 0:
409
+ ref_ce_loss = ref_ce_loss.detach().item()
410
+
411
+ return {"loss": loss, "logits": logits, "ce_loss": ce_loss_total, "distill_loss": distill_loss_total, "ref_ce_loss": ref_ce_loss}
pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b399a1000c5275b7939ca0672061ae91d0c637012a25cc281217c9a0f6fcb5e3
3
+ size 329256651
special_tokens_map.json ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": {
3
+ "content": "<|endoftext|>",
4
+ "lstrip": false,
5
+ "normalized": true,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "eos_token": {
10
+ "content": "<|endoftext|>",
11
+ "lstrip": false,
12
+ "normalized": true,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "pad_token": "[PAD]",
17
+ "unk_token": {
18
+ "content": "<|endoftext|>",
19
+ "lstrip": false,
20
+ "normalized": true,
21
+ "rstrip": false,
22
+ "single_word": false
23
+ }
24
+ }
tokenizer_config.json ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": false,
3
+ "add_prefix_space": false,
4
+ "added_tokens_decoder": {
5
+ "50256": {
6
+ "content": "<|endoftext|>",
7
+ "lstrip": false,
8
+ "normalized": true,
9
+ "rstrip": false,
10
+ "single_word": false,
11
+ "special": true
12
+ },
13
+ "50257": {
14
+ "content": "[PAD]",
15
+ "lstrip": false,
16
+ "normalized": false,
17
+ "rstrip": false,
18
+ "single_word": false,
19
+ "special": true
20
+ }
21
+ },
22
+ "bos_token": "<|endoftext|>",
23
+ "clean_up_tokenization_spaces": false,
24
+ "eos_token": "<|endoftext|>",
25
+ "errors": "replace",
26
+ "extra_special_tokens": {},
27
+ "model_max_length": 512,
28
+ "pad_token": "[PAD]",
29
+ "padding_side": "right",
30
+ "tokenizer_class": "GPT2Tokenizer",
31
+ "unk_token": "<|endoftext|>"
32
+ }
trainer_state.json ADDED
The diff for this file is too large to render. See raw diff
 
training_args.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:759a19e15bacb7fcae6046d2b00d253e71a9056799e5007110ca8a4659d34ce2
3
+ size 6481
vocab.json ADDED
The diff for this file is too large to render. See raw diff