PeytonT commited on
Commit
d67f29d
·
verified ·
1 Parent(s): 2d58866

Upload folder using huggingface_hub

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +20 -0
  2. README.md +40 -0
  3. parquet/snippets.parquet +3 -0
  4. source_snippets/AgentLab.jsonl +0 -0
  5. source_snippets/BOLAA.jsonl +0 -0
  6. source_snippets/BrowserGym.jsonl +0 -0
  7. source_snippets/CREMA.jsonl +0 -0
  8. source_snippets/CUDALibrarySamples.jsonl +0 -0
  9. source_snippets/CodeT.jsonl +0 -0
  10. source_snippets/ConfidenceTransformer.jsonl +25 -0
  11. source_snippets/Cross-Scale-MAE.jsonl +0 -0
  12. source_snippets/DMOSpeech2.jsonl +0 -0
  13. source_snippets/Digital-World-Model.jsonl +0 -0
  14. source_snippets/EE-LLM.jsonl +0 -0
  15. source_snippets/EfficientDynamic3DGaussian.jsonl +0 -0
  16. source_snippets/Fuser.jsonl +0 -0
  17. source_snippets/GPTeacher.jsonl +3 -0
  18. source_snippets/Human3R.jsonl +0 -0
  19. source_snippets/LLaMA-Adapter.jsonl +0 -0
  20. source_snippets/Learning-with-Holographic-Reduced-Representations.jsonl +0 -0
  21. source_snippets/M2PT.jsonl +20 -0
  22. source_snippets/Mediapipe-VR-Fullbody-Tracking.jsonl +0 -0
  23. source_snippets/Megatron-Energon.jsonl +0 -0
  24. source_snippets/Megatron-LM.jsonl +3 -0
  25. source_snippets/MetaGPT.jsonl +0 -0
  26. source_snippets/MetaMathQA.jsonl +0 -0
  27. source_snippets/MoE-LLaVA.jsonl +0 -0
  28. source_snippets/Model-Optimizer.jsonl +3 -0
  29. source_snippets/ModuleFormer.jsonl +0 -0
  30. source_snippets/OSWorld.jsonl +3 -0
  31. source_snippets/OneFormer.jsonl +0 -0
  32. source_snippets/OpenAgents.jsonl +0 -0
  33. source_snippets/OpenStrawberry.jsonl +0 -0
  34. source_snippets/OpenWebVoyager.jsonl +3 -0
  35. source_snippets/Program_Conditioned_Adapter.jsonl +0 -0
  36. source_snippets/Python.jsonl +3 -0
  37. source_snippets/SuperAlignment.jsonl +33 -0
  38. source_snippets/TOLBERT.jsonl +0 -0
  39. source_snippets/TaskMatrix.jsonl +0 -0
  40. source_snippets/TensorRT-LLM.jsonl +3 -0
  41. source_snippets/TinyRecursiveModels.jsonl +0 -0
  42. source_snippets/Track-Anything.jsonl +0 -0
  43. source_snippets/TransformerEngine.jsonl +3 -0
  44. source_snippets/WorkArena.jsonl +0 -0
  45. source_snippets/abliterator.jsonl +0 -0
  46. source_snippets/action-transformer-environment.jsonl +0 -0
  47. source_snippets/action-transformer.jsonl +0 -0
  48. source_snippets/agent-knowledge-generator.jsonl +0 -0
  49. source_snippets/arrow_multitask.jsonl +10 -0
  50. source_snippets/augmentoolkit.jsonl +0 -0
.gitattributes CHANGED
@@ -58,3 +58,23 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
58
  # Video files - compressed
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58
  # Video files - compressed
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
61
+ source_snippets/Megatron-LM.jsonl filter=lfs diff=lfs merge=lfs -text
62
+ source_snippets/Model-Optimizer.jsonl filter=lfs diff=lfs merge=lfs -text
63
+ source_snippets/OSWorld.jsonl filter=lfs diff=lfs merge=lfs -text
64
+ source_snippets/OpenWebVoyager.jsonl filter=lfs diff=lfs merge=lfs -text
65
+ source_snippets/Python.jsonl filter=lfs diff=lfs merge=lfs -text
66
+ source_snippets/TensorRT-LLM.jsonl filter=lfs diff=lfs merge=lfs -text
67
+ source_snippets/TransformerEngine.jsonl filter=lfs diff=lfs merge=lfs -text
68
+ source_snippets/cpython.jsonl filter=lfs diff=lfs merge=lfs -text
69
+ source_snippets/cuda-quantum.jsonl filter=lfs diff=lfs merge=lfs -text
70
+ source_snippets/cutlass.jsonl filter=lfs diff=lfs merge=lfs -text
71
+ source_snippets/jax.jsonl filter=lfs diff=lfs merge=lfs -text
72
+ source_snippets/linux.jsonl filter=lfs diff=lfs merge=lfs -text
73
+ source_snippets/llama-stack.jsonl filter=lfs diff=lfs merge=lfs -text
74
+ source_snippets/model-stack.jsonl filter=lfs diff=lfs merge=lfs -text
75
+ source_snippets/nvmath-python.jsonl filter=lfs diff=lfs merge=lfs -text
76
+ source_snippets/peft.jsonl filter=lfs diff=lfs merge=lfs -text
77
+ source_snippets/pytorch.jsonl filter=lfs diff=lfs merge=lfs -text
78
+ source_snippets/tilus.jsonl filter=lfs diff=lfs merge=lfs -text
79
+ source_snippets/transformers.jsonl filter=lfs diff=lfs merge=lfs -text
80
+ source_snippets/unilm.jsonl filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: other
3
+ task_categories:
4
+ - text-generation
5
+ language:
6
+ - code
7
+ pretty_name: Repository Code Snippets
8
+ ---
9
+
10
+ # Repository Code Snippets
11
+
12
+ Focused source-code snippets for static repository graph browsing.
13
+
14
+ Rows are keyed by `repo_id` and `entity_id`, matching the public repo graph
15
+ entity ids. Each row contains a focused source span plus surrounding context,
16
+ not a complete repository dump.
17
+
18
+ ## Columns
19
+
20
+ - `repo_id`
21
+ - `entity_id`
22
+ - `uri`
23
+ - `kind`
24
+ - `name`
25
+ - `path`
26
+ - `language`
27
+ - `start_line`
28
+ - `end_line`
29
+ - `context_start_line`
30
+ - `context_end_line`
31
+ - `code`
32
+ - `source_hash`
33
+ - `truncated`
34
+
35
+ ## Stats
36
+
37
+ - snippets: `468,268`
38
+ - skipped entities: `437,756`
39
+ - repos: `155`
40
+ - generated at: `1777152029`
parquet/snippets.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4c8416854b0cd30bfdc60361b4c62eeb3d0cc4bf645304a244f44220fb9e6400
3
+ size 122787179
source_snippets/AgentLab.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
source_snippets/BOLAA.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
source_snippets/BrowserGym.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
source_snippets/CREMA.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
source_snippets/CUDALibrarySamples.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
source_snippets/CodeT.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
source_snippets/ConfidenceTransformer.jsonl ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {"repo_id":"ConfidenceTransformer","entity_id":"py:eval","uri":"program://ConfidenceTransformer/module/eval#L1-L79","kind":"module","name":"eval","path":"eval.py","language":"python","start_line":1,"end_line":79,"context_start_line":1,"context_end_line":79,"code":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom transformers import GPT2Tokenizer, GPT2LMHeadModel, GPT2Model\nfrom datasets import load_dataset\nfrom main import ConfidenceEnhancedTransformer # Import the class from main.py\n\n# Load the trained model and tokenizer\nmodel_name = 'confidence_model'\nmodel_path = model_name\ntokenizer_path = model_name\ntokenizer = GPT2Tokenizer.from_pretrained(tokenizer_path)\n\nmodel = ConfidenceEnhancedTransformer.from_pretrained(model_path, attn_implementation=\"eager\")\n\n# Move model to GPU if available\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\nmodel.to(device)\n\n# Set the model to evaluation mode\nmodel.eval()\n\n# Load the WikiText-2 dataset\ndataset = load_dataset('wikitext', 'wikitext-2-raw-v1', split='train')\n\n# Ensure the example text is not empty and preprocess it\nexample_text = dataset['text'][3].strip() # Get the first example from the dataset and strip whitespace\nif not example_text:\n raise ValueError(\"The example text from the dataset is empty. Please check the dataset.\")\n\n# Example usage\nif __name__ == \"__main__\":\n prompt = \"tefewafwef aoasdfsfasdfsadfdfasdsdijfoiwej\"\n inputs = tokenizer(prompt, return_tensors='pt').to(device)\n \n # Check if input_ids is empty\n if inputs.input_ids.size(1) == 0:\n raise ValueError(\"The input text resulted in an empty input_ids tensor. Please check the input text.\")\n \n with torch.no_grad():\n outputs = model(\n input_ids=inputs.input_ids,\n attention_mask=inputs.attention_mask,\n num_dropout_samples=10 # Increased from 5 to 10\n )\n # Get the confidence score\n confidence_score = outputs['confidence_score'].item()\n ood_score = outputs['ood_score'].item()\n print(f\"Refined Confidence Score: {confidence_score}\")\n print(f\"OOD Score: {ood_score}\")\n\n # Decode and print the generated text (not part of the confidence mechanism)\n generated_text = tokenizer.decode(outputs['lm_logits'].argmax(-1).squeeze().tolist())\n print(f\"OOD example: {prompt}\")\n print(f\"Generated Text: {generated_text}\")\n\n # Evaluate on an in-distribution example from WikiText-2\n inputs = tokenizer(example_text, return_tensors='pt').to(device)\n \n # Check if input_ids is empty\n if inputs.input_ids.size(1) == 0:\n raise ValueError(\"The example text resulted in an empty input_ids tensor. Please check the example text.\")\n \n with torch.no_grad():\n outputs = model(\n input_ids=inputs.input_ids,\n attention_mask=inputs.attention_mask,\n num_dropout_samples=10\n )\n # Get the confidence score for the in-distribution example\n confidence_score = outputs['confidence_score'].item()\n ood_score = outputs['ood_score'].item()\n print(f\"In-Distribution Example - Refined Confidence Score: {confidence_score}\")\n print(f\"In-Distribution Example - OOD Score: {ood_score}\")\n\n # Decode and print the generated text for the in-distribution example\n generated_text = tokenizer.decode(outputs['lm_logits'].argmax(-1).squeeze().tolist())\n print(f\"example text: {example_text}\")\n print(f\"In-Distribution Example - Generated Text: {generated_text}\")","source_hash":"3578bf0e13cd974bc6904184ebfe9ffbf435d2522c4e913c4c68d1f6dc98ef44","truncated":false}
2
+ {"repo_id":"ConfidenceTransformer","entity_id":"py:main","uri":"program://ConfidenceTransformer/module/main#L1-L135","kind":"module","name":"main","path":"main.py","language":"python","start_line":1,"end_line":135,"context_start_line":1,"context_end_line":135,"code":"import torch\nimport torch.nn as nn\nfrom transformers import GPT2LMHeadModel, GPT2Model, GPT2Tokenizer\nimport torch.nn.functional as F\n\nclass ConfidenceEnhancedTransformer(GPT2LMHeadModel):\n def __init__(self, config):\n super(ConfidenceEnhancedTransformer, self).__init__(config)\n self.transformer = GPT2Model(config)\n #self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False) # Language modeling head\n\n # Confidence scoring head for epistemic uncertainty and OOD detection\n self.confidence_head = nn.Sequential(\n nn.Linear(config.n_embd, 128),\n nn.ReLU(),\n nn.Linear(128, 1), # Single output for confidence score\n nn.Sigmoid() # Confidence score between 0 and 1\n )\n \n # OOD detector head\n self.ood_detector = nn.Linear(config.n_embd, 1) # Auxiliary head for OOD detection\n self.init_weights()\n\n def forward(self, input_ids, attention_mask=None, labels=None, num_dropout_samples=10):\n # Standard forward pass through transformer\n outputs = super().forward(\n input_ids=input_ids,\n attention_mask=attention_mask,\n labels=labels,\n output_attentions=True,\n output_hidden_states=True,\n return_dict=True,\n )\n lm_logits = outputs.logits # [batch_size, sequence_length, vocab_size]\n hidden_states = outputs.hidden_states[-1] # Get the last hidden state\n attentions = outputs.attentions # Attention weights\n\n # Base confidence score from hidden states\n base_confidence_score = self.confidence_head(hidden_states.mean(dim=1))\n\n # Attention-based confidence signal\n attention_entropy = []\n for attn_layer in attentions:\n attn_probs = attn_layer.mean(dim=1) # Mean over heads\n attn_entropy = -torch.sum(attn_probs * torch.log(attn_probs + 1e-12), dim=-1)\n attention_entropy.append(attn_entropy.mean(dim=-1)) # Mean over tokens\n avg_attention_entropy = torch.stack(attention_entropy).mean(dim=0) # Mean over layers\n\n # Monte Carlo Dropout for variance estimation\n variance_confidence = 0.0\n dropout_scores = []\n if num_dropout_samples > 1:\n original_mode = self.training # Save original mode\n self.train() # Enable dropout layers\n for _ in range(num_dropout_samples):\n # Removed torch.no_grad() to ensure dropout behaves correctly\n dropout_outputs = super().forward(\n input_ids=input_ids,\n attention_mask=attention_mask,\n output_hidden_states=True,\n return_dict=True,\n )\n dropout_hidden_states = dropout_outputs.hidden_states[-1]\n dropout_confidence = self.confidence_head(dropout_hidden_states.mean(dim=1))\n dropout_scores.append(dropout_confidence)\n \n self.train(original_mode) # Restore original mode\n # Calculate variance of dropout predictions as a confidence measure\n dropout_scores = torch.stack(dropout_scores) # [num_samples, batch_size, 1]\n variance_confidence = torch.var(dropout_scores, dim=0).mean()\n else:\n variance_confidence = torch.tensor(0.0).to(hidden_states.device)\n\n # OOD detection score\n ood_score = torch.sigmoid(self.ood_detector(hidden_states.mean(dim=1))).squeeze()\n\n # Adjust this line to handle ood_score shape correctly\n if len(ood_score.shape) == 0:\n ood_score = ood_score.unsqueeze(0) # Add batch dimension if it's a scalar\n\n # Combine all signals into a refined confidence score\n refined_confidence_score = (\n base_confidence_score \n - variance_confidence # Lower confidence if high variance\n - avg_attention_entropy.unsqueeze(1) # Lower confidence if high attention entropy\n - ood_score.unsqueeze(1) # Lower confidence if high OOD score\n ).clamp(0, 1) # Ensure the final score is between 0 and 1\n\n # Calculate total loss if labels are provided\n total_loss = None\n if labels is not None:\n # Language modeling loss\n shift_logits = lm_logits[..., :-1, :].contiguous()\n shift_labels = labels[..., 1:].contiguous()\n lm_loss = nn.CrossEntropyLoss()(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))\n\n # Entropy-based confidence loss\n token_probs = F.softmax(shift_logits, dim=-1)\n entropy = -torch.sum(token_probs * torch.log(token_probs + 1e-12), dim=-1).mean(dim=-1)\n confidence_loss = nn.MSELoss()(base_confidence_score.squeeze(), 1 - entropy)\n\n # OOD loss\n ood_loss = nn.BCELoss()(ood_score, torch.zeros_like(ood_score)) # Penalty for high OOD score\n\n # Combine all losses with adjusted weights\n total_loss = lm_loss + 0.5 * confidence_loss + 0.3 * ood_loss # Increased weights\n\n return {\n 'loss': total_loss,\n 'lm_logits': lm_logits,\n 'confidence_score': refined_confidence_score, # Refined confidence score\n 'ood_score': ood_score, # Out-of-distribution score\n 'base_confidence_score': base_confidence_score.squeeze(), # Added for logging\n 'variance_confidence': variance_confidence, # Added for logging\n 'avg_attention_entropy': avg_attention_entropy # Added for logging\n }\n\n# Example usage of the model\ntokenizer = GPT2Tokenizer.from_pretrained('gpt2')\nmodel = ConfidenceEnhancedTransformer.from_pretrained('gpt2', attn_implementation='eager')\n\n# Example input\ninput_text = \"What is the capital of USA?\"\ninput_tokens = tokenizer(input_text, return_tensors=\"pt\")\noutputs = model(input_tokens['input_ids'], num_dropout_samples=10)\n\n# Get the confidence score\nconfidence_score = outputs['confidence_score'].item()\nood_score = outputs['ood_score'].item()\nprint(f\"Refined Confidence Score: {confidence_score}\")\nprint(f\"OOD Score: {ood_score}\")\n\n# Decode and print the generated text (not part of the confidence mechanism)\ngenerated_text = tokenizer.decode(outputs['lm_logits'].argmax(-1).squeeze().tolist())\nprint(f\"Generated Text: {generated_text}\")","source_hash":"0bf4a6d8cb4435d83ba0509db804e4c03aefa41e5e87fca50ffea0cd28079b65","truncated":false}
3
+ {"repo_id":"ConfidenceTransformer","entity_id":"py:main.ConfidenceEnhancedTransformer","uri":"program://ConfidenceTransformer/class/main.ConfidenceEnhancedTransformer#L6-L116","kind":"class","name":"ConfidenceEnhancedTransformer","path":"main.py","language":"python","start_line":6,"end_line":116,"context_start_line":1,"context_end_line":135,"code":"import torch\nimport torch.nn as nn\nfrom transformers import GPT2LMHeadModel, GPT2Model, GPT2Tokenizer\nimport torch.nn.functional as F\n\nclass ConfidenceEnhancedTransformer(GPT2LMHeadModel):\n def __init__(self, config):\n super(ConfidenceEnhancedTransformer, self).__init__(config)\n self.transformer = GPT2Model(config)\n #self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False) # Language modeling head\n\n # Confidence scoring head for epistemic uncertainty and OOD detection\n self.confidence_head = nn.Sequential(\n nn.Linear(config.n_embd, 128),\n nn.ReLU(),\n nn.Linear(128, 1), # Single output for confidence score\n nn.Sigmoid() # Confidence score between 0 and 1\n )\n \n # OOD detector head\n self.ood_detector = nn.Linear(config.n_embd, 1) # Auxiliary head for OOD detection\n self.init_weights()\n\n def forward(self, input_ids, attention_mask=None, labels=None, num_dropout_samples=10):\n # Standard forward pass through transformer\n outputs = super().forward(\n input_ids=input_ids,\n attention_mask=attention_mask,\n labels=labels,\n output_attentions=True,\n output_hidden_states=True,\n return_dict=True,\n )\n lm_logits = outputs.logits # [batch_size, sequence_length, vocab_size]\n hidden_states = outputs.hidden_states[-1] # Get the last hidden state\n attentions = outputs.attentions # Attention weights\n\n # Base confidence score from hidden states\n base_confidence_score = self.confidence_head(hidden_states.mean(dim=1))\n\n # Attention-based confidence signal\n attention_entropy = []\n for attn_layer in attentions:\n attn_probs = attn_layer.mean(dim=1) # Mean over heads\n attn_entropy = -torch.sum(attn_probs * torch.log(attn_probs + 1e-12), dim=-1)\n attention_entropy.append(attn_entropy.mean(dim=-1)) # Mean over tokens\n avg_attention_entropy = torch.stack(attention_entropy).mean(dim=0) # Mean over layers\n\n # Monte Carlo Dropout for variance estimation\n variance_confidence = 0.0\n dropout_scores = []\n if num_dropout_samples > 1:\n original_mode = self.training # Save original mode\n self.train() # Enable dropout layers\n for _ in range(num_dropout_samples):\n # Removed torch.no_grad() to ensure dropout behaves correctly\n dropout_outputs = super().forward(\n input_ids=input_ids,\n attention_mask=attention_mask,\n output_hidden_states=True,\n return_dict=True,\n )\n dropout_hidden_states = dropout_outputs.hidden_states[-1]\n dropout_confidence = self.confidence_head(dropout_hidden_states.mean(dim=1))\n dropout_scores.append(dropout_confidence)\n \n self.train(original_mode) # Restore original mode\n # Calculate variance of dropout predictions as a confidence measure\n dropout_scores = torch.stack(dropout_scores) # [num_samples, batch_size, 1]\n variance_confidence = torch.var(dropout_scores, dim=0).mean()\n else:\n variance_confidence = torch.tensor(0.0).to(hidden_states.device)\n\n # OOD detection score\n ood_score = torch.sigmoid(self.ood_detector(hidden_states.mean(dim=1))).squeeze()\n\n # Adjust this line to handle ood_score shape correctly\n if len(ood_score.shape) == 0:\n ood_score = ood_score.unsqueeze(0) # Add batch dimension if it's a scalar\n\n # Combine all signals into a refined confidence score\n refined_confidence_score = (\n base_confidence_score \n - variance_confidence # Lower confidence if high variance\n - avg_attention_entropy.unsqueeze(1) # Lower confidence if high attention entropy\n - ood_score.unsqueeze(1) # Lower confidence if high OOD score\n ).clamp(0, 1) # Ensure the final score is between 0 and 1\n\n # Calculate total loss if labels are provided\n total_loss = None\n if labels is not None:\n # Language modeling loss\n shift_logits = lm_logits[..., :-1, :].contiguous()\n shift_labels = labels[..., 1:].contiguous()\n lm_loss = nn.CrossEntropyLoss()(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))\n\n # Entropy-based confidence loss\n token_probs = F.softmax(shift_logits, dim=-1)\n entropy = -torch.sum(token_probs * torch.log(token_probs + 1e-12), dim=-1).mean(dim=-1)\n confidence_loss = nn.MSELoss()(base_confidence_score.squeeze(), 1 - entropy)\n\n # OOD loss\n ood_loss = nn.BCELoss()(ood_score, torch.zeros_like(ood_score)) # Penalty for high OOD score\n\n # Combine all losses with adjusted weights\n total_loss = lm_loss + 0.5 * confidence_loss + 0.3 * ood_loss # Increased weights\n\n return {\n 'loss': total_loss,\n 'lm_logits': lm_logits,\n 'confidence_score': refined_confidence_score, # Refined confidence score\n 'ood_score': ood_score, # Out-of-distribution score\n 'base_confidence_score': base_confidence_score.squeeze(), # Added for logging\n 'variance_confidence': variance_confidence, # Added for logging\n 'avg_attention_entropy': avg_attention_entropy # Added for logging\n }\n\n# Example usage of the model\ntokenizer = GPT2Tokenizer.from_pretrained('gpt2')\nmodel = ConfidenceEnhancedTransformer.from_pretrained('gpt2', attn_implementation='eager')\n\n# Example input\ninput_text = \"What is the capital of USA?\"\ninput_tokens = tokenizer(input_text, return_tensors=\"pt\")\noutputs = model(input_tokens['input_ids'], num_dropout_samples=10)\n\n# Get the confidence score\nconfidence_score = outputs['confidence_score'].item()\nood_score = outputs['ood_score'].item()\nprint(f\"Refined Confidence Score: {confidence_score}\")\nprint(f\"OOD Score: {ood_score}\")\n\n# Decode and print the generated text (not part of the confidence mechanism)\ngenerated_text = tokenizer.decode(outputs['lm_logits'].argmax(-1).squeeze().tolist())\nprint(f\"Generated Text: {generated_text}\")","source_hash":"0bf4a6d8cb4435d83ba0509db804e4c03aefa41e5e87fca50ffea0cd28079b65","truncated":false}
4
+ {"repo_id":"ConfidenceTransformer","entity_id":"py:main.__init__","uri":"program://ConfidenceTransformer/function/main.__init__#L7-L22","kind":"function","name":"__init__","path":"main.py","language":"python","start_line":7,"end_line":22,"context_start_line":1,"context_end_line":42,"code":"import torch\nimport torch.nn as nn\nfrom transformers import GPT2LMHeadModel, GPT2Model, GPT2Tokenizer\nimport torch.nn.functional as F\n\nclass ConfidenceEnhancedTransformer(GPT2LMHeadModel):\n def __init__(self, config):\n super(ConfidenceEnhancedTransformer, self).__init__(config)\n self.transformer = GPT2Model(config)\n #self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False) # Language modeling head\n\n # Confidence scoring head for epistemic uncertainty and OOD detection\n self.confidence_head = nn.Sequential(\n nn.Linear(config.n_embd, 128),\n nn.ReLU(),\n nn.Linear(128, 1), # Single output for confidence score\n nn.Sigmoid() # Confidence score between 0 and 1\n )\n \n # OOD detector head\n self.ood_detector = nn.Linear(config.n_embd, 1) # Auxiliary head for OOD detection\n self.init_weights()\n\n def forward(self, input_ids, attention_mask=None, labels=None, num_dropout_samples=10):\n # Standard forward pass through transformer\n outputs = super().forward(\n input_ids=input_ids,\n attention_mask=attention_mask,\n labels=labels,\n output_attentions=True,\n output_hidden_states=True,\n return_dict=True,\n )\n lm_logits = outputs.logits # [batch_size, sequence_length, vocab_size]\n hidden_states = outputs.hidden_states[-1] # Get the last hidden state\n attentions = outputs.attentions # Attention weights\n\n # Base confidence score from hidden states\n base_confidence_score = self.confidence_head(hidden_states.mean(dim=1))\n\n # Attention-based confidence signal\n attention_entropy = []","source_hash":"0bf4a6d8cb4435d83ba0509db804e4c03aefa41e5e87fca50ffea0cd28079b65","truncated":false}
5
+ {"repo_id":"ConfidenceTransformer","entity_id":"py:main.forward","uri":"program://ConfidenceTransformer/function/main.forward#L24-L116","kind":"function","name":"forward","path":"main.py","language":"python","start_line":24,"end_line":116,"context_start_line":4,"context_end_line":135,"code":"import torch.nn.functional as F\n\nclass ConfidenceEnhancedTransformer(GPT2LMHeadModel):\n def __init__(self, config):\n super(ConfidenceEnhancedTransformer, self).__init__(config)\n self.transformer = GPT2Model(config)\n #self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False) # Language modeling head\n\n # Confidence scoring head for epistemic uncertainty and OOD detection\n self.confidence_head = nn.Sequential(\n nn.Linear(config.n_embd, 128),\n nn.ReLU(),\n nn.Linear(128, 1), # Single output for confidence score\n nn.Sigmoid() # Confidence score between 0 and 1\n )\n \n # OOD detector head\n self.ood_detector = nn.Linear(config.n_embd, 1) # Auxiliary head for OOD detection\n self.init_weights()\n\n def forward(self, input_ids, attention_mask=None, labels=None, num_dropout_samples=10):\n # Standard forward pass through transformer\n outputs = super().forward(\n input_ids=input_ids,\n attention_mask=attention_mask,\n labels=labels,\n output_attentions=True,\n output_hidden_states=True,\n return_dict=True,\n )\n lm_logits = outputs.logits # [batch_size, sequence_length, vocab_size]\n hidden_states = outputs.hidden_states[-1] # Get the last hidden state\n attentions = outputs.attentions # Attention weights\n\n # Base confidence score from hidden states\n base_confidence_score = self.confidence_head(hidden_states.mean(dim=1))\n\n # Attention-based confidence signal\n attention_entropy = []\n for attn_layer in attentions:\n attn_probs = attn_layer.mean(dim=1) # Mean over heads\n attn_entropy = -torch.sum(attn_probs * torch.log(attn_probs + 1e-12), dim=-1)\n attention_entropy.append(attn_entropy.mean(dim=-1)) # Mean over tokens\n avg_attention_entropy = torch.stack(attention_entropy).mean(dim=0) # Mean over layers\n\n # Monte Carlo Dropout for variance estimation\n variance_confidence = 0.0\n dropout_scores = []\n if num_dropout_samples > 1:\n original_mode = self.training # Save original mode\n self.train() # Enable dropout layers\n for _ in range(num_dropout_samples):\n # Removed torch.no_grad() to ensure dropout behaves correctly\n dropout_outputs = super().forward(\n input_ids=input_ids,\n attention_mask=attention_mask,\n output_hidden_states=True,\n return_dict=True,\n )\n dropout_hidden_states = dropout_outputs.hidden_states[-1]\n dropout_confidence = self.confidence_head(dropout_hidden_states.mean(dim=1))\n dropout_scores.append(dropout_confidence)\n \n self.train(original_mode) # Restore original mode\n # Calculate variance of dropout predictions as a confidence measure\n dropout_scores = torch.stack(dropout_scores) # [num_samples, batch_size, 1]\n variance_confidence = torch.var(dropout_scores, dim=0).mean()\n else:\n variance_confidence = torch.tensor(0.0).to(hidden_states.device)\n\n # OOD detection score\n ood_score = torch.sigmoid(self.ood_detector(hidden_states.mean(dim=1))).squeeze()\n\n # Adjust this line to handle ood_score shape correctly\n if len(ood_score.shape) == 0:\n ood_score = ood_score.unsqueeze(0) # Add batch dimension if it's a scalar\n\n # Combine all signals into a refined confidence score\n refined_confidence_score = (\n base_confidence_score \n - variance_confidence # Lower confidence if high variance\n - avg_attention_entropy.unsqueeze(1) # Lower confidence if high attention entropy\n - ood_score.unsqueeze(1) # Lower confidence if high OOD score\n ).clamp(0, 1) # Ensure the final score is between 0 and 1\n\n # Calculate total loss if labels are provided\n total_loss = None\n if labels is not None:\n # Language modeling loss\n shift_logits = lm_logits[..., :-1, :].contiguous()\n shift_labels = labels[..., 1:].contiguous()\n lm_loss = nn.CrossEntropyLoss()(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))\n\n # Entropy-based confidence loss\n token_probs = F.softmax(shift_logits, dim=-1)\n entropy = -torch.sum(token_probs * torch.log(token_probs + 1e-12), dim=-1).mean(dim=-1)\n confidence_loss = nn.MSELoss()(base_confidence_score.squeeze(), 1 - entropy)\n\n # OOD loss\n ood_loss = nn.BCELoss()(ood_score, torch.zeros_like(ood_score)) # Penalty for high OOD score\n\n # Combine all losses with adjusted weights\n total_loss = lm_loss + 0.5 * confidence_loss + 0.3 * ood_loss # Increased weights\n\n return {\n 'loss': total_loss,\n 'lm_logits': lm_logits,\n 'confidence_score': refined_confidence_score, # Refined confidence score\n 'ood_score': ood_score, # Out-of-distribution score\n 'base_confidence_score': base_confidence_score.squeeze(), # Added for logging\n 'variance_confidence': variance_confidence, # Added for logging\n 'avg_attention_entropy': avg_attention_entropy # Added for logging\n }\n\n# Example usage of the model\ntokenizer = GPT2Tokenizer.from_pretrained('gpt2')\nmodel = ConfidenceEnhancedTransformer.from_pretrained('gpt2', attn_implementation='eager')\n\n# Example input\ninput_text = \"What is the capital of USA?\"\ninput_tokens = tokenizer(input_text, return_tensors=\"pt\")\noutputs = model(input_tokens['input_ids'], num_dropout_samples=10)\n\n# Get the confidence score\nconfidence_score = outputs['confidence_score'].item()\nood_score = outputs['ood_score'].item()\nprint(f\"Refined Confidence Score: {confidence_score}\")\nprint(f\"OOD Score: {ood_score}\")\n\n# Decode and print the generated text (not part of the confidence mechanism)\ngenerated_text = tokenizer.decode(outputs['lm_logits'].argmax(-1).squeeze().tolist())\nprint(f\"Generated Text: {generated_text}\")","source_hash":"0bf4a6d8cb4435d83ba0509db804e4c03aefa41e5e87fca50ffea0cd28079b65","truncated":false}
6
+ {"repo_id":"ConfidenceTransformer","entity_id":"py:train","uri":"program://ConfidenceTransformer/module/train#L1-L214","kind":"module","name":"train","path":"train.py","language":"python","start_line":1,"end_line":214,"context_start_line":1,"context_end_line":214,"code":"import torch\nfrom torch.utils.data import Dataset, DataLoader\nfrom transformers import GPT2Tokenizer, get_linear_schedule_with_warmup\nfrom tqdm import tqdm\nimport torch.optim as optim\nfrom datasets import load_dataset\nfrom main import ConfidenceEnhancedTransformer\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nnum_epochs = 3\nsave_steps = 500 # Save the model every 500 steps\n\n# Define a custom dataset\nclass TextDataset(Dataset):\n def __init__(self, tokenizer, texts, block_size=128):\n self.examples = []\n\n for text in texts:\n tokenized_text = tokenizer.encode(text)\n for i in range(0, len(tokenized_text) - block_size + 1, block_size):\n self.examples.append(\n torch.tensor(tokenized_text[i:i + block_size], dtype=torch.long)\n )\n\n def __len__(self):\n return len(self.examples)\n\n def __getitem__(self, i):\n return self.examples[i]\n\n# Load tokenizer and model\ntokenizer = GPT2Tokenizer.from_pretrained('gpt2')\nmodel = ConfidenceEnhancedTransformer.from_pretrained('gpt2')\n\n# Load the WikiText-2 dataset\ndataset = load_dataset('wikitext', 'wikitext-2-raw-v1', split='train')\ntexts = dataset['text']\n\n# Split the dataset into training and validation sets\ntrain_texts, val_texts = train_test_split(texts, test_size=0.1, random_state=42)\n\n# Prepare datasets\ntrain_dataset = TextDataset(\n tokenizer=tokenizer,\n texts=train_texts,\n block_size=128\n)\nval_dataset = TextDataset(\n tokenizer=tokenizer,\n texts=val_texts,\n block_size=128\n)\n\n# Create DataLoaders\ntrain_dataloader = DataLoader(train_dataset, batch_size=4, shuffle=True)\nval_dataloader = DataLoader(val_dataset, batch_size=4, shuffle=False)\n\n# Prepare optimizer and scheduler\noptimizer = optim.AdamW(model.parameters(), lr=5e-5)\ntotal_steps = len(train_dataloader) * num_epochs\nscheduler = get_linear_schedule_with_warmup(\n optimizer,\n num_warmup_steps=0,\n num_training_steps=total_steps\n)\n\n# Move model to GPU if available\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\nmodel.to(device)\n\n# Define ECE computation function\ndef compute_ece(preds, confidences, n_bins=10):\n bin_boundaries = np.linspace(0, 1, n_bins + 1)\n ece = 0.0\n for i in range(n_bins):\n bin_lower = bin_boundaries[i]\n bin_upper = bin_boundaries[i + 1]\n in_bin = (confidences > bin_lower) & (confidences <= bin_upper)\n prop_in_bin = np.mean(in_bin)\n if prop_in_bin > 0:\n accuracy_in_bin = np.mean(preds[in_bin] == preds[in_bin]) # Adjust based on your prediction mechanism\n avg_confidence_in_bin = np.mean(confidences[in_bin])\n ece += np.abs(avg_confidence_in_bin - accuracy_in_bin) * prop_in_bin\n return ece\n\n# Define Reliability Diagram function\ndef reliability_diagram(confidences, predictions, n_bins=10):\n bin_boundaries = np.linspace(0, 1, n_bins + 1)\n bin_centers = (bin_boundaries[:-1] + bin_boundaries[1:]) / 2\n accuracy = np.zeros(n_bins)\n confidence = np.zeros(n_bins)\n prop = np.zeros(n_bins)\n\n for i in range(n_bins):\n in_bin = (confidences > bin_boundaries[i]) & (confidences <= bin_boundaries[i + 1])\n prop[i] = np.mean(in_bin)\n if prop[i] > 0:\n accuracy[i] = np.mean(predictions[in_bin] == predictions[in_bin]) # Replace with actual labels\n confidence[i] = np.mean(confidences[in_bin])\n\n plt.figure(figsize=(8, 6))\n plt.plot(bin_centers, accuracy, marker='o', label='Accuracy')\n plt.plot(bin_centers, confidence, marker='s', label='Confidence')\n plt.fill_between(bin_boundaries[:-1], 0, 1, color='gray', alpha=0.1)\n plt.xlabel('Confidence')\n plt.ylabel('Accuracy')\n plt.legend()\n plt.title('Reliability Diagram')\n plt.show()\n\n# Training loop\nmodel.train()\nglobal_step = 0\nfor epoch in range(num_epochs):\n print(f\"Epoch {epoch + 1}/{num_epochs}\")\n epoch_loss = 0\n for batch in tqdm(train_dataloader):\n inputs = batch.to(device)\n labels = inputs.clone()\n\n optimizer.zero_grad()\n\n outputs = model(\n input_ids=inputs,\n labels=labels,\n num_dropout_samples=15 # You can adjust this number\n )\n loss = outputs['loss']\n loss.backward()\n\n # Check gradients for confidence_head and ood_detector\n for name, param in model.named_parameters():\n if 'confidence_head' in name or 'ood_detector' in name:\n if param.grad is not None:\n print(f\"Gradient for {name}: {param.grad.mean().item()}\")\n\n optimizer.step()\n scheduler.step()\n\n epoch_loss += loss.item()\n global_step += 1\n\n # Log intermediate values for debugging\n base_confidence_score = outputs['base_confidence_score'].mean().item()\n variance_confidence = outputs['variance_confidence'].item()\n avg_attention_entropy = outputs['avg_attention_entropy'].mean().item()\n ood_score = outputs['ood_score'].mean().item()\n\n print(f\"Step {global_step}: Loss = {loss.item():.4f}, \"\n f\"Base Confidence Score = {base_confidence_score:.4f}, \"\n f\"Variance Confidence = {variance_confidence:.4f}, \"\n f\"Avg Attention Entropy = {avg_attention_entropy:.4f}, \"\n f\"OOD Score = {ood_score:.4f}\")\n\n # Save the model every 500 steps\n if global_step % save_steps == 0:\n model.save_pretrained(f'model_step_{global_step}.pth')\n tokenizer.save_pretrained(f'tokenizer_step_{global_step}.pth')\n\n avg_train_loss = epoch_loss / len(train_dataloader)\n print(f\"Average Training Loss: {avg_train_loss:.4f}\")\n\n # Validation phase\n model.eval()\n val_loss = 0\n all_val_preds = []\n all_val_confidences = []\n with torch.no_grad():\n for val_batch in tqdm(val_dataloader, desc=\"Validation\"):\n val_inputs = val_batch.to(device)\n val_labels = val_inputs.clone()\n\n val_outputs = model(\n input_ids=val_inputs,\n labels=val_labels,\n num_dropout_samples=15\n )\n val_loss += val_outputs['loss'].item()\n\n # Collect predictions and confidence scores for calibration\n val_confidences = val_outputs['base_confidence_score'].cpu().numpy()\n # Assuming you're using the model's logits to derive predictions\n val_logits = val_outputs['logits']\n val_preds = torch.argmax(val_logits, dim=-1).cpu().numpy()\n all_val_preds.extend(val_preds.flatten())\n all_val_confidences.extend(val_confidences.flatten())\n\n avg_val_loss = val_loss / len(val_dataloader)\n print(f\"Average Validation Loss after Epoch {epoch + 1}: {avg_val_loss:.4f}\")\n\n # Calculate ECE\n ece = compute_ece(\n preds=np.array(all_val_preds),\n confidences=np.array(all_val_confidences),\n n_bins=10\n )\n print(f\"Expected Calibration Error (ECE) after Epoch {epoch + 1}: {ece:.4f}\")\n\n # Plot Reliability Diagram\n reliability_diagram(\n confidences=np.array(all_val_confidences),\n predictions=np.array(all_val_preds),\n n_bins=10\n )\n\n # Reset model to training mode\n model.train()\n\n# Save the final trained model\nmodel.save_pretrained('confidence_model')\ntokenizer.save_pretrained('confidence_model')","source_hash":"fca41099ce250271c231f639b57270deadda7aaebce2cdea10a73247db8e086b","truncated":false}
7
+ {"repo_id":"ConfidenceTransformer","entity_id":"py:train.TextDataset","uri":"program://ConfidenceTransformer/class/train.TextDataset#L17-L32","kind":"class","name":"TextDataset","path":"train.py","language":"python","start_line":17,"end_line":32,"context_start_line":1,"context_end_line":52,"code":"import torch\nfrom torch.utils.data import Dataset, DataLoader\nfrom transformers import GPT2Tokenizer, get_linear_schedule_with_warmup\nfrom tqdm import tqdm\nimport torch.optim as optim\nfrom datasets import load_dataset\nfrom main import ConfidenceEnhancedTransformer\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nnum_epochs = 3\nsave_steps = 500 # Save the model every 500 steps\n\n# Define a custom dataset\nclass TextDataset(Dataset):\n def __init__(self, tokenizer, texts, block_size=128):\n self.examples = []\n\n for text in texts:\n tokenized_text = tokenizer.encode(text)\n for i in range(0, len(tokenized_text) - block_size + 1, block_size):\n self.examples.append(\n torch.tensor(tokenized_text[i:i + block_size], dtype=torch.long)\n )\n\n def __len__(self):\n return len(self.examples)\n\n def __getitem__(self, i):\n return self.examples[i]\n\n# Load tokenizer and model\ntokenizer = GPT2Tokenizer.from_pretrained('gpt2')\nmodel = ConfidenceEnhancedTransformer.from_pretrained('gpt2')\n\n# Load the WikiText-2 dataset\ndataset = load_dataset('wikitext', 'wikitext-2-raw-v1', split='train')\ntexts = dataset['text']\n\n# Split the dataset into training and validation sets\ntrain_texts, val_texts = train_test_split(texts, test_size=0.1, random_state=42)\n\n# Prepare datasets\ntrain_dataset = TextDataset(\n tokenizer=tokenizer,\n texts=train_texts,\n block_size=128\n)\nval_dataset = TextDataset(\n tokenizer=tokenizer,","source_hash":"fca41099ce250271c231f639b57270deadda7aaebce2cdea10a73247db8e086b","truncated":false}
8
+ {"repo_id":"ConfidenceTransformer","entity_id":"py:train.compute_ece","uri":"program://ConfidenceTransformer/function/train.compute_ece#L75-L87","kind":"function","name":"compute_ece","path":"train.py","language":"python","start_line":75,"end_line":87,"context_start_line":55,"context_end_line":107,"code":")\n\n# Create DataLoaders\ntrain_dataloader = DataLoader(train_dataset, batch_size=4, shuffle=True)\nval_dataloader = DataLoader(val_dataset, batch_size=4, shuffle=False)\n\n# Prepare optimizer and scheduler\noptimizer = optim.AdamW(model.parameters(), lr=5e-5)\ntotal_steps = len(train_dataloader) * num_epochs\nscheduler = get_linear_schedule_with_warmup(\n optimizer,\n num_warmup_steps=0,\n num_training_steps=total_steps\n)\n\n# Move model to GPU if available\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\nmodel.to(device)\n\n# Define ECE computation function\ndef compute_ece(preds, confidences, n_bins=10):\n bin_boundaries = np.linspace(0, 1, n_bins + 1)\n ece = 0.0\n for i in range(n_bins):\n bin_lower = bin_boundaries[i]\n bin_upper = bin_boundaries[i + 1]\n in_bin = (confidences > bin_lower) & (confidences <= bin_upper)\n prop_in_bin = np.mean(in_bin)\n if prop_in_bin > 0:\n accuracy_in_bin = np.mean(preds[in_bin] == preds[in_bin]) # Adjust based on your prediction mechanism\n avg_confidence_in_bin = np.mean(confidences[in_bin])\n ece += np.abs(avg_confidence_in_bin - accuracy_in_bin) * prop_in_bin\n return ece\n\n# Define Reliability Diagram function\ndef reliability_diagram(confidences, predictions, n_bins=10):\n bin_boundaries = np.linspace(0, 1, n_bins + 1)\n bin_centers = (bin_boundaries[:-1] + bin_boundaries[1:]) / 2\n accuracy = np.zeros(n_bins)\n confidence = np.zeros(n_bins)\n prop = np.zeros(n_bins)\n\n for i in range(n_bins):\n in_bin = (confidences > bin_boundaries[i]) & (confidences <= bin_boundaries[i + 1])\n prop[i] = np.mean(in_bin)\n if prop[i] > 0:\n accuracy[i] = np.mean(predictions[in_bin] == predictions[in_bin]) # Replace with actual labels\n confidence[i] = np.mean(confidences[in_bin])\n\n plt.figure(figsize=(8, 6))\n plt.plot(bin_centers, accuracy, marker='o', label='Accuracy')\n plt.plot(bin_centers, confidence, marker='s', label='Confidence')\n plt.fill_between(bin_boundaries[:-1], 0, 1, color='gray', alpha=0.1)","source_hash":"fca41099ce250271c231f639b57270deadda7aaebce2cdea10a73247db8e086b","truncated":false}
9
+ {"repo_id":"ConfidenceTransformer","entity_id":"py:train.reliability_diagram","uri":"program://ConfidenceTransformer/function/train.reliability_diagram#L90-L112","kind":"function","name":"reliability_diagram","path":"train.py","language":"python","start_line":90,"end_line":112,"context_start_line":70,"context_end_line":132,"code":"# Move model to GPU if available\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\nmodel.to(device)\n\n# Define ECE computation function\ndef compute_ece(preds, confidences, n_bins=10):\n bin_boundaries = np.linspace(0, 1, n_bins + 1)\n ece = 0.0\n for i in range(n_bins):\n bin_lower = bin_boundaries[i]\n bin_upper = bin_boundaries[i + 1]\n in_bin = (confidences > bin_lower) & (confidences <= bin_upper)\n prop_in_bin = np.mean(in_bin)\n if prop_in_bin > 0:\n accuracy_in_bin = np.mean(preds[in_bin] == preds[in_bin]) # Adjust based on your prediction mechanism\n avg_confidence_in_bin = np.mean(confidences[in_bin])\n ece += np.abs(avg_confidence_in_bin - accuracy_in_bin) * prop_in_bin\n return ece\n\n# Define Reliability Diagram function\ndef reliability_diagram(confidences, predictions, n_bins=10):\n bin_boundaries = np.linspace(0, 1, n_bins + 1)\n bin_centers = (bin_boundaries[:-1] + bin_boundaries[1:]) / 2\n accuracy = np.zeros(n_bins)\n confidence = np.zeros(n_bins)\n prop = np.zeros(n_bins)\n\n for i in range(n_bins):\n in_bin = (confidences > bin_boundaries[i]) & (confidences <= bin_boundaries[i + 1])\n prop[i] = np.mean(in_bin)\n if prop[i] > 0:\n accuracy[i] = np.mean(predictions[in_bin] == predictions[in_bin]) # Replace with actual labels\n confidence[i] = np.mean(confidences[in_bin])\n\n plt.figure(figsize=(8, 6))\n plt.plot(bin_centers, accuracy, marker='o', label='Accuracy')\n plt.plot(bin_centers, confidence, marker='s', label='Confidence')\n plt.fill_between(bin_boundaries[:-1], 0, 1, color='gray', alpha=0.1)\n plt.xlabel('Confidence')\n plt.ylabel('Accuracy')\n plt.legend()\n plt.title('Reliability Diagram')\n plt.show()\n\n# Training loop\nmodel.train()\nglobal_step = 0\nfor epoch in range(num_epochs):\n print(f\"Epoch {epoch + 1}/{num_epochs}\")\n epoch_loss = 0\n for batch in tqdm(train_dataloader):\n inputs = batch.to(device)\n labels = inputs.clone()\n\n optimizer.zero_grad()\n\n outputs = model(\n input_ids=inputs,\n labels=labels,\n num_dropout_samples=15 # You can adjust this number\n )\n loss = outputs['loss']\n loss.backward()","source_hash":"fca41099ce250271c231f639b57270deadda7aaebce2cdea10a73247db8e086b","truncated":false}
10
+ {"repo_id":"ConfidenceTransformer","entity_id":"py:train.__init__","uri":"program://ConfidenceTransformer/function/train.__init__#L18-L26","kind":"function","name":"__init__","path":"train.py","language":"python","start_line":18,"end_line":26,"context_start_line":1,"context_end_line":46,"code":"import torch\nfrom torch.utils.data import Dataset, DataLoader\nfrom transformers import GPT2Tokenizer, get_linear_schedule_with_warmup\nfrom tqdm import tqdm\nimport torch.optim as optim\nfrom datasets import load_dataset\nfrom main import ConfidenceEnhancedTransformer\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nnum_epochs = 3\nsave_steps = 500 # Save the model every 500 steps\n\n# Define a custom dataset\nclass TextDataset(Dataset):\n def __init__(self, tokenizer, texts, block_size=128):\n self.examples = []\n\n for text in texts:\n tokenized_text = tokenizer.encode(text)\n for i in range(0, len(tokenized_text) - block_size + 1, block_size):\n self.examples.append(\n torch.tensor(tokenized_text[i:i + block_size], dtype=torch.long)\n )\n\n def __len__(self):\n return len(self.examples)\n\n def __getitem__(self, i):\n return self.examples[i]\n\n# Load tokenizer and model\ntokenizer = GPT2Tokenizer.from_pretrained('gpt2')\nmodel = ConfidenceEnhancedTransformer.from_pretrained('gpt2')\n\n# Load the WikiText-2 dataset\ndataset = load_dataset('wikitext', 'wikitext-2-raw-v1', split='train')\ntexts = dataset['text']\n\n# Split the dataset into training and validation sets\ntrain_texts, val_texts = train_test_split(texts, test_size=0.1, random_state=42)\n\n# Prepare datasets\ntrain_dataset = TextDataset(","source_hash":"fca41099ce250271c231f639b57270deadda7aaebce2cdea10a73247db8e086b","truncated":false}
11
+ {"repo_id":"ConfidenceTransformer","entity_id":"py:train.__len__","uri":"program://ConfidenceTransformer/function/train.__len__#L28-L29","kind":"function","name":"__len__","path":"train.py","language":"python","start_line":28,"end_line":29,"context_start_line":8,"context_end_line":49,"code":"from sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nnum_epochs = 3\nsave_steps = 500 # Save the model every 500 steps\n\n# Define a custom dataset\nclass TextDataset(Dataset):\n def __init__(self, tokenizer, texts, block_size=128):\n self.examples = []\n\n for text in texts:\n tokenized_text = tokenizer.encode(text)\n for i in range(0, len(tokenized_text) - block_size + 1, block_size):\n self.examples.append(\n torch.tensor(tokenized_text[i:i + block_size], dtype=torch.long)\n )\n\n def __len__(self):\n return len(self.examples)\n\n def __getitem__(self, i):\n return self.examples[i]\n\n# Load tokenizer and model\ntokenizer = GPT2Tokenizer.from_pretrained('gpt2')\nmodel = ConfidenceEnhancedTransformer.from_pretrained('gpt2')\n\n# Load the WikiText-2 dataset\ndataset = load_dataset('wikitext', 'wikitext-2-raw-v1', split='train')\ntexts = dataset['text']\n\n# Split the dataset into training and validation sets\ntrain_texts, val_texts = train_test_split(texts, test_size=0.1, random_state=42)\n\n# Prepare datasets\ntrain_dataset = TextDataset(\n tokenizer=tokenizer,\n texts=train_texts,\n block_size=128","source_hash":"fca41099ce250271c231f639b57270deadda7aaebce2cdea10a73247db8e086b","truncated":false}
12
+ {"repo_id":"ConfidenceTransformer","entity_id":"py:train.__getitem__","uri":"program://ConfidenceTransformer/function/train.__getitem__#L31-L32","kind":"function","name":"__getitem__","path":"train.py","language":"python","start_line":31,"end_line":32,"context_start_line":11,"context_end_line":52,"code":"import matplotlib.pyplot as plt\n\nnum_epochs = 3\nsave_steps = 500 # Save the model every 500 steps\n\n# Define a custom dataset\nclass TextDataset(Dataset):\n def __init__(self, tokenizer, texts, block_size=128):\n self.examples = []\n\n for text in texts:\n tokenized_text = tokenizer.encode(text)\n for i in range(0, len(tokenized_text) - block_size + 1, block_size):\n self.examples.append(\n torch.tensor(tokenized_text[i:i + block_size], dtype=torch.long)\n )\n\n def __len__(self):\n return len(self.examples)\n\n def __getitem__(self, i):\n return self.examples[i]\n\n# Load tokenizer and model\ntokenizer = GPT2Tokenizer.from_pretrained('gpt2')\nmodel = ConfidenceEnhancedTransformer.from_pretrained('gpt2')\n\n# Load the WikiText-2 dataset\ndataset = load_dataset('wikitext', 'wikitext-2-raw-v1', split='train')\ntexts = dataset['text']\n\n# Split the dataset into training and validation sets\ntrain_texts, val_texts = train_test_split(texts, test_size=0.1, random_state=42)\n\n# Prepare datasets\ntrain_dataset = TextDataset(\n tokenizer=tokenizer,\n texts=train_texts,\n block_size=128\n)\nval_dataset = TextDataset(\n tokenizer=tokenizer,","source_hash":"fca41099ce250271c231f639b57270deadda7aaebce2cdea10a73247db8e086b","truncated":false}
13
+ {"repo_id":"ConfidenceTransformer","entity_id":"py:test","uri":"program://ConfidenceTransformer/module/test#L1-L74","kind":"module","name":"test","path":"test.py","language":"python","start_line":1,"end_line":74,"context_start_line":1,"context_end_line":74,"code":"import unittest\nimport torch\nfrom transformers import GPT2Tokenizer\nfrom main import ConfidenceEnhancedTransformer\n\nclass TestConfidenceEnhancedTransformer(unittest.TestCase):\n\n @classmethod\n def setUpClass(cls):\n cls.tokenizer = GPT2Tokenizer.from_pretrained('gpt2')\n cls.model = ConfidenceEnhancedTransformer.from_pretrained('gpt2')\n cls.model.eval() # Set model to evaluation mode\n\n def test_initialization(self):\n self.assertIsInstance(self.model, ConfidenceEnhancedTransformer)\n\n def test_forward_pass(self):\n input_text = \"What is the capital of USA?\"\n input_tokens = self.tokenizer(input_text, return_tensors=\"pt\")\n with torch.no_grad():\n outputs = self.model(input_tokens['input_ids'], num_dropout_samples=2)\n \n self.assertIn('lm_logits', outputs)\n self.assertIn('confidence_score', outputs)\n self.assertIn('ood_score', outputs)\n\n def test_confidence_score_range(self):\n input_text = \"What is the capital of USA?\"\n input_tokens = self.tokenizer(input_text, return_tensors=\"pt\")\n with torch.no_grad():\n outputs = self.model(input_tokens['input_ids'], num_dropout_samples=2)\n \n confidence_score = outputs['confidence_score'].item()\n self.assertGreaterEqual(confidence_score, 0.0)\n self.assertLessEqual(confidence_score, 1.0)\n\n def test_ood_score_range(self):\n input_text = \"What is the capital of USA?\"\n input_tokens = self.tokenizer(input_text, return_tensors=\"pt\")\n with torch.no_grad():\n outputs = self.model(input_tokens['input_ids'], num_dropout_samples=2)\n \n ood_score = outputs['ood_score'].item()\n self.assertGreaterEqual(ood_score, 0.0)\n self.assertLessEqual(ood_score, 1.0)\n\n def test_loss_calculation(self):\n input_text = \"What is the capital of USA?\"\n input_tokens = self.tokenizer(input_text, return_tensors=\"pt\")\n labels = input_tokens['input_ids'].clone()\n with torch.no_grad():\n outputs = self.model(input_tokens['input_ids'], labels=labels, num_dropout_samples=2)\n \n self.assertIn('loss', outputs)\n self.assertIsNotNone(outputs['loss'])\n\n def test_training_step(self):\n input_text = \"What is the capital of USA?\"\n input_tokens = self.tokenizer(input_text, return_tensors=\"pt\")\n labels = input_tokens['input_ids'].clone()\n optimizer = torch.optim.AdamW(self.model.parameters(), lr=5e-5)\n \n self.model.train()\n optimizer.zero_grad()\n outputs = self.model(input_tokens['input_ids'], labels=labels, num_dropout_samples=2)\n loss = outputs['loss']\n loss.backward()\n optimizer.step()\n \n self.assertIsNotNone(loss)\n self.assertGreater(loss.item(), 0.0)\n\nif __name__ == '__main__':\n unittest.main()","source_hash":"ba380ce5eaed855a01a22a5d730ef8e9e6c7f260a060b9c2a08938a0f06823b9","truncated":false}
14
+ {"repo_id":"ConfidenceTransformer","entity_id":"py:test.TestConfidenceEnhancedTransformer","uri":"program://ConfidenceTransformer/class/test.TestConfidenceEnhancedTransformer#L6-L71","kind":"class","name":"TestConfidenceEnhancedTransformer","path":"test.py","language":"python","start_line":6,"end_line":71,"context_start_line":1,"context_end_line":74,"code":"import unittest\nimport torch\nfrom transformers import GPT2Tokenizer\nfrom main import ConfidenceEnhancedTransformer\n\nclass TestConfidenceEnhancedTransformer(unittest.TestCase):\n\n @classmethod\n def setUpClass(cls):\n cls.tokenizer = GPT2Tokenizer.from_pretrained('gpt2')\n cls.model = ConfidenceEnhancedTransformer.from_pretrained('gpt2')\n cls.model.eval() # Set model to evaluation mode\n\n def test_initialization(self):\n self.assertIsInstance(self.model, ConfidenceEnhancedTransformer)\n\n def test_forward_pass(self):\n input_text = \"What is the capital of USA?\"\n input_tokens = self.tokenizer(input_text, return_tensors=\"pt\")\n with torch.no_grad():\n outputs = self.model(input_tokens['input_ids'], num_dropout_samples=2)\n \n self.assertIn('lm_logits', outputs)\n self.assertIn('confidence_score', outputs)\n self.assertIn('ood_score', outputs)\n\n def test_confidence_score_range(self):\n input_text = \"What is the capital of USA?\"\n input_tokens = self.tokenizer(input_text, return_tensors=\"pt\")\n with torch.no_grad():\n outputs = self.model(input_tokens['input_ids'], num_dropout_samples=2)\n \n confidence_score = outputs['confidence_score'].item()\n self.assertGreaterEqual(confidence_score, 0.0)\n self.assertLessEqual(confidence_score, 1.0)\n\n def test_ood_score_range(self):\n input_text = \"What is the capital of USA?\"\n input_tokens = self.tokenizer(input_text, return_tensors=\"pt\")\n with torch.no_grad():\n outputs = self.model(input_tokens['input_ids'], num_dropout_samples=2)\n \n ood_score = outputs['ood_score'].item()\n self.assertGreaterEqual(ood_score, 0.0)\n self.assertLessEqual(ood_score, 1.0)\n\n def test_loss_calculation(self):\n input_text = \"What is the capital of USA?\"\n input_tokens = self.tokenizer(input_text, return_tensors=\"pt\")\n labels = input_tokens['input_ids'].clone()\n with torch.no_grad():\n outputs = self.model(input_tokens['input_ids'], labels=labels, num_dropout_samples=2)\n \n self.assertIn('loss', outputs)\n self.assertIsNotNone(outputs['loss'])\n\n def test_training_step(self):\n input_text = \"What is the capital of USA?\"\n input_tokens = self.tokenizer(input_text, return_tensors=\"pt\")\n labels = input_tokens['input_ids'].clone()\n optimizer = torch.optim.AdamW(self.model.parameters(), lr=5e-5)\n \n self.model.train()\n optimizer.zero_grad()\n outputs = self.model(input_tokens['input_ids'], labels=labels, num_dropout_samples=2)\n loss = outputs['loss']\n loss.backward()\n optimizer.step()\n \n self.assertIsNotNone(loss)\n self.assertGreater(loss.item(), 0.0)\n\nif __name__ == '__main__':\n unittest.main()","source_hash":"ba380ce5eaed855a01a22a5d730ef8e9e6c7f260a060b9c2a08938a0f06823b9","truncated":false}
15
+ {"repo_id":"ConfidenceTransformer","entity_id":"py:test.setUpClass","uri":"program://ConfidenceTransformer/function/test.setUpClass#L9-L12","kind":"function","name":"setUpClass","path":"test.py","language":"python","start_line":9,"end_line":12,"context_start_line":1,"context_end_line":32,"code":"import unittest\nimport torch\nfrom transformers import GPT2Tokenizer\nfrom main import ConfidenceEnhancedTransformer\n\nclass TestConfidenceEnhancedTransformer(unittest.TestCase):\n\n @classmethod\n def setUpClass(cls):\n cls.tokenizer = GPT2Tokenizer.from_pretrained('gpt2')\n cls.model = ConfidenceEnhancedTransformer.from_pretrained('gpt2')\n cls.model.eval() # Set model to evaluation mode\n\n def test_initialization(self):\n self.assertIsInstance(self.model, ConfidenceEnhancedTransformer)\n\n def test_forward_pass(self):\n input_text = \"What is the capital of USA?\"\n input_tokens = self.tokenizer(input_text, return_tensors=\"pt\")\n with torch.no_grad():\n outputs = self.model(input_tokens['input_ids'], num_dropout_samples=2)\n \n self.assertIn('lm_logits', outputs)\n self.assertIn('confidence_score', outputs)\n self.assertIn('ood_score', outputs)\n\n def test_confidence_score_range(self):\n input_text = \"What is the capital of USA?\"\n input_tokens = self.tokenizer(input_text, return_tensors=\"pt\")\n with torch.no_grad():\n outputs = self.model(input_tokens['input_ids'], num_dropout_samples=2)\n ","source_hash":"ba380ce5eaed855a01a22a5d730ef8e9e6c7f260a060b9c2a08938a0f06823b9","truncated":false}
16
+ {"repo_id":"ConfidenceTransformer","entity_id":"py:test.test_initialization","uri":"program://ConfidenceTransformer/function/test.test_initialization#L14-L15","kind":"function","name":"test_initialization","path":"test.py","language":"python","start_line":14,"end_line":15,"context_start_line":1,"context_end_line":35,"code":"import unittest\nimport torch\nfrom transformers import GPT2Tokenizer\nfrom main import ConfidenceEnhancedTransformer\n\nclass TestConfidenceEnhancedTransformer(unittest.TestCase):\n\n @classmethod\n def setUpClass(cls):\n cls.tokenizer = GPT2Tokenizer.from_pretrained('gpt2')\n cls.model = ConfidenceEnhancedTransformer.from_pretrained('gpt2')\n cls.model.eval() # Set model to evaluation mode\n\n def test_initialization(self):\n self.assertIsInstance(self.model, ConfidenceEnhancedTransformer)\n\n def test_forward_pass(self):\n input_text = \"What is the capital of USA?\"\n input_tokens = self.tokenizer(input_text, return_tensors=\"pt\")\n with torch.no_grad():\n outputs = self.model(input_tokens['input_ids'], num_dropout_samples=2)\n \n self.assertIn('lm_logits', outputs)\n self.assertIn('confidence_score', outputs)\n self.assertIn('ood_score', outputs)\n\n def test_confidence_score_range(self):\n input_text = \"What is the capital of USA?\"\n input_tokens = self.tokenizer(input_text, return_tensors=\"pt\")\n with torch.no_grad():\n outputs = self.model(input_tokens['input_ids'], num_dropout_samples=2)\n \n confidence_score = outputs['confidence_score'].item()\n self.assertGreaterEqual(confidence_score, 0.0)\n self.assertLessEqual(confidence_score, 1.0)","source_hash":"ba380ce5eaed855a01a22a5d730ef8e9e6c7f260a060b9c2a08938a0f06823b9","truncated":false}
17
+ {"repo_id":"ConfidenceTransformer","entity_id":"py:test.test_forward_pass","uri":"program://ConfidenceTransformer/function/test.test_forward_pass#L17-L25","kind":"function","name":"test_forward_pass","path":"test.py","language":"python","start_line":17,"end_line":25,"context_start_line":1,"context_end_line":45,"code":"import unittest\nimport torch\nfrom transformers import GPT2Tokenizer\nfrom main import ConfidenceEnhancedTransformer\n\nclass TestConfidenceEnhancedTransformer(unittest.TestCase):\n\n @classmethod\n def setUpClass(cls):\n cls.tokenizer = GPT2Tokenizer.from_pretrained('gpt2')\n cls.model = ConfidenceEnhancedTransformer.from_pretrained('gpt2')\n cls.model.eval() # Set model to evaluation mode\n\n def test_initialization(self):\n self.assertIsInstance(self.model, ConfidenceEnhancedTransformer)\n\n def test_forward_pass(self):\n input_text = \"What is the capital of USA?\"\n input_tokens = self.tokenizer(input_text, return_tensors=\"pt\")\n with torch.no_grad():\n outputs = self.model(input_tokens['input_ids'], num_dropout_samples=2)\n \n self.assertIn('lm_logits', outputs)\n self.assertIn('confidence_score', outputs)\n self.assertIn('ood_score', outputs)\n\n def test_confidence_score_range(self):\n input_text = \"What is the capital of USA?\"\n input_tokens = self.tokenizer(input_text, return_tensors=\"pt\")\n with torch.no_grad():\n outputs = self.model(input_tokens['input_ids'], num_dropout_samples=2)\n \n confidence_score = outputs['confidence_score'].item()\n self.assertGreaterEqual(confidence_score, 0.0)\n self.assertLessEqual(confidence_score, 1.0)\n\n def test_ood_score_range(self):\n input_text = \"What is the capital of USA?\"\n input_tokens = self.tokenizer(input_text, return_tensors=\"pt\")\n with torch.no_grad():\n outputs = self.model(input_tokens['input_ids'], num_dropout_samples=2)\n \n ood_score = outputs['ood_score'].item()\n self.assertGreaterEqual(ood_score, 0.0)\n self.assertLessEqual(ood_score, 1.0)","source_hash":"ba380ce5eaed855a01a22a5d730ef8e9e6c7f260a060b9c2a08938a0f06823b9","truncated":false}
18
+ {"repo_id":"ConfidenceTransformer","entity_id":"py:test.test_confidence_score_range","uri":"program://ConfidenceTransformer/function/test.test_confidence_score_range#L27-L35","kind":"function","name":"test_confidence_score_range","path":"test.py","language":"python","start_line":27,"end_line":35,"context_start_line":7,"context_end_line":55,"code":"\n @classmethod\n def setUpClass(cls):\n cls.tokenizer = GPT2Tokenizer.from_pretrained('gpt2')\n cls.model = ConfidenceEnhancedTransformer.from_pretrained('gpt2')\n cls.model.eval() # Set model to evaluation mode\n\n def test_initialization(self):\n self.assertIsInstance(self.model, ConfidenceEnhancedTransformer)\n\n def test_forward_pass(self):\n input_text = \"What is the capital of USA?\"\n input_tokens = self.tokenizer(input_text, return_tensors=\"pt\")\n with torch.no_grad():\n outputs = self.model(input_tokens['input_ids'], num_dropout_samples=2)\n \n self.assertIn('lm_logits', outputs)\n self.assertIn('confidence_score', outputs)\n self.assertIn('ood_score', outputs)\n\n def test_confidence_score_range(self):\n input_text = \"What is the capital of USA?\"\n input_tokens = self.tokenizer(input_text, return_tensors=\"pt\")\n with torch.no_grad():\n outputs = self.model(input_tokens['input_ids'], num_dropout_samples=2)\n \n confidence_score = outputs['confidence_score'].item()\n self.assertGreaterEqual(confidence_score, 0.0)\n self.assertLessEqual(confidence_score, 1.0)\n\n def test_ood_score_range(self):\n input_text = \"What is the capital of USA?\"\n input_tokens = self.tokenizer(input_text, return_tensors=\"pt\")\n with torch.no_grad():\n outputs = self.model(input_tokens['input_ids'], num_dropout_samples=2)\n \n ood_score = outputs['ood_score'].item()\n self.assertGreaterEqual(ood_score, 0.0)\n self.assertLessEqual(ood_score, 1.0)\n\n def test_loss_calculation(self):\n input_text = \"What is the capital of USA?\"\n input_tokens = self.tokenizer(input_text, return_tensors=\"pt\")\n labels = input_tokens['input_ids'].clone()\n with torch.no_grad():\n outputs = self.model(input_tokens['input_ids'], labels=labels, num_dropout_samples=2)\n \n self.assertIn('loss', outputs)\n self.assertIsNotNone(outputs['loss'])","source_hash":"ba380ce5eaed855a01a22a5d730ef8e9e6c7f260a060b9c2a08938a0f06823b9","truncated":false}
19
+ {"repo_id":"ConfidenceTransformer","entity_id":"py:test.test_ood_score_range","uri":"program://ConfidenceTransformer/function/test.test_ood_score_range#L37-L45","kind":"function","name":"test_ood_score_range","path":"test.py","language":"python","start_line":37,"end_line":45,"context_start_line":17,"context_end_line":65,"code":" def test_forward_pass(self):\n input_text = \"What is the capital of USA?\"\n input_tokens = self.tokenizer(input_text, return_tensors=\"pt\")\n with torch.no_grad():\n outputs = self.model(input_tokens['input_ids'], num_dropout_samples=2)\n \n self.assertIn('lm_logits', outputs)\n self.assertIn('confidence_score', outputs)\n self.assertIn('ood_score', outputs)\n\n def test_confidence_score_range(self):\n input_text = \"What is the capital of USA?\"\n input_tokens = self.tokenizer(input_text, return_tensors=\"pt\")\n with torch.no_grad():\n outputs = self.model(input_tokens['input_ids'], num_dropout_samples=2)\n \n confidence_score = outputs['confidence_score'].item()\n self.assertGreaterEqual(confidence_score, 0.0)\n self.assertLessEqual(confidence_score, 1.0)\n\n def test_ood_score_range(self):\n input_text = \"What is the capital of USA?\"\n input_tokens = self.tokenizer(input_text, return_tensors=\"pt\")\n with torch.no_grad():\n outputs = self.model(input_tokens['input_ids'], num_dropout_samples=2)\n \n ood_score = outputs['ood_score'].item()\n self.assertGreaterEqual(ood_score, 0.0)\n self.assertLessEqual(ood_score, 1.0)\n\n def test_loss_calculation(self):\n input_text = \"What is the capital of USA?\"\n input_tokens = self.tokenizer(input_text, return_tensors=\"pt\")\n labels = input_tokens['input_ids'].clone()\n with torch.no_grad():\n outputs = self.model(input_tokens['input_ids'], labels=labels, num_dropout_samples=2)\n \n self.assertIn('loss', outputs)\n self.assertIsNotNone(outputs['loss'])\n\n def test_training_step(self):\n input_text = \"What is the capital of USA?\"\n input_tokens = self.tokenizer(input_text, return_tensors=\"pt\")\n labels = input_tokens['input_ids'].clone()\n optimizer = torch.optim.AdamW(self.model.parameters(), lr=5e-5)\n \n self.model.train()\n optimizer.zero_grad()\n outputs = self.model(input_tokens['input_ids'], labels=labels, num_dropout_samples=2)","source_hash":"ba380ce5eaed855a01a22a5d730ef8e9e6c7f260a060b9c2a08938a0f06823b9","truncated":false}
20
+ {"repo_id":"ConfidenceTransformer","entity_id":"py:test.test_loss_calculation","uri":"program://ConfidenceTransformer/function/test.test_loss_calculation#L47-L55","kind":"function","name":"test_loss_calculation","path":"test.py","language":"python","start_line":47,"end_line":55,"context_start_line":27,"context_end_line":74,"code":" def test_confidence_score_range(self):\n input_text = \"What is the capital of USA?\"\n input_tokens = self.tokenizer(input_text, return_tensors=\"pt\")\n with torch.no_grad():\n outputs = self.model(input_tokens['input_ids'], num_dropout_samples=2)\n \n confidence_score = outputs['confidence_score'].item()\n self.assertGreaterEqual(confidence_score, 0.0)\n self.assertLessEqual(confidence_score, 1.0)\n\n def test_ood_score_range(self):\n input_text = \"What is the capital of USA?\"\n input_tokens = self.tokenizer(input_text, return_tensors=\"pt\")\n with torch.no_grad():\n outputs = self.model(input_tokens['input_ids'], num_dropout_samples=2)\n \n ood_score = outputs['ood_score'].item()\n self.assertGreaterEqual(ood_score, 0.0)\n self.assertLessEqual(ood_score, 1.0)\n\n def test_loss_calculation(self):\n input_text = \"What is the capital of USA?\"\n input_tokens = self.tokenizer(input_text, return_tensors=\"pt\")\n labels = input_tokens['input_ids'].clone()\n with torch.no_grad():\n outputs = self.model(input_tokens['input_ids'], labels=labels, num_dropout_samples=2)\n \n self.assertIn('loss', outputs)\n self.assertIsNotNone(outputs['loss'])\n\n def test_training_step(self):\n input_text = \"What is the capital of USA?\"\n input_tokens = self.tokenizer(input_text, return_tensors=\"pt\")\n labels = input_tokens['input_ids'].clone()\n optimizer = torch.optim.AdamW(self.model.parameters(), lr=5e-5)\n \n self.model.train()\n optimizer.zero_grad()\n outputs = self.model(input_tokens['input_ids'], labels=labels, num_dropout_samples=2)\n loss = outputs['loss']\n loss.backward()\n optimizer.step()\n \n self.assertIsNotNone(loss)\n self.assertGreater(loss.item(), 0.0)\n\nif __name__ == '__main__':\n unittest.main()","source_hash":"ba380ce5eaed855a01a22a5d730ef8e9e6c7f260a060b9c2a08938a0f06823b9","truncated":false}
21
+ {"repo_id":"ConfidenceTransformer","entity_id":"py:test.test_training_step","uri":"program://ConfidenceTransformer/function/test.test_training_step#L57-L71","kind":"function","name":"test_training_step","path":"test.py","language":"python","start_line":57,"end_line":71,"context_start_line":37,"context_end_line":74,"code":" def test_ood_score_range(self):\n input_text = \"What is the capital of USA?\"\n input_tokens = self.tokenizer(input_text, return_tensors=\"pt\")\n with torch.no_grad():\n outputs = self.model(input_tokens['input_ids'], num_dropout_samples=2)\n \n ood_score = outputs['ood_score'].item()\n self.assertGreaterEqual(ood_score, 0.0)\n self.assertLessEqual(ood_score, 1.0)\n\n def test_loss_calculation(self):\n input_text = \"What is the capital of USA?\"\n input_tokens = self.tokenizer(input_text, return_tensors=\"pt\")\n labels = input_tokens['input_ids'].clone()\n with torch.no_grad():\n outputs = self.model(input_tokens['input_ids'], labels=labels, num_dropout_samples=2)\n \n self.assertIn('loss', outputs)\n self.assertIsNotNone(outputs['loss'])\n\n def test_training_step(self):\n input_text = \"What is the capital of USA?\"\n input_tokens = self.tokenizer(input_text, return_tensors=\"pt\")\n labels = input_tokens['input_ids'].clone()\n optimizer = torch.optim.AdamW(self.model.parameters(), lr=5e-5)\n \n self.model.train()\n optimizer.zero_grad()\n outputs = self.model(input_tokens['input_ids'], labels=labels, num_dropout_samples=2)\n loss = outputs['loss']\n loss.backward()\n optimizer.step()\n \n self.assertIsNotNone(loss)\n self.assertGreater(loss.item(), 0.0)\n\nif __name__ == '__main__':\n unittest.main()","source_hash":"ba380ce5eaed855a01a22a5d730ef8e9e6c7f260a060b9c2a08938a0f06823b9","truncated":false}
22
+ {"repo_id":"ConfidenceTransformer","entity_id":"file:eval.py","uri":"program://ConfidenceTransformer/file/eval.py","kind":"file","name":"eval.py","path":"eval.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom transformers import GPT2Tokenizer, GPT2LMHeadModel, GPT2Model\nfrom datasets import load_dataset\nfrom main import ConfidenceEnhancedTransformer # Import the class from main.py\n\n# Load the trained model and tokenizer\nmodel_name = 'confidence_model'\nmodel_path = model_name\ntokenizer_path = model_name\ntokenizer = GPT2Tokenizer.from_pretrained(tokenizer_path)\n\nmodel = ConfidenceEnhancedTransformer.from_pretrained(model_path, attn_implementation=\"eager\")\n\n# Move model to GPU if available\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\nmodel.to(device)\n\n# Set the model to evaluation mode\nmodel.eval()","source_hash":"3578bf0e13cd974bc6904184ebfe9ffbf435d2522c4e913c4c68d1f6dc98ef44","truncated":false}
23
+ {"repo_id":"ConfidenceTransformer","entity_id":"file:main.py","uri":"program://ConfidenceTransformer/file/main.py","kind":"file","name":"main.py","path":"main.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import torch\nimport torch.nn as nn\nfrom transformers import GPT2LMHeadModel, GPT2Model, GPT2Tokenizer\nimport torch.nn.functional as F\n\nclass ConfidenceEnhancedTransformer(GPT2LMHeadModel):\n def __init__(self, config):\n super(ConfidenceEnhancedTransformer, self).__init__(config)\n self.transformer = GPT2Model(config)\n #self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False) # Language modeling head\n\n # Confidence scoring head for epistemic uncertainty and OOD detection\n self.confidence_head = nn.Sequential(\n nn.Linear(config.n_embd, 128),\n nn.ReLU(),\n nn.Linear(128, 1), # Single output for confidence score\n nn.Sigmoid() # Confidence score between 0 and 1\n )\n \n # OOD detector head\n self.ood_detector = nn.Linear(config.n_embd, 1) # Auxiliary head for OOD detection","source_hash":"0bf4a6d8cb4435d83ba0509db804e4c03aefa41e5e87fca50ffea0cd28079b65","truncated":false}
24
+ {"repo_id":"ConfidenceTransformer","entity_id":"file:train.py","uri":"program://ConfidenceTransformer/file/train.py","kind":"file","name":"train.py","path":"train.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import torch\nfrom torch.utils.data import Dataset, DataLoader\nfrom transformers import GPT2Tokenizer, get_linear_schedule_with_warmup\nfrom tqdm import tqdm\nimport torch.optim as optim\nfrom datasets import load_dataset\nfrom main import ConfidenceEnhancedTransformer\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nnum_epochs = 3\nsave_steps = 500 # Save the model every 500 steps\n\n# Define a custom dataset\nclass TextDataset(Dataset):\n def __init__(self, tokenizer, texts, block_size=128):\n self.examples = []\n\n for text in texts:","source_hash":"fca41099ce250271c231f639b57270deadda7aaebce2cdea10a73247db8e086b","truncated":false}
25
+ {"repo_id":"ConfidenceTransformer","entity_id":"file:test.py","uri":"program://ConfidenceTransformer/file/test.py","kind":"file","name":"test.py","path":"test.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import unittest\nimport torch\nfrom transformers import GPT2Tokenizer\nfrom main import ConfidenceEnhancedTransformer\n\nclass TestConfidenceEnhancedTransformer(unittest.TestCase):\n\n @classmethod\n def setUpClass(cls):\n cls.tokenizer = GPT2Tokenizer.from_pretrained('gpt2')\n cls.model = ConfidenceEnhancedTransformer.from_pretrained('gpt2')\n cls.model.eval() # Set model to evaluation mode\n\n def test_initialization(self):\n self.assertIsInstance(self.model, ConfidenceEnhancedTransformer)\n\n def test_forward_pass(self):\n input_text = \"What is the capital of USA?\"\n input_tokens = self.tokenizer(input_text, return_tensors=\"pt\")\n with torch.no_grad():\n outputs = self.model(input_tokens['input_ids'], num_dropout_samples=2)","source_hash":"ba380ce5eaed855a01a22a5d730ef8e9e6c7f260a060b9c2a08938a0f06823b9","truncated":false}
source_snippets/Cross-Scale-MAE.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
source_snippets/DMOSpeech2.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
source_snippets/Digital-World-Model.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
source_snippets/EE-LLM.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
source_snippets/EfficientDynamic3DGaussian.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
source_snippets/Fuser.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
source_snippets/GPTeacher.jsonl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ {"repo_id":"GPTeacher","entity_id":"py:json2markdown","uri":"program://GPTeacher/module/json2markdown#L1-L44","kind":"module","name":"json2markdown","path":"json2markdown.py","language":"python","start_line":1,"end_line":44,"context_start_line":1,"context_end_line":44,"code":"import json\nimport os\nimport glob\nimport warnings\nfrom markdownify import markdownify as md\n\nwarnings.filterwarnings(\"ignore\", category=UserWarning, module='markdownify')\n\n\ndef json_to_markdown(json_file, output_dir):\n with open(json_file, 'r', encoding='utf-8') as file:\n data = json.load(file)\n\n # Process the JSON data and convert it to Markdown.\n # This step depends on the structure of your JSON files.\n markdown_output = \"\"\n for item in data:\n if isinstance(item, dict):\n for key, value in item.items():\n markdown_output += f\"## {key}\\n\\n{md(value)}\\n\\n\"\n else:\n markdown_output += f\"{md(item)}\\n\\n\"\n\n # Write the output to a Markdown file.\n output_file = os.path.join(output_dir, os.path.splitext(os.path.basename(json_file))[0] + '.md')\n os.makedirs(os.path.dirname(output_file), exist_ok=True)\n with open(output_file, 'w', encoding='utf-8') as file:\n file.write(markdown_output)\n\n# Set the folder paths and the input directory.\nfolder_paths = ['Codegen', 'Instruct', 'Roleplay', 'Toolformer']\ninput_dir = '.'\noutput_dir = 'output'\n\n# Process all JSON files in the specified folder paths.\nfor folder in folder_paths:\n input_files = glob.glob(os.path.join(input_dir, folder, '*.json'))\n\n for input_file in input_files:\n # Create a mirrored output path by replacing the input directory with the output directory.\n mirrored_output_dir = input_file.replace(input_dir, output_dir)\n mirrored_output_dir = os.path.dirname(mirrored_output_dir)\n\n json_to_markdown(input_file, mirrored_output_dir)","source_hash":"5940fd296f240b7ef7a8b0721a0b0c184d89fefab2b936bcab11d1e7032e23bf","truncated":false}
2
+ {"repo_id":"GPTeacher","entity_id":"py:json2markdown.json_to_markdown","uri":"program://GPTeacher/function/json2markdown.json_to_markdown#L10-L28","kind":"function","name":"json_to_markdown","path":"json2markdown.py","language":"python","start_line":10,"end_line":28,"context_start_line":1,"context_end_line":44,"code":"import json\nimport os\nimport glob\nimport warnings\nfrom markdownify import markdownify as md\n\nwarnings.filterwarnings(\"ignore\", category=UserWarning, module='markdownify')\n\n\ndef json_to_markdown(json_file, output_dir):\n with open(json_file, 'r', encoding='utf-8') as file:\n data = json.load(file)\n\n # Process the JSON data and convert it to Markdown.\n # This step depends on the structure of your JSON files.\n markdown_output = \"\"\n for item in data:\n if isinstance(item, dict):\n for key, value in item.items():\n markdown_output += f\"## {key}\\n\\n{md(value)}\\n\\n\"\n else:\n markdown_output += f\"{md(item)}\\n\\n\"\n\n # Write the output to a Markdown file.\n output_file = os.path.join(output_dir, os.path.splitext(os.path.basename(json_file))[0] + '.md')\n os.makedirs(os.path.dirname(output_file), exist_ok=True)\n with open(output_file, 'w', encoding='utf-8') as file:\n file.write(markdown_output)\n\n# Set the folder paths and the input directory.\nfolder_paths = ['Codegen', 'Instruct', 'Roleplay', 'Toolformer']\ninput_dir = '.'\noutput_dir = 'output'\n\n# Process all JSON files in the specified folder paths.\nfor folder in folder_paths:\n input_files = glob.glob(os.path.join(input_dir, folder, '*.json'))\n\n for input_file in input_files:\n # Create a mirrored output path by replacing the input directory with the output directory.\n mirrored_output_dir = input_file.replace(input_dir, output_dir)\n mirrored_output_dir = os.path.dirname(mirrored_output_dir)\n\n json_to_markdown(input_file, mirrored_output_dir)","source_hash":"5940fd296f240b7ef7a8b0721a0b0c184d89fefab2b936bcab11d1e7032e23bf","truncated":false}
3
+ {"repo_id":"GPTeacher","entity_id":"file:json2markdown.py","uri":"program://GPTeacher/file/json2markdown.py","kind":"file","name":"json2markdown.py","path":"json2markdown.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import json\nimport os\nimport glob\nimport warnings\nfrom markdownify import markdownify as md\n\nwarnings.filterwarnings(\"ignore\", category=UserWarning, module='markdownify')\n\n\ndef json_to_markdown(json_file, output_dir):\n with open(json_file, 'r', encoding='utf-8') as file:\n data = json.load(file)\n\n # Process the JSON data and convert it to Markdown.\n # This step depends on the structure of your JSON files.\n markdown_output = \"\"\n for item in data:\n if isinstance(item, dict):\n for key, value in item.items():\n markdown_output += f\"## {key}\\n\\n{md(value)}\\n\\n\"\n else:","source_hash":"5940fd296f240b7ef7a8b0721a0b0c184d89fefab2b936bcab11d1e7032e23bf","truncated":false}
source_snippets/Human3R.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
source_snippets/LLaMA-Adapter.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
source_snippets/Learning-with-Holographic-Reduced-Representations.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
source_snippets/M2PT.jsonl ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {"repo_id":"M2PT","entity_id":"py:model_example","uri":"program://M2PT/module/model_example#L1-L29","kind":"module","name":"model_example","path":"model_example.py","language":"python","start_line":1,"end_line":29,"context_start_line":1,"context_end_line":29,"code":"import torch\nfrom torch import nn\nfrom m2pt.main import M2PT\n\n# Create an instance of the MPTransformerBlock class with the specified parameters\nmodel = M2PT(\n dim=512, # Dimension of the input and output tensors\n num_tokens=10000,\n depth=6,\n dim_head=64, # Dimension of each attention head\n heads=8, # Number of attention heads\n dropout=0.1, # Dropout rate\n ff_mult=4, # Multiplier for the dimension of the feed-forward network\n original_linear=nn.Linear(512, 512), # Linear layer for the original input tensor\n auxiliar_linear=nn.Linear(512, 512), # Linear layer for the auxiliary input tensor\n ffn_original_linear=nn.Linear, # Linear layer for the original input tensor in the feed-forward network\n ffn_auxiliar_linear=nn.Linear, # Linear layer for the auxiliary input tensor in the feed-forward network\n ffn_original_last_linear=nn.Linear, # Last linear layer for the original input tensor in the feed-forward network\n ffn_aux_last_linear=nn.Linear, # Last linear layer for the auxiliary input tensor in the feed-forward network\n)\n\n# Create a 3D tensor with shape B x S x D\nx = torch.randint(0, 10000, (1, 512))\n\n# Pass the input tensor through the model\nout = model(x)\n\n# Print the shape of the output tensor\nprint(out.shape)","source_hash":"d24a5209a920e60f35f2a1c3e4a14ff7b796d1b3698ef04d0b072e913a127412","truncated":false}
2
+ {"repo_id":"M2PT","entity_id":"py:example","uri":"program://M2PT/module/example#L1-L27","kind":"module","name":"example","path":"example.py","language":"python","start_line":1,"end_line":27,"context_start_line":1,"context_end_line":27,"code":"import torch\nfrom torch import nn\nfrom m2pt import MPTransformerBlock\n\n# Create an instance of the MPTransformerBlock class with the specified parameters\nmodel = MPTransformerBlock(\n dim=512, # Dimension of the input and output tensors\n dim_head=64, # Dimension of each attention head\n heads=8, # Number of attention heads\n dropout=0.1, # Dropout rate\n ff_mult=4, # Multiplier for the dimension of the feed-forward network\n original_linear=nn.Linear(512, 512), # Linear layer for the original input tensor\n auxiliar_linear=nn.Linear(512, 512), # Linear layer for the auxiliary input tensor\n ffn_original_linear=nn.Linear, # Linear layer for the original input tensor in the feed-forward network\n ffn_auxiliar_linear=nn.Linear, # Linear layer for the auxiliary input tensor in the feed-forward network\n ffn_original_last_linear=nn.Linear, # Last linear layer for the original input tensor in the feed-forward network\n ffn_aux_last_linear=nn.Linear, # Last linear layer for the auxiliary input tensor in the feed-forward network\n)\n\n# Create a 3D tensor with shape B x S x D\nx = torch.randn(1, 512, 512)\n\n# Pass the input tensor through the model\nout = model(x)\n\n# Print the shape of the output tensor\nprint(out.shape)","source_hash":"400c144f38a8cc5a7dd896fdda7b083f58ddd38248e9b9a78a0fa99c65a806a4","truncated":false}
3
+ {"repo_id":"M2PT","entity_id":"py:m2pt.main","uri":"program://M2PT/module/m2pt.main#L1-L450","kind":"module","name":"m2pt.main","path":"m2pt/main.py","language":"python","start_line":1,"end_line":450,"context_start_line":1,"context_end_line":450,"code":"import torch\nfrom torch import nn, Tensor\nfrom zeta.nn.attention.multihead_attention import MultiheadAttention\nfrom typing import List\nimport torch.nn.functional as F\n\n\nclass CrossModalReparamLinear(nn.Linear):\n \"\"\"\n Linear layer with cross-modal reparameterization.\n\n Args:\n in_features (int): Size of each input sample.\n out_features (int): Size of each output sample.\n bias (bool, optional): If set to False, the layer will not learn an additive bias. Default is True.\n origin_layer (nn.Linear, optional): Original linear layer to initialize the weight and bias from. Default is None.\n aux_weight (torch.Tensor, optional): Auxiliary weight tensor. Default is None.\n is_aux_trainable (bool, optional): If set to False, the auxiliary weight will not be trainable. Default is True.\n \"\"\"\n\n def __init__(\n self,\n in_features,\n out_features,\n bias=True,\n origin_layer=None,\n aux_weight=None,\n is_aux_trainable=True,\n ):\n super().__init__(in_features, out_features, bias)\n self.cross_modal_scale = nn.Parameter(torch.zeros(1))\n assert (\n self.weight.size() == aux_weight.size()\n ), \"Target weight and aux weight must have the same shape\"\n self.aux_weight = aux_weight\n self.aux_weight.requires_grad_(is_aux_trainable)\n if origin_layer is not None:\n with torch.no_grad():\n self.weight.copy_(origin_layer.weight)\n self.bias.copy_(origin_layer.bias)\n\n def forward(self, input):\n \"\"\"\n Forward pass of the CrossModalReparamLinear layer.\n\n Args:\n input (torch.Tensor): Input tensor.\n\n Returns:\n torch.Tensor: Output tensor.\n \"\"\"\n weight = (\n self.weight + self.cross_modal_scale * self.aux_weight\n )\n return F.linear(input, weight, self.bias)\n\n\ndef cross_modal_ffn(\n ffn_original_linear: nn.Linear,\n ffn_auxiliar_linear: nn.Linear,\n dim: int,\n ff_mult: int,\n dropout: int,\n ffn_original_last_linear: nn.Linear,\n ffn_aux_last_linear: nn.Linear,\n *args,\n **kwargs,\n):\n \"\"\"\n Cross-modal feed-forward network.\n\n Args:\n ffn_original_linear (nn.Linear): Linear layer for the original modality.\n ffn_auxiliar_linear (nn.Linear): Linear layer for the auxiliary modality.\n dim (int): Dimension of the input.\n ff_mult (int): Multiplier for the hidden dimension.\n dropout (int): Dropout rate.\n ffn_original_last_linear (nn.Linear): Linear layer for the original modality in the last step.\n ffn_aux_last_linear (nn.Linear): Linear layer for the auxiliary modality in the last step.\n *args: Variable length arguments.\n **kwargs: Keyword arguments.\n\n Returns:\n nn.Sequential: Sequential model representing the cross-modal feed-forward network.\n \"\"\"\n\n ffn_1st_rep_linear = CrossModalReParametrization(\n ffn_original_linear(dim, dim * ff_mult),\n ffn_auxiliar_linear(dim, dim * ff_mult),\n )\n\n ffn_2nd_linear = CrossModalReParametrization(\n ffn_original_last_linear(dim * ff_mult, dim),\n ffn_aux_last_linear(dim * ff_mult, dim),\n )\n\n return nn.Sequential(\n ffn_1st_rep_linear,\n nn.GELU(),\n nn.Dropout(dropout),\n nn.LayerNorm(dim**ff_mult),\n nn.GELU(),\n ffn_2nd_linear,\n nn.LayerNorm(dim),\n )\n\n\ndef build_cross_modal_reparam_linear(origin_layer, aux_layer):\n assert origin_layer.weight.size() == aux_layer.weight.size()\n return CrossModalReparamLinear(\n in_features=origin_layer.in_features,\n out_features=origin_layer.out_features,\n origin_layer=origin_layer,\n bias=origin_layer.bias is not None,\n aux_weight=aux_layer.weight,\n )\n\n\ndef _get_attr_by_name(obj, attr_name):\n attrs = attr_name.split(\".\")\n for a in attrs:\n obj = obj.__getattr__(a)\n return obj\n\n\ndef _set_attr_by_name(obj, attr_name, attr_value):\n owner = obj\n attr_names = attr_name.split(\".\")\n if len(attr_names) > 1:\n for a in attr_names[:-1]:\n owner = owner.__getattr__(a)\n owner.__setattr__(attr_names[-1], attr_value)\n\n\ndef change_original_linear_to_reparam(\n target_module, aux_module, layer_name\n):\n origin_linear_layer = _get_attr_by_name(target_module, layer_name)\n aux_linear_layer = _get_attr_by_name(aux_module, layer_name)\n reparam_layer = build_cross_modal_reparam_linear(\n origin_linear_layer, aux_linear_layer\n )\n _set_attr_by_name(target_module, layer_name, reparam_layer)\n\n\ndef reparameterize_aux_into_target_model(\n target_model,\n aux_model,\n layer_names=(\"attn.qkv\", \"attn.proj\", \"mlp.fc1\", \"mlp.fc2\"),\n main_body_name=\"blocks\",\n):\n \"\"\"\n Reparameterizes the auxiliary model into the target model by replacing specific layers with corresponding layers from the auxiliary model.\n\n Args:\n target_model (object): The target model to reparameterize.\n aux_model (object): The auxiliary model containing the replacement layers.\n layer_names (tuple, optional): The names of the layers to be replaced. Defaults to (\"attn.qkv\", \"attn.proj\", \"mlp.fc1\", \"mlp.fc2\").\n main_body_name (str, optional): The name of the main body of the models. Defaults to \"blocks\".\n \"\"\"\n target_transformer_blocks = _get_attr_by_name(\n target_model, main_body_name\n )\n aux_transformer_blocks = _get_attr_by_name(\n aux_model, main_body_name\n )\n for target_block, aux_block in zip(\n target_transformer_blocks, aux_transformer_blocks\n ):\n for layer_name in layer_names:\n change_original_linear_to_reparam(\n target_block, aux_block, layer_name\n )\n\n\nclass CrossModalReParametrization(nn.Module):\n \"\"\"\n A module for cross-modal reparametrization.\n\n Args:\n original_linear (nn.Linear): The original linear layer.\n auxiliary_linear (nn.Linear): The auxiliary linear layer.\n\n Attributes:\n cross_modal_scale (nn.Parameter): The scale parameter for cross-modal reparametrization.\n\n Methods:\n forward(x: Tensor) -> Tensor: Performs forward pass through the module.\n merge(): Merges the weights and biases of the original and auxiliary linear layers.\n \"\"\"\n\n def __init__(\n self,\n original_linear: nn.Linear,\n auxiliary_linear: nn.Linear,\n linears: List[nn.Linear] = None,\n ):\n super().__init__()\n self.original_linear = original_linear\n self.auxiliary_linear = auxiliary_linear\n self.cross_modal_scale = nn.Parameter(torch.zeros(1))\n\n def forward(self, x: Tensor) -> Tensor:\n combined_weight = (\n self.original_linear.weight\n + self.cross_modal_scale * self.auxiliary_linear.weight\n )\n return nn.functional.linear(\n x, combined_weight, self.original_linear.bias\n )\n\n def merge(self):\n self.original_linear.weight.data.add_(\n self.cross_modal_scale.item()\n * self.auxiliary_linear.weight.data\n )\n if (\n self.original_linear.bias is not None\n and self.auxiliary_linear.bias is not None\n ):\n self.original_linear.bias.data.add_(\n self.cross_modal_scale.item()\n * self.auxiliary_linear.bias.data\n )\n\n\nclass MPTransformerBlock(nn.Module):\n \"\"\"\n Multi-Modal Transformer Block.\n\n Args:\n dim (int): Dimension of the input.\n dim_head (int): Dimension of each attention head.\n heads (int): Number of attention heads.\n dropout (float): Dropout rate.\n original_linear (nn.Linear): Linear layer for the original modality.\n auxiliar_linear (nn.Linear): Linear layer for the auxiliary modality.\n \"\"\"\n\n def __init__(\n self,\n dim: int,\n dim_head: int,\n heads: int,\n dropout: float,\n ff_mult: int,\n original_linear: nn.Linear,\n auxiliar_linear: nn.Linear,\n ffn_original_linear: nn.Linear,\n ffn_auxiliar_linear: nn.Linear,\n ffn_original_last_linear: nn.Linear,\n ffn_aux_last_linear: nn.Linear,\n ):\n super().__init__()\n self.dim = dim\n self.dim_head = dim_head\n self.heads = heads\n self.dropout = dropout\n self.ff_mult = ff_mult\n self.original_linear = original_linear\n self.auxiliar_linear = auxiliar_linear\n self.ffn_auxiliar_linear = ffn_auxiliar_linear\n self.ffn_original_last_linear = ffn_original_last_linear\n self.ffn_aux_last_linear = ffn_aux_last_linear\n\n self.ffn_1st_rep_linear = CrossModalReParametrization(\n ffn_original_linear(dim, dim * ff_mult),\n self.ffn_auxiliar_linear(dim, dim * ff_mult),\n )\n\n self.ffn_2nd_linear = CrossModalReParametrization(\n ffn_original_last_linear(dim * ff_mult, dim),\n ffn_aux_last_linear(dim * ff_mult, dim),\n )\n\n self.ffn = nn.Sequential(\n self.ffn_1st_rep_linear,\n nn.GELU(),\n nn.Dropout(),\n nn.LayerNorm(dim**ff_mult),\n nn.GELU(),\n self.ffn_2nd_linear,\n nn.LayerNorm(dim),\n )\n\n # Cross modal reparametrization\n self.reparametrization = CrossModalReParametrization(\n self.original_linear, self.auxiliar_linear\n )\n\n # Norm\n self.norm = nn.LayerNorm(self.dim)\n\n # Check for gpu\n self.is_cuda = torch.cuda.is_available()\n\n # Flash Attention\n self.mha = MultiheadAttention(\n dim,\n heads,\n dropout,\n subln=True,\n )\n\n def forward(self, x: Tensor):\n \"\"\"\n Forward pass of the Multi-Modal Transformer Block.\n\n Args:\n x (Tensor): Input tensor.\n\n Returns:\n Tensor: Output tensor.\n \"\"\"\n skip = x\n x = self.norm(x)\n\n # Cross Modal Reparametrization with the q, k, v\n q, k, v = (\n self.reparametrization(x),\n self.reparametrization(x),\n self.reparametrization(x),\n )\n print(f\"All shapes: {q.shape}, {k.shape}, {v.shape}\")\n\n # Attention\n attn = self.mha(q, k, v)\n\n # After attention projections\n attn_out = self.reparametrization(attn) + skip\n\n # Norm\n attn_out_norm = self.norm(attn_out)\n\n # Reparameterization again\n norm_then_reparam = self.reparametrization(attn_out_norm)\n\n # Reparameterization again\n reparam_them_reparam = self.reparametrization(\n norm_then_reparam\n )\n\n # FFN\n ffn = self.ffn(reparam_them_reparam)\n\n return self.norm(ffn)\n\n # return reparam_them_reparam + attn_out_norm\n\n\n\nclass M2PT(nn.Module):\n \"\"\"\n M2PT (Multi-Perspective Transformer) model.\n\n Args:\n dim (int): Dimension of the model.\n depth (int): Number of transformer blocks.\n num_tokens (int): Number of tokens in the input.\n dim_head (int): Dimension of each attention head.\n heads (int): Number of attention heads.\n dropout (float): Dropout rate.\n ff_mult (int): Multiplier for the feed-forward network dimension.\n original_linear (nn.Linear): Linear layer for the original input.\n auxiliar_linear (nn.Linear): Linear layer for the auxiliary input.\n ffn_original_linear (nn.Linear): Linear layer for the original input in the feed-forward network.\n ffn_auxiliar_linear (nn.Linear): Linear layer for the auxiliary input in the feed-forward network.\n ffn_original_last_linear (nn.Linear): Last linear layer for the original input in the feed-forward network.\n ffn_aux_last_linear (nn.Linear): Last linear layer for the auxiliary input in the feed-forward network.\n \"\"\"\n\n def __init__(\n self,\n dim: int,\n depth: int,\n num_tokens: int,\n dim_head: int,\n heads: int,\n dropout: float,\n ff_mult: int,\n original_linear: nn.Linear,\n auxiliar_linear: nn.Linear,\n ffn_original_linear: nn.Linear,\n ffn_auxiliar_linear: nn.Linear,\n ffn_original_last_linear: nn.Linear,\n ffn_aux_last_linear: nn.Linear,\n ):\n super().__init__()\n self.dim = dim\n self.depth = depth\n self.num_tokens = num_tokens\n self.dim_head = dim_head\n self.heads = heads\n self.dropout = dropout\n self.ff_mult = ff_mult\n self.original_linear = original_linear\n self.auxiliar_linear = auxiliar_linear\n self.ffn_original_linear = ffn_original_linear\n self.ffn_auxiliar_linear = ffn_auxiliar_linear\n self.ffn_original_last_linear = ffn_original_last_linear\n self.ffn_aux_last_linear = ffn_aux_last_linear\n \n self.layers = nn.ModuleList([])\n \n for _ in range(depth):\n self.layers.append(\n MPTransformerBlock(\n dim=dim,\n dim_head=dim_head,\n heads=heads,\n dropout=dropout,\n ff_mult=ff_mult,\n original_linear=original_linear,\n auxiliar_linear=auxiliar_linear,\n ffn_original_linear=ffn_original_linear,\n ffn_auxiliar_linear=ffn_auxiliar_linear,\n ffn_original_last_linear=ffn_original_last_linear,\n ffn_aux_last_linear=ffn_aux_last_linear,\n )\n )\n \n self.norm = nn.LayerNorm(dim)\n \n self.embedding = nn.Embedding(num_tokens, dim)\n \n self.to_out = nn.Sequential(\n nn.Linear(dim, num_tokens),\n nn.Softmax(dim=-1),\n # nn.LayerNorm(dim)\n )\n \n \n def forward(self, x: Tensor):\n \"\"\"\n Forward pass of the M2PT model.\n\n Args:\n x (Tensor): Input tensor of shape (batch_size, sequence_length).\n\n Returns:\n Tensor: Output tensor of shape (batch_size, sequence_length, num_tokens).\n \"\"\"\n x = self.embedding(x)\n \n for layer in self.layers:\n x = layer(x) + x\n \n x = self.to_out(x)\n \n return self.norm(x)","source_hash":"8ddc151100c77f47cb2257b0053f51a84733db5c392bcd8ddb66b0edd5aceb6c","truncated":false}
4
+ {"repo_id":"M2PT","entity_id":"py:m2pt.main.CrossModalReparamLinear","uri":"program://M2PT/class/m2pt.main.CrossModalReparamLinear#L8-L55","kind":"class","name":"CrossModalReparamLinear","path":"m2pt/main.py","language":"python","start_line":8,"end_line":55,"context_start_line":1,"context_end_line":75,"code":"import torch\nfrom torch import nn, Tensor\nfrom zeta.nn.attention.multihead_attention import MultiheadAttention\nfrom typing import List\nimport torch.nn.functional as F\n\n\nclass CrossModalReparamLinear(nn.Linear):\n \"\"\"\n Linear layer with cross-modal reparameterization.\n\n Args:\n in_features (int): Size of each input sample.\n out_features (int): Size of each output sample.\n bias (bool, optional): If set to False, the layer will not learn an additive bias. Default is True.\n origin_layer (nn.Linear, optional): Original linear layer to initialize the weight and bias from. Default is None.\n aux_weight (torch.Tensor, optional): Auxiliary weight tensor. Default is None.\n is_aux_trainable (bool, optional): If set to False, the auxiliary weight will not be trainable. Default is True.\n \"\"\"\n\n def __init__(\n self,\n in_features,\n out_features,\n bias=True,\n origin_layer=None,\n aux_weight=None,\n is_aux_trainable=True,\n ):\n super().__init__(in_features, out_features, bias)\n self.cross_modal_scale = nn.Parameter(torch.zeros(1))\n assert (\n self.weight.size() == aux_weight.size()\n ), \"Target weight and aux weight must have the same shape\"\n self.aux_weight = aux_weight\n self.aux_weight.requires_grad_(is_aux_trainable)\n if origin_layer is not None:\n with torch.no_grad():\n self.weight.copy_(origin_layer.weight)\n self.bias.copy_(origin_layer.bias)\n\n def forward(self, input):\n \"\"\"\n Forward pass of the CrossModalReparamLinear layer.\n\n Args:\n input (torch.Tensor): Input tensor.\n\n Returns:\n torch.Tensor: Output tensor.\n \"\"\"\n weight = (\n self.weight + self.cross_modal_scale * self.aux_weight\n )\n return F.linear(input, weight, self.bias)\n\n\ndef cross_modal_ffn(\n ffn_original_linear: nn.Linear,\n ffn_auxiliar_linear: nn.Linear,\n dim: int,\n ff_mult: int,\n dropout: int,\n ffn_original_last_linear: nn.Linear,\n ffn_aux_last_linear: nn.Linear,\n *args,\n **kwargs,\n):\n \"\"\"\n Cross-modal feed-forward network.\n\n Args:\n ffn_original_linear (nn.Linear): Linear layer for the original modality.\n ffn_auxiliar_linear (nn.Linear): Linear layer for the auxiliary modality.\n dim (int): Dimension of the input.","source_hash":"8ddc151100c77f47cb2257b0053f51a84733db5c392bcd8ddb66b0edd5aceb6c","truncated":false}
5
+ {"repo_id":"M2PT","entity_id":"py:m2pt.main.cross_modal_ffn","uri":"program://M2PT/function/m2pt.main.cross_modal_ffn#L58-L105","kind":"function","name":"cross_modal_ffn","path":"m2pt/main.py","language":"python","start_line":58,"end_line":105,"context_start_line":38,"context_end_line":125,"code":" with torch.no_grad():\n self.weight.copy_(origin_layer.weight)\n self.bias.copy_(origin_layer.bias)\n\n def forward(self, input):\n \"\"\"\n Forward pass of the CrossModalReparamLinear layer.\n\n Args:\n input (torch.Tensor): Input tensor.\n\n Returns:\n torch.Tensor: Output tensor.\n \"\"\"\n weight = (\n self.weight + self.cross_modal_scale * self.aux_weight\n )\n return F.linear(input, weight, self.bias)\n\n\ndef cross_modal_ffn(\n ffn_original_linear: nn.Linear,\n ffn_auxiliar_linear: nn.Linear,\n dim: int,\n ff_mult: int,\n dropout: int,\n ffn_original_last_linear: nn.Linear,\n ffn_aux_last_linear: nn.Linear,\n *args,\n **kwargs,\n):\n \"\"\"\n Cross-modal feed-forward network.\n\n Args:\n ffn_original_linear (nn.Linear): Linear layer for the original modality.\n ffn_auxiliar_linear (nn.Linear): Linear layer for the auxiliary modality.\n dim (int): Dimension of the input.\n ff_mult (int): Multiplier for the hidden dimension.\n dropout (int): Dropout rate.\n ffn_original_last_linear (nn.Linear): Linear layer for the original modality in the last step.\n ffn_aux_last_linear (nn.Linear): Linear layer for the auxiliary modality in the last step.\n *args: Variable length arguments.\n **kwargs: Keyword arguments.\n\n Returns:\n nn.Sequential: Sequential model representing the cross-modal feed-forward network.\n \"\"\"\n\n ffn_1st_rep_linear = CrossModalReParametrization(\n ffn_original_linear(dim, dim * ff_mult),\n ffn_auxiliar_linear(dim, dim * ff_mult),\n )\n\n ffn_2nd_linear = CrossModalReParametrization(\n ffn_original_last_linear(dim * ff_mult, dim),\n ffn_aux_last_linear(dim * ff_mult, dim),\n )\n\n return nn.Sequential(\n ffn_1st_rep_linear,\n nn.GELU(),\n nn.Dropout(dropout),\n nn.LayerNorm(dim**ff_mult),\n nn.GELU(),\n ffn_2nd_linear,\n nn.LayerNorm(dim),\n )\n\n\ndef build_cross_modal_reparam_linear(origin_layer, aux_layer):\n assert origin_layer.weight.size() == aux_layer.weight.size()\n return CrossModalReparamLinear(\n in_features=origin_layer.in_features,\n out_features=origin_layer.out_features,\n origin_layer=origin_layer,\n bias=origin_layer.bias is not None,\n aux_weight=aux_layer.weight,\n )\n\n\ndef _get_attr_by_name(obj, attr_name):\n attrs = attr_name.split(\".\")\n for a in attrs:\n obj = obj.__getattr__(a)\n return obj\n\n","source_hash":"8ddc151100c77f47cb2257b0053f51a84733db5c392bcd8ddb66b0edd5aceb6c","truncated":false}
6
+ {"repo_id":"M2PT","entity_id":"py:m2pt.main.build_cross_modal_reparam_linear","uri":"program://M2PT/function/m2pt.main.build_cross_modal_reparam_linear#L108-L116","kind":"function","name":"build_cross_modal_reparam_linear","path":"m2pt/main.py","language":"python","start_line":108,"end_line":116,"context_start_line":88,"context_end_line":136,"code":" ffn_original_linear(dim, dim * ff_mult),\n ffn_auxiliar_linear(dim, dim * ff_mult),\n )\n\n ffn_2nd_linear = CrossModalReParametrization(\n ffn_original_last_linear(dim * ff_mult, dim),\n ffn_aux_last_linear(dim * ff_mult, dim),\n )\n\n return nn.Sequential(\n ffn_1st_rep_linear,\n nn.GELU(),\n nn.Dropout(dropout),\n nn.LayerNorm(dim**ff_mult),\n nn.GELU(),\n ffn_2nd_linear,\n nn.LayerNorm(dim),\n )\n\n\ndef build_cross_modal_reparam_linear(origin_layer, aux_layer):\n assert origin_layer.weight.size() == aux_layer.weight.size()\n return CrossModalReparamLinear(\n in_features=origin_layer.in_features,\n out_features=origin_layer.out_features,\n origin_layer=origin_layer,\n bias=origin_layer.bias is not None,\n aux_weight=aux_layer.weight,\n )\n\n\ndef _get_attr_by_name(obj, attr_name):\n attrs = attr_name.split(\".\")\n for a in attrs:\n obj = obj.__getattr__(a)\n return obj\n\n\ndef _set_attr_by_name(obj, attr_name, attr_value):\n owner = obj\n attr_names = attr_name.split(\".\")\n if len(attr_names) > 1:\n for a in attr_names[:-1]:\n owner = owner.__getattr__(a)\n owner.__setattr__(attr_names[-1], attr_value)\n\n\ndef change_original_linear_to_reparam(\n target_module, aux_module, layer_name","source_hash":"8ddc151100c77f47cb2257b0053f51a84733db5c392bcd8ddb66b0edd5aceb6c","truncated":false}
7
+ {"repo_id":"M2PT","entity_id":"py:m2pt.main._get_attr_by_name","uri":"program://M2PT/function/m2pt.main._get_attr_by_name#L119-L123","kind":"function","name":"_get_attr_by_name","path":"m2pt/main.py","language":"python","start_line":119,"end_line":123,"context_start_line":99,"context_end_line":143,"code":" nn.GELU(),\n nn.Dropout(dropout),\n nn.LayerNorm(dim**ff_mult),\n nn.GELU(),\n ffn_2nd_linear,\n nn.LayerNorm(dim),\n )\n\n\ndef build_cross_modal_reparam_linear(origin_layer, aux_layer):\n assert origin_layer.weight.size() == aux_layer.weight.size()\n return CrossModalReparamLinear(\n in_features=origin_layer.in_features,\n out_features=origin_layer.out_features,\n origin_layer=origin_layer,\n bias=origin_layer.bias is not None,\n aux_weight=aux_layer.weight,\n )\n\n\ndef _get_attr_by_name(obj, attr_name):\n attrs = attr_name.split(\".\")\n for a in attrs:\n obj = obj.__getattr__(a)\n return obj\n\n\ndef _set_attr_by_name(obj, attr_name, attr_value):\n owner = obj\n attr_names = attr_name.split(\".\")\n if len(attr_names) > 1:\n for a in attr_names[:-1]:\n owner = owner.__getattr__(a)\n owner.__setattr__(attr_names[-1], attr_value)\n\n\ndef change_original_linear_to_reparam(\n target_module, aux_module, layer_name\n):\n origin_linear_layer = _get_attr_by_name(target_module, layer_name)\n aux_linear_layer = _get_attr_by_name(aux_module, layer_name)\n reparam_layer = build_cross_modal_reparam_linear(\n origin_linear_layer, aux_linear_layer\n )\n _set_attr_by_name(target_module, layer_name, reparam_layer)","source_hash":"8ddc151100c77f47cb2257b0053f51a84733db5c392bcd8ddb66b0edd5aceb6c","truncated":false}
8
+ {"repo_id":"M2PT","entity_id":"py:m2pt.main._set_attr_by_name","uri":"program://M2PT/function/m2pt.main._set_attr_by_name#L126-L132","kind":"function","name":"_set_attr_by_name","path":"m2pt/main.py","language":"python","start_line":126,"end_line":132,"context_start_line":106,"context_end_line":152,"code":"\n\ndef build_cross_modal_reparam_linear(origin_layer, aux_layer):\n assert origin_layer.weight.size() == aux_layer.weight.size()\n return CrossModalReparamLinear(\n in_features=origin_layer.in_features,\n out_features=origin_layer.out_features,\n origin_layer=origin_layer,\n bias=origin_layer.bias is not None,\n aux_weight=aux_layer.weight,\n )\n\n\ndef _get_attr_by_name(obj, attr_name):\n attrs = attr_name.split(\".\")\n for a in attrs:\n obj = obj.__getattr__(a)\n return obj\n\n\ndef _set_attr_by_name(obj, attr_name, attr_value):\n owner = obj\n attr_names = attr_name.split(\".\")\n if len(attr_names) > 1:\n for a in attr_names[:-1]:\n owner = owner.__getattr__(a)\n owner.__setattr__(attr_names[-1], attr_value)\n\n\ndef change_original_linear_to_reparam(\n target_module, aux_module, layer_name\n):\n origin_linear_layer = _get_attr_by_name(target_module, layer_name)\n aux_linear_layer = _get_attr_by_name(aux_module, layer_name)\n reparam_layer = build_cross_modal_reparam_linear(\n origin_linear_layer, aux_linear_layer\n )\n _set_attr_by_name(target_module, layer_name, reparam_layer)\n\n\ndef reparameterize_aux_into_target_model(\n target_model,\n aux_model,\n layer_names=(\"attn.qkv\", \"attn.proj\", \"mlp.fc1\", \"mlp.fc2\"),\n main_body_name=\"blocks\",\n):\n \"\"\"","source_hash":"8ddc151100c77f47cb2257b0053f51a84733db5c392bcd8ddb66b0edd5aceb6c","truncated":false}
9
+ {"repo_id":"M2PT","entity_id":"py:m2pt.main.change_original_linear_to_reparam","uri":"program://M2PT/function/m2pt.main.change_original_linear_to_reparam#L135-L143","kind":"function","name":"change_original_linear_to_reparam","path":"m2pt/main.py","language":"python","start_line":135,"end_line":143,"context_start_line":115,"context_end_line":163,"code":" aux_weight=aux_layer.weight,\n )\n\n\ndef _get_attr_by_name(obj, attr_name):\n attrs = attr_name.split(\".\")\n for a in attrs:\n obj = obj.__getattr__(a)\n return obj\n\n\ndef _set_attr_by_name(obj, attr_name, attr_value):\n owner = obj\n attr_names = attr_name.split(\".\")\n if len(attr_names) > 1:\n for a in attr_names[:-1]:\n owner = owner.__getattr__(a)\n owner.__setattr__(attr_names[-1], attr_value)\n\n\ndef change_original_linear_to_reparam(\n target_module, aux_module, layer_name\n):\n origin_linear_layer = _get_attr_by_name(target_module, layer_name)\n aux_linear_layer = _get_attr_by_name(aux_module, layer_name)\n reparam_layer = build_cross_modal_reparam_linear(\n origin_linear_layer, aux_linear_layer\n )\n _set_attr_by_name(target_module, layer_name, reparam_layer)\n\n\ndef reparameterize_aux_into_target_model(\n target_model,\n aux_model,\n layer_names=(\"attn.qkv\", \"attn.proj\", \"mlp.fc1\", \"mlp.fc2\"),\n main_body_name=\"blocks\",\n):\n \"\"\"\n Reparameterizes the auxiliary model into the target model by replacing specific layers with corresponding layers from the auxiliary model.\n\n Args:\n target_model (object): The target model to reparameterize.\n aux_model (object): The auxiliary model containing the replacement layers.\n layer_names (tuple, optional): The names of the layers to be replaced. Defaults to (\"attn.qkv\", \"attn.proj\", \"mlp.fc1\", \"mlp.fc2\").\n main_body_name (str, optional): The name of the main body of the models. Defaults to \"blocks\".\n \"\"\"\n target_transformer_blocks = _get_attr_by_name(\n target_model, main_body_name\n )","source_hash":"8ddc151100c77f47cb2257b0053f51a84733db5c392bcd8ddb66b0edd5aceb6c","truncated":false}
10
+ {"repo_id":"M2PT","entity_id":"py:m2pt.main.reparameterize_aux_into_target_model","uri":"program://M2PT/function/m2pt.main.reparameterize_aux_into_target_model#L146-L173","kind":"function","name":"reparameterize_aux_into_target_model","path":"m2pt/main.py","language":"python","start_line":146,"end_line":173,"context_start_line":126,"context_end_line":193,"code":"def _set_attr_by_name(obj, attr_name, attr_value):\n owner = obj\n attr_names = attr_name.split(\".\")\n if len(attr_names) > 1:\n for a in attr_names[:-1]:\n owner = owner.__getattr__(a)\n owner.__setattr__(attr_names[-1], attr_value)\n\n\ndef change_original_linear_to_reparam(\n target_module, aux_module, layer_name\n):\n origin_linear_layer = _get_attr_by_name(target_module, layer_name)\n aux_linear_layer = _get_attr_by_name(aux_module, layer_name)\n reparam_layer = build_cross_modal_reparam_linear(\n origin_linear_layer, aux_linear_layer\n )\n _set_attr_by_name(target_module, layer_name, reparam_layer)\n\n\ndef reparameterize_aux_into_target_model(\n target_model,\n aux_model,\n layer_names=(\"attn.qkv\", \"attn.proj\", \"mlp.fc1\", \"mlp.fc2\"),\n main_body_name=\"blocks\",\n):\n \"\"\"\n Reparameterizes the auxiliary model into the target model by replacing specific layers with corresponding layers from the auxiliary model.\n\n Args:\n target_model (object): The target model to reparameterize.\n aux_model (object): The auxiliary model containing the replacement layers.\n layer_names (tuple, optional): The names of the layers to be replaced. Defaults to (\"attn.qkv\", \"attn.proj\", \"mlp.fc1\", \"mlp.fc2\").\n main_body_name (str, optional): The name of the main body of the models. Defaults to \"blocks\".\n \"\"\"\n target_transformer_blocks = _get_attr_by_name(\n target_model, main_body_name\n )\n aux_transformer_blocks = _get_attr_by_name(\n aux_model, main_body_name\n )\n for target_block, aux_block in zip(\n target_transformer_blocks, aux_transformer_blocks\n ):\n for layer_name in layer_names:\n change_original_linear_to_reparam(\n target_block, aux_block, layer_name\n )\n\n\nclass CrossModalReParametrization(nn.Module):\n \"\"\"\n A module for cross-modal reparametrization.\n\n Args:\n original_linear (nn.Linear): The original linear layer.\n auxiliary_linear (nn.Linear): The auxiliary linear layer.\n\n Attributes:\n cross_modal_scale (nn.Parameter): The scale parameter for cross-modal reparametrization.\n\n Methods:\n forward(x: Tensor) -> Tensor: Performs forward pass through the module.\n merge(): Merges the weights and biases of the original and auxiliary linear layers.\n \"\"\"\n\n def __init__(\n self,","source_hash":"8ddc151100c77f47cb2257b0053f51a84733db5c392bcd8ddb66b0edd5aceb6c","truncated":false}
11
+ {"repo_id":"M2PT","entity_id":"py:m2pt.main.CrossModalReParametrization","uri":"program://M2PT/class/m2pt.main.CrossModalReParametrization#L176-L224","kind":"class","name":"CrossModalReParametrization","path":"m2pt/main.py","language":"python","start_line":176,"end_line":224,"context_start_line":156,"context_end_line":244,"code":" target_model (object): The target model to reparameterize.\n aux_model (object): The auxiliary model containing the replacement layers.\n layer_names (tuple, optional): The names of the layers to be replaced. Defaults to (\"attn.qkv\", \"attn.proj\", \"mlp.fc1\", \"mlp.fc2\").\n main_body_name (str, optional): The name of the main body of the models. Defaults to \"blocks\".\n \"\"\"\n target_transformer_blocks = _get_attr_by_name(\n target_model, main_body_name\n )\n aux_transformer_blocks = _get_attr_by_name(\n aux_model, main_body_name\n )\n for target_block, aux_block in zip(\n target_transformer_blocks, aux_transformer_blocks\n ):\n for layer_name in layer_names:\n change_original_linear_to_reparam(\n target_block, aux_block, layer_name\n )\n\n\nclass CrossModalReParametrization(nn.Module):\n \"\"\"\n A module for cross-modal reparametrization.\n\n Args:\n original_linear (nn.Linear): The original linear layer.\n auxiliary_linear (nn.Linear): The auxiliary linear layer.\n\n Attributes:\n cross_modal_scale (nn.Parameter): The scale parameter for cross-modal reparametrization.\n\n Methods:\n forward(x: Tensor) -> Tensor: Performs forward pass through the module.\n merge(): Merges the weights and biases of the original and auxiliary linear layers.\n \"\"\"\n\n def __init__(\n self,\n original_linear: nn.Linear,\n auxiliary_linear: nn.Linear,\n linears: List[nn.Linear] = None,\n ):\n super().__init__()\n self.original_linear = original_linear\n self.auxiliary_linear = auxiliary_linear\n self.cross_modal_scale = nn.Parameter(torch.zeros(1))\n\n def forward(self, x: Tensor) -> Tensor:\n combined_weight = (\n self.original_linear.weight\n + self.cross_modal_scale * self.auxiliary_linear.weight\n )\n return nn.functional.linear(\n x, combined_weight, self.original_linear.bias\n )\n\n def merge(self):\n self.original_linear.weight.data.add_(\n self.cross_modal_scale.item()\n * self.auxiliary_linear.weight.data\n )\n if (\n self.original_linear.bias is not None\n and self.auxiliary_linear.bias is not None\n ):\n self.original_linear.bias.data.add_(\n self.cross_modal_scale.item()\n * self.auxiliary_linear.bias.data\n )\n\n\nclass MPTransformerBlock(nn.Module):\n \"\"\"\n Multi-Modal Transformer Block.\n\n Args:\n dim (int): Dimension of the input.\n dim_head (int): Dimension of each attention head.\n heads (int): Number of attention heads.\n dropout (float): Dropout rate.\n original_linear (nn.Linear): Linear layer for the original modality.\n auxiliar_linear (nn.Linear): Linear layer for the auxiliary modality.\n \"\"\"\n\n def __init__(\n self,\n dim: int,\n dim_head: int,\n heads: int,","source_hash":"8ddc151100c77f47cb2257b0053f51a84733db5c392bcd8ddb66b0edd5aceb6c","truncated":false}
12
+ {"repo_id":"M2PT","entity_id":"py:m2pt.main.MPTransformerBlock","uri":"program://M2PT/class/m2pt.main.MPTransformerBlock#L227-L346","kind":"class","name":"MPTransformerBlock","path":"m2pt/main.py","language":"python","start_line":227,"end_line":346,"context_start_line":207,"context_end_line":366,"code":" )\n return nn.functional.linear(\n x, combined_weight, self.original_linear.bias\n )\n\n def merge(self):\n self.original_linear.weight.data.add_(\n self.cross_modal_scale.item()\n * self.auxiliary_linear.weight.data\n )\n if (\n self.original_linear.bias is not None\n and self.auxiliary_linear.bias is not None\n ):\n self.original_linear.bias.data.add_(\n self.cross_modal_scale.item()\n * self.auxiliary_linear.bias.data\n )\n\n\nclass MPTransformerBlock(nn.Module):\n \"\"\"\n Multi-Modal Transformer Block.\n\n Args:\n dim (int): Dimension of the input.\n dim_head (int): Dimension of each attention head.\n heads (int): Number of attention heads.\n dropout (float): Dropout rate.\n original_linear (nn.Linear): Linear layer for the original modality.\n auxiliar_linear (nn.Linear): Linear layer for the auxiliary modality.\n \"\"\"\n\n def __init__(\n self,\n dim: int,\n dim_head: int,\n heads: int,\n dropout: float,\n ff_mult: int,\n original_linear: nn.Linear,\n auxiliar_linear: nn.Linear,\n ffn_original_linear: nn.Linear,\n ffn_auxiliar_linear: nn.Linear,\n ffn_original_last_linear: nn.Linear,\n ffn_aux_last_linear: nn.Linear,\n ):\n super().__init__()\n self.dim = dim\n self.dim_head = dim_head\n self.heads = heads\n self.dropout = dropout\n self.ff_mult = ff_mult\n self.original_linear = original_linear\n self.auxiliar_linear = auxiliar_linear\n self.ffn_auxiliar_linear = ffn_auxiliar_linear\n self.ffn_original_last_linear = ffn_original_last_linear\n self.ffn_aux_last_linear = ffn_aux_last_linear\n\n self.ffn_1st_rep_linear = CrossModalReParametrization(\n ffn_original_linear(dim, dim * ff_mult),\n self.ffn_auxiliar_linear(dim, dim * ff_mult),\n )\n\n self.ffn_2nd_linear = CrossModalReParametrization(\n ffn_original_last_linear(dim * ff_mult, dim),\n ffn_aux_last_linear(dim * ff_mult, dim),\n )\n\n self.ffn = nn.Sequential(\n self.ffn_1st_rep_linear,\n nn.GELU(),\n nn.Dropout(),\n nn.LayerNorm(dim**ff_mult),\n nn.GELU(),\n self.ffn_2nd_linear,\n nn.LayerNorm(dim),\n )\n\n # Cross modal reparametrization\n self.reparametrization = CrossModalReParametrization(\n self.original_linear, self.auxiliar_linear\n )\n\n # Norm\n self.norm = nn.LayerNorm(self.dim)\n\n # Check for gpu\n self.is_cuda = torch.cuda.is_available()\n\n # Flash Attention\n self.mha = MultiheadAttention(\n dim,\n heads,\n dropout,\n subln=True,\n )\n\n def forward(self, x: Tensor):\n \"\"\"\n Forward pass of the Multi-Modal Transformer Block.\n\n Args:\n x (Tensor): Input tensor.\n\n Returns:\n Tensor: Output tensor.\n \"\"\"\n skip = x\n x = self.norm(x)\n\n # Cross Modal Reparametrization with the q, k, v\n q, k, v = (\n self.reparametrization(x),\n self.reparametrization(x),\n self.reparametrization(x),\n )\n print(f\"All shapes: {q.shape}, {k.shape}, {v.shape}\")\n\n # Attention\n attn = self.mha(q, k, v)\n\n # After attention projections\n attn_out = self.reparametrization(attn) + skip\n\n # Norm\n attn_out_norm = self.norm(attn_out)\n\n # Reparameterization again\n norm_then_reparam = self.reparametrization(attn_out_norm)\n\n # Reparameterization again\n reparam_them_reparam = self.reparametrization(\n norm_then_reparam\n )\n\n # FFN\n ffn = self.ffn(reparam_them_reparam)\n\n return self.norm(ffn)\n\n # return reparam_them_reparam + attn_out_norm\n\n\n\nclass M2PT(nn.Module):\n \"\"\"\n M2PT (Multi-Perspective Transformer) model.\n\n Args:\n dim (int): Dimension of the model.\n depth (int): Number of transformer blocks.\n num_tokens (int): Number of tokens in the input.\n dim_head (int): Dimension of each attention head.\n heads (int): Number of attention heads.\n dropout (float): Dropout rate.\n ff_mult (int): Multiplier for the feed-forward network dimension.\n original_linear (nn.Linear): Linear layer for the original input.\n auxiliar_linear (nn.Linear): Linear layer for the auxiliary input.\n ffn_original_linear (nn.Linear): Linear layer for the original input in the feed-forward network.","source_hash":"8ddc151100c77f47cb2257b0053f51a84733db5c392bcd8ddb66b0edd5aceb6c","truncated":false}
13
+ {"repo_id":"M2PT","entity_id":"py:m2pt.main.M2PT","uri":"program://M2PT/class/m2pt.main.M2PT#L352-L450","kind":"class","name":"M2PT","path":"m2pt/main.py","language":"python","start_line":352,"end_line":450,"context_start_line":332,"context_end_line":450,"code":" # Norm\n attn_out_norm = self.norm(attn_out)\n\n # Reparameterization again\n norm_then_reparam = self.reparametrization(attn_out_norm)\n\n # Reparameterization again\n reparam_them_reparam = self.reparametrization(\n norm_then_reparam\n )\n\n # FFN\n ffn = self.ffn(reparam_them_reparam)\n\n return self.norm(ffn)\n\n # return reparam_them_reparam + attn_out_norm\n\n\n\nclass M2PT(nn.Module):\n \"\"\"\n M2PT (Multi-Perspective Transformer) model.\n\n Args:\n dim (int): Dimension of the model.\n depth (int): Number of transformer blocks.\n num_tokens (int): Number of tokens in the input.\n dim_head (int): Dimension of each attention head.\n heads (int): Number of attention heads.\n dropout (float): Dropout rate.\n ff_mult (int): Multiplier for the feed-forward network dimension.\n original_linear (nn.Linear): Linear layer for the original input.\n auxiliar_linear (nn.Linear): Linear layer for the auxiliary input.\n ffn_original_linear (nn.Linear): Linear layer for the original input in the feed-forward network.\n ffn_auxiliar_linear (nn.Linear): Linear layer for the auxiliary input in the feed-forward network.\n ffn_original_last_linear (nn.Linear): Last linear layer for the original input in the feed-forward network.\n ffn_aux_last_linear (nn.Linear): Last linear layer for the auxiliary input in the feed-forward network.\n \"\"\"\n\n def __init__(\n self,\n dim: int,\n depth: int,\n num_tokens: int,\n dim_head: int,\n heads: int,\n dropout: float,\n ff_mult: int,\n original_linear: nn.Linear,\n auxiliar_linear: nn.Linear,\n ffn_original_linear: nn.Linear,\n ffn_auxiliar_linear: nn.Linear,\n ffn_original_last_linear: nn.Linear,\n ffn_aux_last_linear: nn.Linear,\n ):\n super().__init__()\n self.dim = dim\n self.depth = depth\n self.num_tokens = num_tokens\n self.dim_head = dim_head\n self.heads = heads\n self.dropout = dropout\n self.ff_mult = ff_mult\n self.original_linear = original_linear\n self.auxiliar_linear = auxiliar_linear\n self.ffn_original_linear = ffn_original_linear\n self.ffn_auxiliar_linear = ffn_auxiliar_linear\n self.ffn_original_last_linear = ffn_original_last_linear\n self.ffn_aux_last_linear = ffn_aux_last_linear\n \n self.layers = nn.ModuleList([])\n \n for _ in range(depth):\n self.layers.append(\n MPTransformerBlock(\n dim=dim,\n dim_head=dim_head,\n heads=heads,\n dropout=dropout,\n ff_mult=ff_mult,\n original_linear=original_linear,\n auxiliar_linear=auxiliar_linear,\n ffn_original_linear=ffn_original_linear,\n ffn_auxiliar_linear=ffn_auxiliar_linear,\n ffn_original_last_linear=ffn_original_last_linear,\n ffn_aux_last_linear=ffn_aux_last_linear,\n )\n )\n \n self.norm = nn.LayerNorm(dim)\n \n self.embedding = nn.Embedding(num_tokens, dim)\n \n self.to_out = nn.Sequential(\n nn.Linear(dim, num_tokens),\n nn.Softmax(dim=-1),\n # nn.LayerNorm(dim)\n )\n \n \n def forward(self, x: Tensor):\n \"\"\"\n Forward pass of the M2PT model.\n\n Args:\n x (Tensor): Input tensor of shape (batch_size, sequence_length).\n\n Returns:\n Tensor: Output tensor of shape (batch_size, sequence_length, num_tokens).\n \"\"\"\n x = self.embedding(x)\n \n for layer in self.layers:\n x = layer(x) + x\n \n x = self.to_out(x)\n \n return self.norm(x)","source_hash":"8ddc151100c77f47cb2257b0053f51a84733db5c392bcd8ddb66b0edd5aceb6c","truncated":false}
14
+ {"repo_id":"M2PT","entity_id":"py:m2pt.main.__init__","uri":"program://M2PT/function/m2pt.main.__init__#L372-L430","kind":"function","name":"__init__","path":"m2pt/main.py","language":"python","start_line":372,"end_line":430,"context_start_line":352,"context_end_line":450,"code":"class M2PT(nn.Module):\n \"\"\"\n M2PT (Multi-Perspective Transformer) model.\n\n Args:\n dim (int): Dimension of the model.\n depth (int): Number of transformer blocks.\n num_tokens (int): Number of tokens in the input.\n dim_head (int): Dimension of each attention head.\n heads (int): Number of attention heads.\n dropout (float): Dropout rate.\n ff_mult (int): Multiplier for the feed-forward network dimension.\n original_linear (nn.Linear): Linear layer for the original input.\n auxiliar_linear (nn.Linear): Linear layer for the auxiliary input.\n ffn_original_linear (nn.Linear): Linear layer for the original input in the feed-forward network.\n ffn_auxiliar_linear (nn.Linear): Linear layer for the auxiliary input in the feed-forward network.\n ffn_original_last_linear (nn.Linear): Last linear layer for the original input in the feed-forward network.\n ffn_aux_last_linear (nn.Linear): Last linear layer for the auxiliary input in the feed-forward network.\n \"\"\"\n\n def __init__(\n self,\n dim: int,\n depth: int,\n num_tokens: int,\n dim_head: int,\n heads: int,\n dropout: float,\n ff_mult: int,\n original_linear: nn.Linear,\n auxiliar_linear: nn.Linear,\n ffn_original_linear: nn.Linear,\n ffn_auxiliar_linear: nn.Linear,\n ffn_original_last_linear: nn.Linear,\n ffn_aux_last_linear: nn.Linear,\n ):\n super().__init__()\n self.dim = dim\n self.depth = depth\n self.num_tokens = num_tokens\n self.dim_head = dim_head\n self.heads = heads\n self.dropout = dropout\n self.ff_mult = ff_mult\n self.original_linear = original_linear\n self.auxiliar_linear = auxiliar_linear\n self.ffn_original_linear = ffn_original_linear\n self.ffn_auxiliar_linear = ffn_auxiliar_linear\n self.ffn_original_last_linear = ffn_original_last_linear\n self.ffn_aux_last_linear = ffn_aux_last_linear\n \n self.layers = nn.ModuleList([])\n \n for _ in range(depth):\n self.layers.append(\n MPTransformerBlock(\n dim=dim,\n dim_head=dim_head,\n heads=heads,\n dropout=dropout,\n ff_mult=ff_mult,\n original_linear=original_linear,\n auxiliar_linear=auxiliar_linear,\n ffn_original_linear=ffn_original_linear,\n ffn_auxiliar_linear=ffn_auxiliar_linear,\n ffn_original_last_linear=ffn_original_last_linear,\n ffn_aux_last_linear=ffn_aux_last_linear,\n )\n )\n \n self.norm = nn.LayerNorm(dim)\n \n self.embedding = nn.Embedding(num_tokens, dim)\n \n self.to_out = nn.Sequential(\n nn.Linear(dim, num_tokens),\n nn.Softmax(dim=-1),\n # nn.LayerNorm(dim)\n )\n \n \n def forward(self, x: Tensor):\n \"\"\"\n Forward pass of the M2PT model.\n\n Args:\n x (Tensor): Input tensor of shape (batch_size, sequence_length).\n\n Returns:\n Tensor: Output tensor of shape (batch_size, sequence_length, num_tokens).\n \"\"\"\n x = self.embedding(x)\n \n for layer in self.layers:\n x = layer(x) + x\n \n x = self.to_out(x)\n \n return self.norm(x)","source_hash":"8ddc151100c77f47cb2257b0053f51a84733db5c392bcd8ddb66b0edd5aceb6c","truncated":false}
15
+ {"repo_id":"M2PT","entity_id":"py:m2pt.main.forward","uri":"program://M2PT/function/m2pt.main.forward#L433-L450","kind":"function","name":"forward","path":"m2pt/main.py","language":"python","start_line":433,"end_line":450,"context_start_line":413,"context_end_line":450,"code":" original_linear=original_linear,\n auxiliar_linear=auxiliar_linear,\n ffn_original_linear=ffn_original_linear,\n ffn_auxiliar_linear=ffn_auxiliar_linear,\n ffn_original_last_linear=ffn_original_last_linear,\n ffn_aux_last_linear=ffn_aux_last_linear,\n )\n )\n \n self.norm = nn.LayerNorm(dim)\n \n self.embedding = nn.Embedding(num_tokens, dim)\n \n self.to_out = nn.Sequential(\n nn.Linear(dim, num_tokens),\n nn.Softmax(dim=-1),\n # nn.LayerNorm(dim)\n )\n \n \n def forward(self, x: Tensor):\n \"\"\"\n Forward pass of the M2PT model.\n\n Args:\n x (Tensor): Input tensor of shape (batch_size, sequence_length).\n\n Returns:\n Tensor: Output tensor of shape (batch_size, sequence_length, num_tokens).\n \"\"\"\n x = self.embedding(x)\n \n for layer in self.layers:\n x = layer(x) + x\n \n x = self.to_out(x)\n \n return self.norm(x)","source_hash":"8ddc151100c77f47cb2257b0053f51a84733db5c392bcd8ddb66b0edd5aceb6c","truncated":false}
16
+ {"repo_id":"M2PT","entity_id":"py:m2pt.main.merge","uri":"program://M2PT/function/m2pt.main.merge#L212-L224","kind":"function","name":"merge","path":"m2pt/main.py","language":"python","start_line":212,"end_line":224,"context_start_line":192,"context_end_line":244,"code":" def __init__(\n self,\n original_linear: nn.Linear,\n auxiliary_linear: nn.Linear,\n linears: List[nn.Linear] = None,\n ):\n super().__init__()\n self.original_linear = original_linear\n self.auxiliary_linear = auxiliary_linear\n self.cross_modal_scale = nn.Parameter(torch.zeros(1))\n\n def forward(self, x: Tensor) -> Tensor:\n combined_weight = (\n self.original_linear.weight\n + self.cross_modal_scale * self.auxiliary_linear.weight\n )\n return nn.functional.linear(\n x, combined_weight, self.original_linear.bias\n )\n\n def merge(self):\n self.original_linear.weight.data.add_(\n self.cross_modal_scale.item()\n * self.auxiliary_linear.weight.data\n )\n if (\n self.original_linear.bias is not None\n and self.auxiliary_linear.bias is not None\n ):\n self.original_linear.bias.data.add_(\n self.cross_modal_scale.item()\n * self.auxiliary_linear.bias.data\n )\n\n\nclass MPTransformerBlock(nn.Module):\n \"\"\"\n Multi-Modal Transformer Block.\n\n Args:\n dim (int): Dimension of the input.\n dim_head (int): Dimension of each attention head.\n heads (int): Number of attention heads.\n dropout (float): Dropout rate.\n original_linear (nn.Linear): Linear layer for the original modality.\n auxiliar_linear (nn.Linear): Linear layer for the auxiliary modality.\n \"\"\"\n\n def __init__(\n self,\n dim: int,\n dim_head: int,\n heads: int,","source_hash":"8ddc151100c77f47cb2257b0053f51a84733db5c392bcd8ddb66b0edd5aceb6c","truncated":false}
17
+ {"repo_id":"M2PT","entity_id":"file:model_example.py","uri":"program://M2PT/file/model_example.py","kind":"file","name":"model_example.py","path":"model_example.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import torch\nfrom torch import nn\nfrom m2pt.main import M2PT\n\n# Create an instance of the MPTransformerBlock class with the specified parameters\nmodel = M2PT(\n dim=512, # Dimension of the input and output tensors\n num_tokens=10000,\n depth=6,\n dim_head=64, # Dimension of each attention head\n heads=8, # Number of attention heads\n dropout=0.1, # Dropout rate\n ff_mult=4, # Multiplier for the dimension of the feed-forward network\n original_linear=nn.Linear(512, 512), # Linear layer for the original input tensor\n auxiliar_linear=nn.Linear(512, 512), # Linear layer for the auxiliary input tensor\n ffn_original_linear=nn.Linear, # Linear layer for the original input tensor in the feed-forward network\n ffn_auxiliar_linear=nn.Linear, # Linear layer for the auxiliary input tensor in the feed-forward network\n ffn_original_last_linear=nn.Linear, # Last linear layer for the original input tensor in the feed-forward network\n ffn_aux_last_linear=nn.Linear, # Last linear layer for the auxiliary input tensor in the feed-forward network\n)\n","source_hash":"d24a5209a920e60f35f2a1c3e4a14ff7b796d1b3698ef04d0b072e913a127412","truncated":false}
18
+ {"repo_id":"M2PT","entity_id":"file:example.py","uri":"program://M2PT/file/example.py","kind":"file","name":"example.py","path":"example.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import torch\nfrom torch import nn\nfrom m2pt import MPTransformerBlock\n\n# Create an instance of the MPTransformerBlock class with the specified parameters\nmodel = MPTransformerBlock(\n dim=512, # Dimension of the input and output tensors\n dim_head=64, # Dimension of each attention head\n heads=8, # Number of attention heads\n dropout=0.1, # Dropout rate\n ff_mult=4, # Multiplier for the dimension of the feed-forward network\n original_linear=nn.Linear(512, 512), # Linear layer for the original input tensor\n auxiliar_linear=nn.Linear(512, 512), # Linear layer for the auxiliary input tensor\n ffn_original_linear=nn.Linear, # Linear layer for the original input tensor in the feed-forward network\n ffn_auxiliar_linear=nn.Linear, # Linear layer for the auxiliary input tensor in the feed-forward network\n ffn_original_last_linear=nn.Linear, # Last linear layer for the original input tensor in the feed-forward network\n ffn_aux_last_linear=nn.Linear, # Last linear layer for the auxiliary input tensor in the feed-forward network\n)\n\n# Create a 3D tensor with shape B x S x D\nx = torch.randn(1, 512, 512)","source_hash":"400c144f38a8cc5a7dd896fdda7b083f58ddd38248e9b9a78a0fa99c65a806a4","truncated":false}
19
+ {"repo_id":"M2PT","entity_id":"file:m2pt/main.py","uri":"program://M2PT/file/m2pt/main.py","kind":"file","name":"m2pt/main.py","path":"m2pt/main.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import torch\nfrom torch import nn, Tensor\nfrom zeta.nn.attention.multihead_attention import MultiheadAttention\nfrom typing import List\nimport torch.nn.functional as F\n\n\nclass CrossModalReparamLinear(nn.Linear):\n \"\"\"\n Linear layer with cross-modal reparameterization.\n\n Args:\n in_features (int): Size of each input sample.\n out_features (int): Size of each output sample.\n bias (bool, optional): If set to False, the layer will not learn an additive bias. Default is True.\n origin_layer (nn.Linear, optional): Original linear layer to initialize the weight and bias from. Default is None.\n aux_weight (torch.Tensor, optional): Auxiliary weight tensor. Default is None.\n is_aux_trainable (bool, optional): If set to False, the auxiliary weight will not be trainable. Default is True.\n \"\"\"\n\n def __init__(","source_hash":"8ddc151100c77f47cb2257b0053f51a84733db5c392bcd8ddb66b0edd5aceb6c","truncated":false}
20
+ {"repo_id":"M2PT","entity_id":"file:m2pt/__init__.py","uri":"program://M2PT/file/m2pt/__init__.py","kind":"file","name":"m2pt/__init__.py","path":"m2pt/__init__.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":16,"code":"from m2pt.main import (\n CrossModalReparamLinear,\n cross_modal_ffn,\n reparameterize_aux_into_target_model,\n CrossModalReParametrization,\n MPTransformerBlock,\n)\n\n\n__all__ = [\n \"CrossModalReparamLinear\",\n \"cross_modal_ffn\",\n \"reparameterize_aux_into_target_model\",\n \"CrossModalReParametrization\",\n \"MPTransformerBlock\",\n]","source_hash":"649706ded706fbf75470f96549eb6bd23ff887ab6e879e9e1fc2473833252159","truncated":false}
source_snippets/Mediapipe-VR-Fullbody-Tracking.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
source_snippets/Megatron-Energon.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
source_snippets/Megatron-LM.jsonl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:00cd4781098072269ed2cc1512c44b2bb89a46e3195012e0bbc4cf69a9cae0ed
3
+ size 41655151
source_snippets/MetaGPT.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
source_snippets/MetaMathQA.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
source_snippets/MoE-LLaVA.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
source_snippets/Model-Optimizer.jsonl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:75969da8cb7db0556876f1e051cd0980c2e8a9a9edb5bec32268d00ac48337c0
3
+ size 29597354
source_snippets/ModuleFormer.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
source_snippets/OSWorld.jsonl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e29e0c704fbeee2cb251ba54b41699efeceaf250b9683382b0909a8ebab0b372
3
+ size 17583747
source_snippets/OneFormer.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
source_snippets/OpenAgents.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
source_snippets/OpenStrawberry.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
source_snippets/OpenWebVoyager.jsonl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bf0de50278cc14d71f94cd77078885fe6db61b4d52e2cab809948a0549e02c69
3
+ size 17377976
source_snippets/Program_Conditioned_Adapter.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
source_snippets/Python.jsonl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:97948ae52ed4e6b1ac3b56c9e30ca7457f725ddf3f22108b2b0d5ad5c69e98a6
3
+ size 14084443
source_snippets/SuperAlignment.jsonl ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {"repo_id":"SuperAlignment","entity_id":"py:train_example","uri":"program://SuperAlignment/module/train_example#L1-L60","kind":"module","name":"train_example","path":"train_example.py","language":"python","start_line":1,"end_line":60,"context_start_line":1,"context_end_line":60,"code":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torchvision.models import resnet18, resnet50 # Example models\n\n# Define the teacher (weak model) and student (strong model)\nteacher_model = resnet18(pretrained=True)\nstudent_model = resnet50(pretrained=True)\n\n\n# Custom Adaptive Confidence Distillation Loss\nclass AdaptiveConfidenceDistillationLoss(nn.Module):\n def __init__(self, temperature=1.0):\n super().__init__()\n self.temperature = temperature\n self.ce_loss = nn.CrossEntropyLoss()\n\n def forward(self, student_logits, teacher_logits, targets):\n # Soften probabilities\n soft_teacher_probs = F.softmax(teacher_logits / self.temperature, dim=1)\n soft_student_probs = F.log_softmax(student_logits / self.temperature, dim=1)\n\n # Calculate the KL Divergence for the soft targets\n distillation_loss = F.kl_div(\n soft_student_probs, soft_teacher_probs, reduction=\"batchmean\"\n )\n\n # Calculate the standard loss with hard targets\n hard_loss = self.ce_loss(student_logits, targets)\n\n # Adaptive weighting could be implemented here based on confidence\n # For simplicity, this example uses a fixed ratio\n return distillation_loss + hard_loss\n\n\n# Example Training Loop Skeleton\ndef train_model(student_model, teacher_model, dataloader, optimizer, device):\n student_model.train()\n teacher_model.eval() # Teacher model should be in eval mode\n\n loss_fn = AdaptiveConfidenceDistillationLoss(temperature=2.0)\n\n for inputs, labels in dataloader:\n inputs, labels = inputs.to(device), labels.to(device)\n\n optimizer.zero_grad()\n\n with torch.no_grad():\n teacher_outputs = teacher_model(inputs)\n\n student_outputs = student_model(inputs)\n\n loss = loss_fn(student_outputs, teacher_outputs, labels)\n loss.backward()\n optimizer.step()\n\n\n# Example usage\n# Assuming `dataloader`, `optimizer`, and `device` are defined\n# train_model(student_model, teacher_model, dataloader, optimizer, device)","source_hash":"1d853ce261864b7b90ca11a013e5ff6feff4aa1e87a9d5d20878083564c9aba6","truncated":false}
2
+ {"repo_id":"SuperAlignment","entity_id":"py:train_example.AdaptiveConfidenceDistillationLoss","uri":"program://SuperAlignment/class/train_example.AdaptiveConfidenceDistillationLoss#L12-L33","kind":"class","name":"AdaptiveConfidenceDistillationLoss","path":"train_example.py","language":"python","start_line":12,"end_line":33,"context_start_line":1,"context_end_line":53,"code":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torchvision.models import resnet18, resnet50 # Example models\n\n# Define the teacher (weak model) and student (strong model)\nteacher_model = resnet18(pretrained=True)\nstudent_model = resnet50(pretrained=True)\n\n\n# Custom Adaptive Confidence Distillation Loss\nclass AdaptiveConfidenceDistillationLoss(nn.Module):\n def __init__(self, temperature=1.0):\n super().__init__()\n self.temperature = temperature\n self.ce_loss = nn.CrossEntropyLoss()\n\n def forward(self, student_logits, teacher_logits, targets):\n # Soften probabilities\n soft_teacher_probs = F.softmax(teacher_logits / self.temperature, dim=1)\n soft_student_probs = F.log_softmax(student_logits / self.temperature, dim=1)\n\n # Calculate the KL Divergence for the soft targets\n distillation_loss = F.kl_div(\n soft_student_probs, soft_teacher_probs, reduction=\"batchmean\"\n )\n\n # Calculate the standard loss with hard targets\n hard_loss = self.ce_loss(student_logits, targets)\n\n # Adaptive weighting could be implemented here based on confidence\n # For simplicity, this example uses a fixed ratio\n return distillation_loss + hard_loss\n\n\n# Example Training Loop Skeleton\ndef train_model(student_model, teacher_model, dataloader, optimizer, device):\n student_model.train()\n teacher_model.eval() # Teacher model should be in eval mode\n\n loss_fn = AdaptiveConfidenceDistillationLoss(temperature=2.0)\n\n for inputs, labels in dataloader:\n inputs, labels = inputs.to(device), labels.to(device)\n\n optimizer.zero_grad()\n\n with torch.no_grad():\n teacher_outputs = teacher_model(inputs)\n\n student_outputs = student_model(inputs)\n\n loss = loss_fn(student_outputs, teacher_outputs, labels)","source_hash":"1d853ce261864b7b90ca11a013e5ff6feff4aa1e87a9d5d20878083564c9aba6","truncated":false}
3
+ {"repo_id":"SuperAlignment","entity_id":"py:train_example.train_model","uri":"program://SuperAlignment/function/train_example.train_model#L37-L55","kind":"function","name":"train_model","path":"train_example.py","language":"python","start_line":37,"end_line":55,"context_start_line":17,"context_end_line":60,"code":"\n def forward(self, student_logits, teacher_logits, targets):\n # Soften probabilities\n soft_teacher_probs = F.softmax(teacher_logits / self.temperature, dim=1)\n soft_student_probs = F.log_softmax(student_logits / self.temperature, dim=1)\n\n # Calculate the KL Divergence for the soft targets\n distillation_loss = F.kl_div(\n soft_student_probs, soft_teacher_probs, reduction=\"batchmean\"\n )\n\n # Calculate the standard loss with hard targets\n hard_loss = self.ce_loss(student_logits, targets)\n\n # Adaptive weighting could be implemented here based on confidence\n # For simplicity, this example uses a fixed ratio\n return distillation_loss + hard_loss\n\n\n# Example Training Loop Skeleton\ndef train_model(student_model, teacher_model, dataloader, optimizer, device):\n student_model.train()\n teacher_model.eval() # Teacher model should be in eval mode\n\n loss_fn = AdaptiveConfidenceDistillationLoss(temperature=2.0)\n\n for inputs, labels in dataloader:\n inputs, labels = inputs.to(device), labels.to(device)\n\n optimizer.zero_grad()\n\n with torch.no_grad():\n teacher_outputs = teacher_model(inputs)\n\n student_outputs = student_model(inputs)\n\n loss = loss_fn(student_outputs, teacher_outputs, labels)\n loss.backward()\n optimizer.step()\n\n\n# Example usage\n# Assuming `dataloader`, `optimizer`, and `device` are defined\n# train_model(student_model, teacher_model, dataloader, optimizer, device)","source_hash":"1d853ce261864b7b90ca11a013e5ff6feff4aa1e87a9d5d20878083564c9aba6","truncated":false}
4
+ {"repo_id":"SuperAlignment","entity_id":"py:train_example.__init__","uri":"program://SuperAlignment/function/train_example.__init__#L13-L16","kind":"function","name":"__init__","path":"train_example.py","language":"python","start_line":13,"end_line":16,"context_start_line":1,"context_end_line":36,"code":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torchvision.models import resnet18, resnet50 # Example models\n\n# Define the teacher (weak model) and student (strong model)\nteacher_model = resnet18(pretrained=True)\nstudent_model = resnet50(pretrained=True)\n\n\n# Custom Adaptive Confidence Distillation Loss\nclass AdaptiveConfidenceDistillationLoss(nn.Module):\n def __init__(self, temperature=1.0):\n super().__init__()\n self.temperature = temperature\n self.ce_loss = nn.CrossEntropyLoss()\n\n def forward(self, student_logits, teacher_logits, targets):\n # Soften probabilities\n soft_teacher_probs = F.softmax(teacher_logits / self.temperature, dim=1)\n soft_student_probs = F.log_softmax(student_logits / self.temperature, dim=1)\n\n # Calculate the KL Divergence for the soft targets\n distillation_loss = F.kl_div(\n soft_student_probs, soft_teacher_probs, reduction=\"batchmean\"\n )\n\n # Calculate the standard loss with hard targets\n hard_loss = self.ce_loss(student_logits, targets)\n\n # Adaptive weighting could be implemented here based on confidence\n # For simplicity, this example uses a fixed ratio\n return distillation_loss + hard_loss\n\n\n# Example Training Loop Skeleton","source_hash":"1d853ce261864b7b90ca11a013e5ff6feff4aa1e87a9d5d20878083564c9aba6","truncated":false}
5
+ {"repo_id":"SuperAlignment","entity_id":"py:train_example.forward","uri":"program://SuperAlignment/function/train_example.forward#L18-L33","kind":"function","name":"forward","path":"train_example.py","language":"python","start_line":18,"end_line":33,"context_start_line":1,"context_end_line":53,"code":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torchvision.models import resnet18, resnet50 # Example models\n\n# Define the teacher (weak model) and student (strong model)\nteacher_model = resnet18(pretrained=True)\nstudent_model = resnet50(pretrained=True)\n\n\n# Custom Adaptive Confidence Distillation Loss\nclass AdaptiveConfidenceDistillationLoss(nn.Module):\n def __init__(self, temperature=1.0):\n super().__init__()\n self.temperature = temperature\n self.ce_loss = nn.CrossEntropyLoss()\n\n def forward(self, student_logits, teacher_logits, targets):\n # Soften probabilities\n soft_teacher_probs = F.softmax(teacher_logits / self.temperature, dim=1)\n soft_student_probs = F.log_softmax(student_logits / self.temperature, dim=1)\n\n # Calculate the KL Divergence for the soft targets\n distillation_loss = F.kl_div(\n soft_student_probs, soft_teacher_probs, reduction=\"batchmean\"\n )\n\n # Calculate the standard loss with hard targets\n hard_loss = self.ce_loss(student_logits, targets)\n\n # Adaptive weighting could be implemented here based on confidence\n # For simplicity, this example uses a fixed ratio\n return distillation_loss + hard_loss\n\n\n# Example Training Loop Skeleton\ndef train_model(student_model, teacher_model, dataloader, optimizer, device):\n student_model.train()\n teacher_model.eval() # Teacher model should be in eval mode\n\n loss_fn = AdaptiveConfidenceDistillationLoss(temperature=2.0)\n\n for inputs, labels in dataloader:\n inputs, labels = inputs.to(device), labels.to(device)\n\n optimizer.zero_grad()\n\n with torch.no_grad():\n teacher_outputs = teacher_model(inputs)\n\n student_outputs = student_model(inputs)\n\n loss = loss_fn(student_outputs, teacher_outputs, labels)","source_hash":"1d853ce261864b7b90ca11a013e5ff6feff4aa1e87a9d5d20878083564c9aba6","truncated":false}
6
+ {"repo_id":"SuperAlignment","entity_id":"py:AdaptiveConfidenceDistillation","uri":"program://SuperAlignment/module/AdaptiveConfidenceDistillation#L1-L27","kind":"module","name":"AdaptiveConfidenceDistillation","path":"AdaptiveConfidenceDistillation.py","language":"python","start_line":1,"end_line":27,"context_start_line":1,"context_end_line":27,"code":"import torch.nn as nn\nimport torch.nn.functional as F\n\n\n# Custom Adaptive Confidence Distillation Loss\nclass AdaptiveConfidenceDistillationLoss(nn.Module):\n def __init__(self, temperature=1.0):\n super().__init__()\n self.temperature = temperature\n self.ce_loss = nn.CrossEntropyLoss()\n\n def forward(self, student_logits, teacher_logits, targets):\n # Soften probabilities\n soft_teacher_probs = F.softmax(teacher_logits / self.temperature, dim=1)\n soft_student_probs = F.log_softmax(student_logits / self.temperature, dim=1)\n\n # Calculate the KL Divergence for the soft targets\n distillation_loss = F.kl_div(\n soft_student_probs, soft_teacher_probs, reduction=\"batchmean\"\n )\n\n # Calculate the standard loss with hard targets\n hard_loss = self.ce_loss(student_logits, targets)\n\n # Adaptive weighting could be implemented here based on confidence\n # For simplicity, this example uses a fixed ratio\n return distillation_loss + hard_loss","source_hash":"78f2354cb5ad0726bbf11cff4469be7a070132d3339921881ae5df2398b71f16","truncated":false}
7
+ {"repo_id":"SuperAlignment","entity_id":"py:AdaptiveConfidenceDistillation.AdaptiveConfidenceDistillationLoss","uri":"program://SuperAlignment/class/AdaptiveConfidenceDistillation.AdaptiveConfidenceDistillationLoss#L6-L27","kind":"class","name":"AdaptiveConfidenceDistillationLoss","path":"AdaptiveConfidenceDistillation.py","language":"python","start_line":6,"end_line":27,"context_start_line":1,"context_end_line":27,"code":"import torch.nn as nn\nimport torch.nn.functional as F\n\n\n# Custom Adaptive Confidence Distillation Loss\nclass AdaptiveConfidenceDistillationLoss(nn.Module):\n def __init__(self, temperature=1.0):\n super().__init__()\n self.temperature = temperature\n self.ce_loss = nn.CrossEntropyLoss()\n\n def forward(self, student_logits, teacher_logits, targets):\n # Soften probabilities\n soft_teacher_probs = F.softmax(teacher_logits / self.temperature, dim=1)\n soft_student_probs = F.log_softmax(student_logits / self.temperature, dim=1)\n\n # Calculate the KL Divergence for the soft targets\n distillation_loss = F.kl_div(\n soft_student_probs, soft_teacher_probs, reduction=\"batchmean\"\n )\n\n # Calculate the standard loss with hard targets\n hard_loss = self.ce_loss(student_logits, targets)\n\n # Adaptive weighting could be implemented here based on confidence\n # For simplicity, this example uses a fixed ratio\n return distillation_loss + hard_loss","source_hash":"78f2354cb5ad0726bbf11cff4469be7a070132d3339921881ae5df2398b71f16","truncated":false}
8
+ {"repo_id":"SuperAlignment","entity_id":"py:AdaptiveConfidenceDistillation.__init__","uri":"program://SuperAlignment/function/AdaptiveConfidenceDistillation.__init__#L7-L10","kind":"function","name":"__init__","path":"AdaptiveConfidenceDistillation.py","language":"python","start_line":7,"end_line":10,"context_start_line":1,"context_end_line":27,"code":"import torch.nn as nn\nimport torch.nn.functional as F\n\n\n# Custom Adaptive Confidence Distillation Loss\nclass AdaptiveConfidenceDistillationLoss(nn.Module):\n def __init__(self, temperature=1.0):\n super().__init__()\n self.temperature = temperature\n self.ce_loss = nn.CrossEntropyLoss()\n\n def forward(self, student_logits, teacher_logits, targets):\n # Soften probabilities\n soft_teacher_probs = F.softmax(teacher_logits / self.temperature, dim=1)\n soft_student_probs = F.log_softmax(student_logits / self.temperature, dim=1)\n\n # Calculate the KL Divergence for the soft targets\n distillation_loss = F.kl_div(\n soft_student_probs, soft_teacher_probs, reduction=\"batchmean\"\n )\n\n # Calculate the standard loss with hard targets\n hard_loss = self.ce_loss(student_logits, targets)\n\n # Adaptive weighting could be implemented here based on confidence\n # For simplicity, this example uses a fixed ratio\n return distillation_loss + hard_loss","source_hash":"78f2354cb5ad0726bbf11cff4469be7a070132d3339921881ae5df2398b71f16","truncated":false}
9
+ {"repo_id":"SuperAlignment","entity_id":"py:AdaptiveConfidenceDistillation.forward","uri":"program://SuperAlignment/function/AdaptiveConfidenceDistillation.forward#L12-L27","kind":"function","name":"forward","path":"AdaptiveConfidenceDistillation.py","language":"python","start_line":12,"end_line":27,"context_start_line":1,"context_end_line":27,"code":"import torch.nn as nn\nimport torch.nn.functional as F\n\n\n# Custom Adaptive Confidence Distillation Loss\nclass AdaptiveConfidenceDistillationLoss(nn.Module):\n def __init__(self, temperature=1.0):\n super().__init__()\n self.temperature = temperature\n self.ce_loss = nn.CrossEntropyLoss()\n\n def forward(self, student_logits, teacher_logits, targets):\n # Soften probabilities\n soft_teacher_probs = F.softmax(teacher_logits / self.temperature, dim=1)\n soft_student_probs = F.log_softmax(student_logits / self.temperature, dim=1)\n\n # Calculate the KL Divergence for the soft targets\n distillation_loss = F.kl_div(\n soft_student_probs, soft_teacher_probs, reduction=\"batchmean\"\n )\n\n # Calculate the standard loss with hard targets\n hard_loss = self.ce_loss(student_logits, targets)\n\n # Adaptive weighting could be implemented here based on confidence\n # For simplicity, this example uses a fixed ratio\n return distillation_loss + hard_loss","source_hash":"78f2354cb5ad0726bbf11cff4469be7a070132d3339921881ae5df2398b71f16","truncated":false}
10
+ {"repo_id":"SuperAlignment","entity_id":"py:test_train_example","uri":"program://SuperAlignment/module/test_train_example#L1-L42","kind":"module","name":"test_train_example","path":"test_train_example.py","language":"python","start_line":1,"end_line":42,"context_start_line":1,"context_end_line":42,"code":"import torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torchvision.models import resnet18, resnet50\nfrom torch.utils.data import DataLoader, TensorDataset\nimport numpy as np\nfrom train_example import train_model\n\n# Define the teacher (weak model) and student (strong model)\nteacher_model = resnet18(pretrained=False) # Using pretrained=False for simplicity\nstudent_model = resnet50(pretrained=False)\n\n# Define a simple synthetic dataset resembling CIFAR-100\n# CIFAR-100 has 32x32 images with 3 channels\n# We'll create random data with similar dimensions\nnum_samples = 1000\ninput_channels = 3\ninput_height = 32\ninput_width = 32\nnum_classes = 100\n\n# Generate random images and labels\nimages = torch.randn(num_samples, input_channels, input_height, input_width)\nlabels = torch.randint(0, num_classes, (num_samples,))\n\n# Create DataLoader for the synthetic dataset\ndataset = TensorDataset(images, labels)\ndataloader = DataLoader(dataset, batch_size=32, shuffle=True)\n\n# Define optimizer and device\noptimizer = optim.Adam(student_model.parameters(), lr=0.001)\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n\n# Define a unit test function\ndef test_training_loop():\n train_model(student_model, teacher_model, dataloader, optimizer, device)\n\n\n# Run the test function\ntest_training_loop()\nprint(\"test passed!\")","source_hash":"6e808ad91b17c4e12df91f6ed188bfe810f9d6cb3ef55c61df0055a57b0abc0b","truncated":false}
11
+ {"repo_id":"SuperAlignment","entity_id":"py:test_train_example.test_training_loop","uri":"program://SuperAlignment/function/test_train_example.test_training_loop#L36-L37","kind":"function","name":"test_training_loop","path":"test_train_example.py","language":"python","start_line":36,"end_line":37,"context_start_line":16,"context_end_line":42,"code":"num_samples = 1000\ninput_channels = 3\ninput_height = 32\ninput_width = 32\nnum_classes = 100\n\n# Generate random images and labels\nimages = torch.randn(num_samples, input_channels, input_height, input_width)\nlabels = torch.randint(0, num_classes, (num_samples,))\n\n# Create DataLoader for the synthetic dataset\ndataset = TensorDataset(images, labels)\ndataloader = DataLoader(dataset, batch_size=32, shuffle=True)\n\n# Define optimizer and device\noptimizer = optim.Adam(student_model.parameters(), lr=0.001)\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n\n# Define a unit test function\ndef test_training_loop():\n train_model(student_model, teacher_model, dataloader, optimizer, device)\n\n\n# Run the test function\ntest_training_loop()\nprint(\"test passed!\")","source_hash":"6e808ad91b17c4e12df91f6ed188bfe810f9d6cb3ef55c61df0055a57b0abc0b","truncated":false}
12
+ {"repo_id":"SuperAlignment","entity_id":"py:dataset","uri":"program://SuperAlignment/module/dataset#L1-L58","kind":"module","name":"dataset","path":"dataset.py","language":"python","start_line":1,"end_line":58,"context_start_line":1,"context_end_line":58,"code":"import torch\nfrom torch.utils.data import Dataset\nimport os\nfrom PIL import Image\nfrom generate_labels import generate_label_for_single_image\nimport json\n\n\n# Custom Dataset Class\nclass CustomImageDataset(Dataset):\n def __init__(\n self, image_dir, transform=None, model_name=\"google/vit-base-patch16-224\"\n ):\n self.image_dir = image_dir\n self.transform = transform\n self.memory_bank = load_memory_bank() # Load existing labels from memory bank\n self.image_paths = [\n os.path.join(image_dir, img)\n for img in os.listdir(image_dir)\n if img.endswith((\".png\", \".jpg\", \".jpeg\"))\n ]\n self.model_name = model_name\n self.label_to_index = {} # Dynamically map labels to indices\n self.current_index = 0 # Keep track of the next index to assign\n\n def __len__(self):\n return len(self.image_paths)\n\n def __getitem__(self, idx):\n image_path = self.image_paths[idx]\n image = Image.open(image_path).convert(\"RGB\")\n\n if image_path not in self.memory_bank: # Check if label already exists\n # Generate label for the image\n _, predicted_label = generate_label_for_single_image(image_path)\n self.memory_bank[image_path] = predicted_label # Add to memory bank\n else:\n predicted_label = self.memory_bank[image_path] # Use existing label\n # if self.transform:\n # image = self.transform(image)\n\n # Dynamically assign index to new labels\n if predicted_label not in self.label_to_index:\n self.label_to_index[predicted_label] = self.current_index\n self.current_index += 1\n label_index = self.label_to_index[predicted_label]\n\n if self.transform:\n image = self.transform(image)\n return image, torch.tensor(label_index, dtype=torch.long)\n\n\ndef load_memory_bank(filename=\"label_memory_bank.json\"):\n if os.path.exists(filename):\n with open(filename, \"r\") as file:\n return json.load(file)\n else:\n return {}","source_hash":"981d68dd2e2858f57d74c1cd302ee09901a2fa38c665753fa9e6a5a0b08f1267","truncated":false}
13
+ {"repo_id":"SuperAlignment","entity_id":"py:dataset.CustomImageDataset","uri":"program://SuperAlignment/class/dataset.CustomImageDataset#L10-L50","kind":"class","name":"CustomImageDataset","path":"dataset.py","language":"python","start_line":10,"end_line":50,"context_start_line":1,"context_end_line":58,"code":"import torch\nfrom torch.utils.data import Dataset\nimport os\nfrom PIL import Image\nfrom generate_labels import generate_label_for_single_image\nimport json\n\n\n# Custom Dataset Class\nclass CustomImageDataset(Dataset):\n def __init__(\n self, image_dir, transform=None, model_name=\"google/vit-base-patch16-224\"\n ):\n self.image_dir = image_dir\n self.transform = transform\n self.memory_bank = load_memory_bank() # Load existing labels from memory bank\n self.image_paths = [\n os.path.join(image_dir, img)\n for img in os.listdir(image_dir)\n if img.endswith((\".png\", \".jpg\", \".jpeg\"))\n ]\n self.model_name = model_name\n self.label_to_index = {} # Dynamically map labels to indices\n self.current_index = 0 # Keep track of the next index to assign\n\n def __len__(self):\n return len(self.image_paths)\n\n def __getitem__(self, idx):\n image_path = self.image_paths[idx]\n image = Image.open(image_path).convert(\"RGB\")\n\n if image_path not in self.memory_bank: # Check if label already exists\n # Generate label for the image\n _, predicted_label = generate_label_for_single_image(image_path)\n self.memory_bank[image_path] = predicted_label # Add to memory bank\n else:\n predicted_label = self.memory_bank[image_path] # Use existing label\n # if self.transform:\n # image = self.transform(image)\n\n # Dynamically assign index to new labels\n if predicted_label not in self.label_to_index:\n self.label_to_index[predicted_label] = self.current_index\n self.current_index += 1\n label_index = self.label_to_index[predicted_label]\n\n if self.transform:\n image = self.transform(image)\n return image, torch.tensor(label_index, dtype=torch.long)\n\n\ndef load_memory_bank(filename=\"label_memory_bank.json\"):\n if os.path.exists(filename):\n with open(filename, \"r\") as file:\n return json.load(file)\n else:\n return {}","source_hash":"981d68dd2e2858f57d74c1cd302ee09901a2fa38c665753fa9e6a5a0b08f1267","truncated":false}
14
+ {"repo_id":"SuperAlignment","entity_id":"py:dataset.load_memory_bank","uri":"program://SuperAlignment/function/dataset.load_memory_bank#L53-L58","kind":"function","name":"load_memory_bank","path":"dataset.py","language":"python","start_line":53,"end_line":58,"context_start_line":33,"context_end_line":58,"code":" if image_path not in self.memory_bank: # Check if label already exists\n # Generate label for the image\n _, predicted_label = generate_label_for_single_image(image_path)\n self.memory_bank[image_path] = predicted_label # Add to memory bank\n else:\n predicted_label = self.memory_bank[image_path] # Use existing label\n # if self.transform:\n # image = self.transform(image)\n\n # Dynamically assign index to new labels\n if predicted_label not in self.label_to_index:\n self.label_to_index[predicted_label] = self.current_index\n self.current_index += 1\n label_index = self.label_to_index[predicted_label]\n\n if self.transform:\n image = self.transform(image)\n return image, torch.tensor(label_index, dtype=torch.long)\n\n\ndef load_memory_bank(filename=\"label_memory_bank.json\"):\n if os.path.exists(filename):\n with open(filename, \"r\") as file:\n return json.load(file)\n else:\n return {}","source_hash":"981d68dd2e2858f57d74c1cd302ee09901a2fa38c665753fa9e6a5a0b08f1267","truncated":false}
15
+ {"repo_id":"SuperAlignment","entity_id":"py:dataset.__init__","uri":"program://SuperAlignment/function/dataset.__init__#L11-L24","kind":"function","name":"__init__","path":"dataset.py","language":"python","start_line":11,"end_line":24,"context_start_line":1,"context_end_line":44,"code":"import torch\nfrom torch.utils.data import Dataset\nimport os\nfrom PIL import Image\nfrom generate_labels import generate_label_for_single_image\nimport json\n\n\n# Custom Dataset Class\nclass CustomImageDataset(Dataset):\n def __init__(\n self, image_dir, transform=None, model_name=\"google/vit-base-patch16-224\"\n ):\n self.image_dir = image_dir\n self.transform = transform\n self.memory_bank = load_memory_bank() # Load existing labels from memory bank\n self.image_paths = [\n os.path.join(image_dir, img)\n for img in os.listdir(image_dir)\n if img.endswith((\".png\", \".jpg\", \".jpeg\"))\n ]\n self.model_name = model_name\n self.label_to_index = {} # Dynamically map labels to indices\n self.current_index = 0 # Keep track of the next index to assign\n\n def __len__(self):\n return len(self.image_paths)\n\n def __getitem__(self, idx):\n image_path = self.image_paths[idx]\n image = Image.open(image_path).convert(\"RGB\")\n\n if image_path not in self.memory_bank: # Check if label already exists\n # Generate label for the image\n _, predicted_label = generate_label_for_single_image(image_path)\n self.memory_bank[image_path] = predicted_label # Add to memory bank\n else:\n predicted_label = self.memory_bank[image_path] # Use existing label\n # if self.transform:\n # image = self.transform(image)\n\n # Dynamically assign index to new labels\n if predicted_label not in self.label_to_index:\n self.label_to_index[predicted_label] = self.current_index","source_hash":"981d68dd2e2858f57d74c1cd302ee09901a2fa38c665753fa9e6a5a0b08f1267","truncated":false}
16
+ {"repo_id":"SuperAlignment","entity_id":"py:dataset.__len__","uri":"program://SuperAlignment/function/dataset.__len__#L26-L27","kind":"function","name":"__len__","path":"dataset.py","language":"python","start_line":26,"end_line":27,"context_start_line":6,"context_end_line":47,"code":"import json\n\n\n# Custom Dataset Class\nclass CustomImageDataset(Dataset):\n def __init__(\n self, image_dir, transform=None, model_name=\"google/vit-base-patch16-224\"\n ):\n self.image_dir = image_dir\n self.transform = transform\n self.memory_bank = load_memory_bank() # Load existing labels from memory bank\n self.image_paths = [\n os.path.join(image_dir, img)\n for img in os.listdir(image_dir)\n if img.endswith((\".png\", \".jpg\", \".jpeg\"))\n ]\n self.model_name = model_name\n self.label_to_index = {} # Dynamically map labels to indices\n self.current_index = 0 # Keep track of the next index to assign\n\n def __len__(self):\n return len(self.image_paths)\n\n def __getitem__(self, idx):\n image_path = self.image_paths[idx]\n image = Image.open(image_path).convert(\"RGB\")\n\n if image_path not in self.memory_bank: # Check if label already exists\n # Generate label for the image\n _, predicted_label = generate_label_for_single_image(image_path)\n self.memory_bank[image_path] = predicted_label # Add to memory bank\n else:\n predicted_label = self.memory_bank[image_path] # Use existing label\n # if self.transform:\n # image = self.transform(image)\n\n # Dynamically assign index to new labels\n if predicted_label not in self.label_to_index:\n self.label_to_index[predicted_label] = self.current_index\n self.current_index += 1\n label_index = self.label_to_index[predicted_label]\n","source_hash":"981d68dd2e2858f57d74c1cd302ee09901a2fa38c665753fa9e6a5a0b08f1267","truncated":false}
17
+ {"repo_id":"SuperAlignment","entity_id":"py:dataset.__getitem__","uri":"program://SuperAlignment/function/dataset.__getitem__#L29-L50","kind":"function","name":"__getitem__","path":"dataset.py","language":"python","start_line":29,"end_line":50,"context_start_line":9,"context_end_line":58,"code":"# Custom Dataset Class\nclass CustomImageDataset(Dataset):\n def __init__(\n self, image_dir, transform=None, model_name=\"google/vit-base-patch16-224\"\n ):\n self.image_dir = image_dir\n self.transform = transform\n self.memory_bank = load_memory_bank() # Load existing labels from memory bank\n self.image_paths = [\n os.path.join(image_dir, img)\n for img in os.listdir(image_dir)\n if img.endswith((\".png\", \".jpg\", \".jpeg\"))\n ]\n self.model_name = model_name\n self.label_to_index = {} # Dynamically map labels to indices\n self.current_index = 0 # Keep track of the next index to assign\n\n def __len__(self):\n return len(self.image_paths)\n\n def __getitem__(self, idx):\n image_path = self.image_paths[idx]\n image = Image.open(image_path).convert(\"RGB\")\n\n if image_path not in self.memory_bank: # Check if label already exists\n # Generate label for the image\n _, predicted_label = generate_label_for_single_image(image_path)\n self.memory_bank[image_path] = predicted_label # Add to memory bank\n else:\n predicted_label = self.memory_bank[image_path] # Use existing label\n # if self.transform:\n # image = self.transform(image)\n\n # Dynamically assign index to new labels\n if predicted_label not in self.label_to_index:\n self.label_to_index[predicted_label] = self.current_index\n self.current_index += 1\n label_index = self.label_to_index[predicted_label]\n\n if self.transform:\n image = self.transform(image)\n return image, torch.tensor(label_index, dtype=torch.long)\n\n\ndef load_memory_bank(filename=\"label_memory_bank.json\"):\n if os.path.exists(filename):\n with open(filename, \"r\") as file:\n return json.load(file)\n else:\n return {}","source_hash":"981d68dd2e2858f57d74c1cd302ee09901a2fa38c665753fa9e6a5a0b08f1267","truncated":false}
18
+ {"repo_id":"SuperAlignment","entity_id":"py:train","uri":"program://SuperAlignment/module/train#L1-L156","kind":"module","name":"train","path":"train.py","language":"python","start_line":1,"end_line":156,"context_start_line":1,"context_end_line":156,"code":"import torch\nimport torch.optim as optim\nfrom torchvision import transforms\nfrom torchvision.models import resnet18, resnet50\nfrom torch.utils.data import DataLoader\nimport numpy as np\nimport os\nimport json\nfrom utils import plot_and_save_metrics\nfrom dataset import CustomImageDataset\nfrom AdaptiveConfidenceDistillation import AdaptiveConfidenceDistillationLoss\n\n# Define the teacher (weak model) and student (strong model)\nteacher_model = resnet18(pretrained=True) # Using pretrained=False for simplicity\nstudent_model = resnet50(pretrained=True)\n\n# Define a simple synthetic dataset resembling CIFAR-100\n# CIFAR-100 has 32x32 images with 3 channels\n# We'll create random data with similar dimensions\nnum_samples = 1000\ninput_channels = 3\ninput_height = 32\ninput_width = 32\nnum_classes = 100\n\n# Define transformations\ntransform = transforms.Compose(\n [\n transforms.Resize((32, 32)),\n transforms.ToTensor(),\n ]\n)\n\n# Create an instance of the CustomImageDataset\nimage_dir = \"./images\" # Specify the correct path to your images\ndataset = CustomImageDataset(image_dir=image_dir, transform=transform)\n\n\ndef save_memory_bank(memory_bank, filename=\"label_memory_bank.json\"):\n with open(filename, \"w\") as file:\n json.dump(memory_bank, file)\n\n\n# After training is complete or when you're done using the dataset\nsave_memory_bank(dataset.memory_bank) # Save the updated memory bank to a file\n# Split dataset into train and validation sets\ntrain_size = int(0.8 * len(dataset))\nval_size = len(dataset) - train_size\ntrain_dataset, val_dataset = torch.utils.data.random_split(\n dataset, [train_size, val_size]\n)\n\n# Create DataLoaders\ntrain_dataloader = DataLoader(train_dataset, batch_size=32, shuffle=True)\nval_dataloader = DataLoader(val_dataset, batch_size=32, shuffle=False)\n\n# Define optimizer and device\noptimizer = optim.Adam(student_model.parameters(), lr=0.001)\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nprint(f\"Using device: {device}\")\n\n\n# Step 1: Load Labels and Image Paths\ndef load_image_paths_labels(json_path):\n with open(json_path, \"r\") as f:\n data = json.load(f)\n image_paths = [os.path.join(\"./images\", item[\"image_path\"]) for item in data]\n labels = [item[\"caption\"] for item in data]\n return image_paths, labels\n\n\n# Example Training Loop Skeleton with Validation and Model Checkpointing\ndef train_model_with_validation(\n student_model,\n teacher_model,\n train_dataloader,\n val_dataloader,\n optimizer,\n device,\n num_epochs=10,\n checkpoint_path=\"checkpoint.pth\",\n):\n student_model.train()\n teacher_model.eval() # Teacher model should be in eval mode\n\n # Initialize metrics dictionary\n metrics = {\n \"train_loss\": [],\n \"val_loss\": [],\n } # Add 'train_accuracy': [], 'val_accuracy': [] if tracking accuracy\n loss_fn = AdaptiveConfidenceDistillationLoss(temperature=2.0)\n best_val_loss = float(\"inf\")\n step = 0\n for epoch in range(num_epochs):\n # Training loop\n for inputs, labels in train_dataloader:\n if step % 200 == 0:\n # Validation loop\n val_loss = 0.0\n with torch.no_grad():\n for inputs, labels in val_dataloader:\n inputs, labels = inputs.to(device), labels.to(device)\n teacher_outputs = teacher_model(inputs)\n student_outputs = student_model(inputs)\n loss = loss_fn(student_outputs, teacher_outputs, labels)\n val_loss += loss.item() * inputs.size(\n 0\n ) # Inside the training loop\n metrics[\"train_loss\"].append(\n loss.item()\n ) # Assuming loss is your loss variable\n\n # Inside the validation loop\n metrics[\"val_loss\"].append(\n val_loss\n ) # Assuming val_loss is your accumulated validation loss\n step += 1\n print(f\"val_loss: {val_loss}\")\n # After training, plot and save metrics\n plot_and_save_metrics(metrics)\n inputs, labels = inputs.to(device), labels.to(device)\n optimizer.zero_grad()\n\n with torch.no_grad():\n teacher_outputs = teacher_model(inputs)\n\n student_outputs = student_model(inputs)\n\n loss = loss_fn(student_outputs, teacher_outputs, labels)\n loss.backward()\n optimizer.step()\n\n val_loss /= len(val_dataloader.dataset)\n print(f\"Epoch [{epoch+1}/{num_epochs}], Validation Loss: {val_loss:.4f}\")\n\n # Save the model checkpoint if validation loss improves\n if val_loss < best_val_loss:\n best_val_loss = val_loss\n torch.save(student_model.state_dict(), checkpoint_path)\n # After training, plot and save metrics\n plot_and_save_metrics(metrics)\n print(f\"Saving model checkpoint at {checkpoint_path}\")\n\n\n# Example usage\n# Assuming `train_dataloader`, `val_dataloader`, `optimizer`, and `device` are defined\ntrain_model_with_validation(\n student_model,\n teacher_model,\n train_dataloader,\n val_dataloader,\n optimizer,\n device,\n num_epochs=10,\n checkpoint_path=\"checkpoint.pth\",\n)","source_hash":"aec049768a636ee5c1da4badd75c577ef9b0a0665268f1006af96fee0e488a23","truncated":false}
19
+ {"repo_id":"SuperAlignment","entity_id":"py:train.save_memory_bank","uri":"program://SuperAlignment/function/train.save_memory_bank#L39-L41","kind":"function","name":"save_memory_bank","path":"train.py","language":"python","start_line":39,"end_line":41,"context_start_line":19,"context_end_line":61,"code":"# We'll create random data with similar dimensions\nnum_samples = 1000\ninput_channels = 3\ninput_height = 32\ninput_width = 32\nnum_classes = 100\n\n# Define transformations\ntransform = transforms.Compose(\n [\n transforms.Resize((32, 32)),\n transforms.ToTensor(),\n ]\n)\n\n# Create an instance of the CustomImageDataset\nimage_dir = \"./images\" # Specify the correct path to your images\ndataset = CustomImageDataset(image_dir=image_dir, transform=transform)\n\n\ndef save_memory_bank(memory_bank, filename=\"label_memory_bank.json\"):\n with open(filename, \"w\") as file:\n json.dump(memory_bank, file)\n\n\n# After training is complete or when you're done using the dataset\nsave_memory_bank(dataset.memory_bank) # Save the updated memory bank to a file\n# Split dataset into train and validation sets\ntrain_size = int(0.8 * len(dataset))\nval_size = len(dataset) - train_size\ntrain_dataset, val_dataset = torch.utils.data.random_split(\n dataset, [train_size, val_size]\n)\n\n# Create DataLoaders\ntrain_dataloader = DataLoader(train_dataset, batch_size=32, shuffle=True)\nval_dataloader = DataLoader(val_dataset, batch_size=32, shuffle=False)\n\n# Define optimizer and device\noptimizer = optim.Adam(student_model.parameters(), lr=0.001)\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nprint(f\"Using device: {device}\")\n","source_hash":"aec049768a636ee5c1da4badd75c577ef9b0a0665268f1006af96fee0e488a23","truncated":false}
20
+ {"repo_id":"SuperAlignment","entity_id":"py:train.load_image_paths_labels","uri":"program://SuperAlignment/function/train.load_image_paths_labels#L64-L69","kind":"function","name":"load_image_paths_labels","path":"train.py","language":"python","start_line":64,"end_line":69,"context_start_line":44,"context_end_line":89,"code":"# After training is complete or when you're done using the dataset\nsave_memory_bank(dataset.memory_bank) # Save the updated memory bank to a file\n# Split dataset into train and validation sets\ntrain_size = int(0.8 * len(dataset))\nval_size = len(dataset) - train_size\ntrain_dataset, val_dataset = torch.utils.data.random_split(\n dataset, [train_size, val_size]\n)\n\n# Create DataLoaders\ntrain_dataloader = DataLoader(train_dataset, batch_size=32, shuffle=True)\nval_dataloader = DataLoader(val_dataset, batch_size=32, shuffle=False)\n\n# Define optimizer and device\noptimizer = optim.Adam(student_model.parameters(), lr=0.001)\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nprint(f\"Using device: {device}\")\n\n\n# Step 1: Load Labels and Image Paths\ndef load_image_paths_labels(json_path):\n with open(json_path, \"r\") as f:\n data = json.load(f)\n image_paths = [os.path.join(\"./images\", item[\"image_path\"]) for item in data]\n labels = [item[\"caption\"] for item in data]\n return image_paths, labels\n\n\n# Example Training Loop Skeleton with Validation and Model Checkpointing\ndef train_model_with_validation(\n student_model,\n teacher_model,\n train_dataloader,\n val_dataloader,\n optimizer,\n device,\n num_epochs=10,\n checkpoint_path=\"checkpoint.pth\",\n):\n student_model.train()\n teacher_model.eval() # Teacher model should be in eval mode\n\n # Initialize metrics dictionary\n metrics = {\n \"train_loss\": [],\n \"val_loss\": [],","source_hash":"aec049768a636ee5c1da4badd75c577ef9b0a0665268f1006af96fee0e488a23","truncated":false}
21
+ {"repo_id":"SuperAlignment","entity_id":"py:train.train_model_with_validation","uri":"program://SuperAlignment/function/train.train_model_with_validation#L73-L142","kind":"function","name":"train_model_with_validation","path":"train.py","language":"python","start_line":73,"end_line":142,"context_start_line":53,"context_end_line":156,"code":"# Create DataLoaders\ntrain_dataloader = DataLoader(train_dataset, batch_size=32, shuffle=True)\nval_dataloader = DataLoader(val_dataset, batch_size=32, shuffle=False)\n\n# Define optimizer and device\noptimizer = optim.Adam(student_model.parameters(), lr=0.001)\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nprint(f\"Using device: {device}\")\n\n\n# Step 1: Load Labels and Image Paths\ndef load_image_paths_labels(json_path):\n with open(json_path, \"r\") as f:\n data = json.load(f)\n image_paths = [os.path.join(\"./images\", item[\"image_path\"]) for item in data]\n labels = [item[\"caption\"] for item in data]\n return image_paths, labels\n\n\n# Example Training Loop Skeleton with Validation and Model Checkpointing\ndef train_model_with_validation(\n student_model,\n teacher_model,\n train_dataloader,\n val_dataloader,\n optimizer,\n device,\n num_epochs=10,\n checkpoint_path=\"checkpoint.pth\",\n):\n student_model.train()\n teacher_model.eval() # Teacher model should be in eval mode\n\n # Initialize metrics dictionary\n metrics = {\n \"train_loss\": [],\n \"val_loss\": [],\n } # Add 'train_accuracy': [], 'val_accuracy': [] if tracking accuracy\n loss_fn = AdaptiveConfidenceDistillationLoss(temperature=2.0)\n best_val_loss = float(\"inf\")\n step = 0\n for epoch in range(num_epochs):\n # Training loop\n for inputs, labels in train_dataloader:\n if step % 200 == 0:\n # Validation loop\n val_loss = 0.0\n with torch.no_grad():\n for inputs, labels in val_dataloader:\n inputs, labels = inputs.to(device), labels.to(device)\n teacher_outputs = teacher_model(inputs)\n student_outputs = student_model(inputs)\n loss = loss_fn(student_outputs, teacher_outputs, labels)\n val_loss += loss.item() * inputs.size(\n 0\n ) # Inside the training loop\n metrics[\"train_loss\"].append(\n loss.item()\n ) # Assuming loss is your loss variable\n\n # Inside the validation loop\n metrics[\"val_loss\"].append(\n val_loss\n ) # Assuming val_loss is your accumulated validation loss\n step += 1\n print(f\"val_loss: {val_loss}\")\n # After training, plot and save metrics\n plot_and_save_metrics(metrics)\n inputs, labels = inputs.to(device), labels.to(device)\n optimizer.zero_grad()\n\n with torch.no_grad():\n teacher_outputs = teacher_model(inputs)\n\n student_outputs = student_model(inputs)\n\n loss = loss_fn(student_outputs, teacher_outputs, labels)\n loss.backward()\n optimizer.step()\n\n val_loss /= len(val_dataloader.dataset)\n print(f\"Epoch [{epoch+1}/{num_epochs}], Validation Loss: {val_loss:.4f}\")\n\n # Save the model checkpoint if validation loss improves\n if val_loss < best_val_loss:\n best_val_loss = val_loss\n torch.save(student_model.state_dict(), checkpoint_path)\n # After training, plot and save metrics\n plot_and_save_metrics(metrics)\n print(f\"Saving model checkpoint at {checkpoint_path}\")\n\n\n# Example usage\n# Assuming `train_dataloader`, `val_dataloader`, `optimizer`, and `device` are defined\ntrain_model_with_validation(\n student_model,\n teacher_model,\n train_dataloader,\n val_dataloader,\n optimizer,\n device,\n num_epochs=10,\n checkpoint_path=\"checkpoint.pth\",\n)","source_hash":"aec049768a636ee5c1da4badd75c577ef9b0a0665268f1006af96fee0e488a23","truncated":false}
22
+ {"repo_id":"SuperAlignment","entity_id":"py:utils","uri":"program://SuperAlignment/module/utils#L1-L34","kind":"module","name":"utils","path":"utils.py","language":"python","start_line":1,"end_line":34,"context_start_line":1,"context_end_line":34,"code":"import matplotlib.pyplot as plt\nimport json\n\n\ndef plot_and_save_metrics(\n metrics, filename=\"training_metrics.png\", metrics_path=\"training_metrics.json\"\n):\n epochs = range(1, len(metrics[\"train_loss\"]) + 1)\n\n plt.figure(figsize=(10, 5))\n plt.subplot(1, 2, 1)\n plt.plot(epochs, metrics[\"train_loss\"], label=\"Training Loss\")\n plt.plot(epochs, metrics[\"val_loss\"], label=\"Validation Loss\")\n plt.title(\"Loss Metrics\")\n plt.xlabel(\"Epoch\")\n plt.ylabel(\"Loss\")\n plt.legend()\n\n # If you track accuracy, you can plot it here similarly.\n # plt.subplot(1, 2, 2)\n # plt.plot(epochs, metrics['train_accuracy'], label='Training Accuracy')\n # plt.plot(epochs, metrics['val_accuracy'], label='Validation Accuracy')\n # plt.title('Accuracy Metrics')\n # plt.xlabel('Epoch')\n # plt.ylabel('Accuracy')\n # plt.legend()\n\n plt.tight_layout()\n plt.savefig(filename)\n plt.close()\n\n # Save metrics to a JSON file for further analysis\n with open(metrics_path, \"w\") as f:\n json.dump(metrics, f, indent=4)","source_hash":"7804c1866cae172702f44d671accd34ee657dc7840952f9d6700cc17f267e8bd","truncated":false}
23
+ {"repo_id":"SuperAlignment","entity_id":"py:utils.plot_and_save_metrics","uri":"program://SuperAlignment/function/utils.plot_and_save_metrics#L5-L34","kind":"function","name":"plot_and_save_metrics","path":"utils.py","language":"python","start_line":5,"end_line":34,"context_start_line":1,"context_end_line":34,"code":"import matplotlib.pyplot as plt\nimport json\n\n\ndef plot_and_save_metrics(\n metrics, filename=\"training_metrics.png\", metrics_path=\"training_metrics.json\"\n):\n epochs = range(1, len(metrics[\"train_loss\"]) + 1)\n\n plt.figure(figsize=(10, 5))\n plt.subplot(1, 2, 1)\n plt.plot(epochs, metrics[\"train_loss\"], label=\"Training Loss\")\n plt.plot(epochs, metrics[\"val_loss\"], label=\"Validation Loss\")\n plt.title(\"Loss Metrics\")\n plt.xlabel(\"Epoch\")\n plt.ylabel(\"Loss\")\n plt.legend()\n\n # If you track accuracy, you can plot it here similarly.\n # plt.subplot(1, 2, 2)\n # plt.plot(epochs, metrics['train_accuracy'], label='Training Accuracy')\n # plt.plot(epochs, metrics['val_accuracy'], label='Validation Accuracy')\n # plt.title('Accuracy Metrics')\n # plt.xlabel('Epoch')\n # plt.ylabel('Accuracy')\n # plt.legend()\n\n plt.tight_layout()\n plt.savefig(filename)\n plt.close()\n\n # Save metrics to a JSON file for further analysis\n with open(metrics_path, \"w\") as f:\n json.dump(metrics, f, indent=4)","source_hash":"7804c1866cae172702f44d671accd34ee657dc7840952f9d6700cc17f267e8bd","truncated":false}
24
+ {"repo_id":"SuperAlignment","entity_id":"py:generate_labels","uri":"program://SuperAlignment/module/generate_labels#L1-L78","kind":"module","name":"generate_labels","path":"generate_labels.py","language":"python","start_line":1,"end_line":78,"context_start_line":1,"context_end_line":78,"code":"import os\nfrom transformers import ViTImageProcessor, ViTForImageClassification\nfrom PIL import Image\nimport json\nimport torch\n\n\ndef generate_label_for_single_image(image_path):\n # Initialize the model and processor\n model = ViTForImageClassification.from_pretrained(\"google/vit-base-patch16-224\")\n feature_extractor = ViTImageProcessor.from_pretrained(\"google/vit-base-patch16-224\")\n\n # Load and process the image\n image = Image.open(image_path).convert(\"RGB\")\n inputs = feature_extractor(images=image, return_tensors=\"pt\")\n\n # Predict the class of the image\n with torch.no_grad():\n outputs = model(**inputs)\n\n logits = outputs.logits\n predicted_class_idx = logits.argmax(-1).item()\n\n # Optionally, print the predicted class (if id2label is available)\n predicted_label = (\n model.config.id2label[predicted_class_idx]\n if model.config.id2label\n else str(predicted_class_idx)\n )\n\n print(\"Predicted class index:\", predicted_class_idx)\n print(\"Predicted label:\", predicted_label)\n\n return predicted_class_idx, predicted_label\n\n\ndef generate_labels(image_dir, model_name, output_file, max_images=100):\n # Load the CLIP model and processor\n processor = ViTImageProcessor.from_pretrained(\"google/vit-base-patch16-224\")\n model = ViTForImageClassification.from_pretrained(\"google/vit-base-patch16-224\")\n\n # Fetch image paths\n images = os.listdir(image_dir)\n images = images[:max_images] # Limit to max_images\n\n labels = []\n\n for image_name in images:\n image_path = os.path.join(image_dir, image_name)\n\n # Load image\n image = Image.open(image_path).convert(\"RGB\")\n\n # Prepare the image for the model\n inputs = processor(images=image, return_tensors=\"pt\")\n\n # Generate image features (embeddings)\n with torch.no_grad():\n outputs = model(**inputs)\n\n # Here you would typically use the embeddings to find the closest text descriptions, but since\n # OpenCLIP doesn't provide direct label generation, we'll just save the embeddings for now.\n # This step is a placeholder for any specific label generation or nearest neighbor search you might implement.\n # For demonstration, let's assume a dummy label based on the max value index in the embeddings.\n logits = outputs.logits\n # model predicts one of the 1000 ImageNet classes\n predicted_class_idx = logits.argmax(-1).item()\n\n labels.append({\"image_path\": image_name, \"label\": predicted_class_idx})\n print(\"Predicted class: \", model.config.id2label[predicted_class_idx])\n # Save the labels to a JSON file\n with open(output_file, \"w\") as f:\n json.dump(labels, f, indent=4)\n\n\nimage_dir = \"./images\"\nmodel_name = \"google/vit-base-patch16-224\"\noutput_file = \"imagelabels.json\"","source_hash":"20a6fcb44164bd9974723b003b234785c2e029411323ddda3cb2fab53143ef64","truncated":false}
25
+ {"repo_id":"SuperAlignment","entity_id":"py:generate_labels.generate_label_for_single_image","uri":"program://SuperAlignment/function/generate_labels.generate_label_for_single_image#L8-L34","kind":"function","name":"generate_label_for_single_image","path":"generate_labels.py","language":"python","start_line":8,"end_line":34,"context_start_line":1,"context_end_line":54,"code":"import os\nfrom transformers import ViTImageProcessor, ViTForImageClassification\nfrom PIL import Image\nimport json\nimport torch\n\n\ndef generate_label_for_single_image(image_path):\n # Initialize the model and processor\n model = ViTForImageClassification.from_pretrained(\"google/vit-base-patch16-224\")\n feature_extractor = ViTImageProcessor.from_pretrained(\"google/vit-base-patch16-224\")\n\n # Load and process the image\n image = Image.open(image_path).convert(\"RGB\")\n inputs = feature_extractor(images=image, return_tensors=\"pt\")\n\n # Predict the class of the image\n with torch.no_grad():\n outputs = model(**inputs)\n\n logits = outputs.logits\n predicted_class_idx = logits.argmax(-1).item()\n\n # Optionally, print the predicted class (if id2label is available)\n predicted_label = (\n model.config.id2label[predicted_class_idx]\n if model.config.id2label\n else str(predicted_class_idx)\n )\n\n print(\"Predicted class index:\", predicted_class_idx)\n print(\"Predicted label:\", predicted_label)\n\n return predicted_class_idx, predicted_label\n\n\ndef generate_labels(image_dir, model_name, output_file, max_images=100):\n # Load the CLIP model and processor\n processor = ViTImageProcessor.from_pretrained(\"google/vit-base-patch16-224\")\n model = ViTForImageClassification.from_pretrained(\"google/vit-base-patch16-224\")\n\n # Fetch image paths\n images = os.listdir(image_dir)\n images = images[:max_images] # Limit to max_images\n\n labels = []\n\n for image_name in images:\n image_path = os.path.join(image_dir, image_name)\n\n # Load image\n image = Image.open(image_path).convert(\"RGB\")\n\n # Prepare the image for the model","source_hash":"20a6fcb44164bd9974723b003b234785c2e029411323ddda3cb2fab53143ef64","truncated":false}
26
+ {"repo_id":"SuperAlignment","entity_id":"py:generate_labels.generate_labels","uri":"program://SuperAlignment/function/generate_labels.generate_labels#L37-L73","kind":"function","name":"generate_labels","path":"generate_labels.py","language":"python","start_line":37,"end_line":73,"context_start_line":17,"context_end_line":78,"code":" # Predict the class of the image\n with torch.no_grad():\n outputs = model(**inputs)\n\n logits = outputs.logits\n predicted_class_idx = logits.argmax(-1).item()\n\n # Optionally, print the predicted class (if id2label is available)\n predicted_label = (\n model.config.id2label[predicted_class_idx]\n if model.config.id2label\n else str(predicted_class_idx)\n )\n\n print(\"Predicted class index:\", predicted_class_idx)\n print(\"Predicted label:\", predicted_label)\n\n return predicted_class_idx, predicted_label\n\n\ndef generate_labels(image_dir, model_name, output_file, max_images=100):\n # Load the CLIP model and processor\n processor = ViTImageProcessor.from_pretrained(\"google/vit-base-patch16-224\")\n model = ViTForImageClassification.from_pretrained(\"google/vit-base-patch16-224\")\n\n # Fetch image paths\n images = os.listdir(image_dir)\n images = images[:max_images] # Limit to max_images\n\n labels = []\n\n for image_name in images:\n image_path = os.path.join(image_dir, image_name)\n\n # Load image\n image = Image.open(image_path).convert(\"RGB\")\n\n # Prepare the image for the model\n inputs = processor(images=image, return_tensors=\"pt\")\n\n # Generate image features (embeddings)\n with torch.no_grad():\n outputs = model(**inputs)\n\n # Here you would typically use the embeddings to find the closest text descriptions, but since\n # OpenCLIP doesn't provide direct label generation, we'll just save the embeddings for now.\n # This step is a placeholder for any specific label generation or nearest neighbor search you might implement.\n # For demonstration, let's assume a dummy label based on the max value index in the embeddings.\n logits = outputs.logits\n # model predicts one of the 1000 ImageNet classes\n predicted_class_idx = logits.argmax(-1).item()\n\n labels.append({\"image_path\": image_name, \"label\": predicted_class_idx})\n print(\"Predicted class: \", model.config.id2label[predicted_class_idx])\n # Save the labels to a JSON file\n with open(output_file, \"w\") as f:\n json.dump(labels, f, indent=4)\n\n\nimage_dir = \"./images\"\nmodel_name = \"google/vit-base-patch16-224\"\noutput_file = \"imagelabels.json\"","source_hash":"20a6fcb44164bd9974723b003b234785c2e029411323ddda3cb2fab53143ef64","truncated":false}
27
+ {"repo_id":"SuperAlignment","entity_id":"file:train_example.py","uri":"program://SuperAlignment/file/train_example.py","kind":"file","name":"train_example.py","path":"train_example.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torchvision.models import resnet18, resnet50 # Example models\n\n# Define the teacher (weak model) and student (strong model)\nteacher_model = resnet18(pretrained=True)\nstudent_model = resnet50(pretrained=True)\n\n\n# Custom Adaptive Confidence Distillation Loss\nclass AdaptiveConfidenceDistillationLoss(nn.Module):\n def __init__(self, temperature=1.0):\n super().__init__()\n self.temperature = temperature\n self.ce_loss = nn.CrossEntropyLoss()\n\n def forward(self, student_logits, teacher_logits, targets):\n # Soften probabilities\n soft_teacher_probs = F.softmax(teacher_logits / self.temperature, dim=1)\n soft_student_probs = F.log_softmax(student_logits / self.temperature, dim=1)","source_hash":"1d853ce261864b7b90ca11a013e5ff6feff4aa1e87a9d5d20878083564c9aba6","truncated":false}
28
+ {"repo_id":"SuperAlignment","entity_id":"file:AdaptiveConfidenceDistillation.py","uri":"program://SuperAlignment/file/AdaptiveConfidenceDistillation.py","kind":"file","name":"AdaptiveConfidenceDistillation.py","path":"AdaptiveConfidenceDistillation.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import torch.nn as nn\nimport torch.nn.functional as F\n\n\n# Custom Adaptive Confidence Distillation Loss\nclass AdaptiveConfidenceDistillationLoss(nn.Module):\n def __init__(self, temperature=1.0):\n super().__init__()\n self.temperature = temperature\n self.ce_loss = nn.CrossEntropyLoss()\n\n def forward(self, student_logits, teacher_logits, targets):\n # Soften probabilities\n soft_teacher_probs = F.softmax(teacher_logits / self.temperature, dim=1)\n soft_student_probs = F.log_softmax(student_logits / self.temperature, dim=1)\n\n # Calculate the KL Divergence for the soft targets\n distillation_loss = F.kl_div(\n soft_student_probs, soft_teacher_probs, reduction=\"batchmean\"\n )\n","source_hash":"78f2354cb5ad0726bbf11cff4469be7a070132d3339921881ae5df2398b71f16","truncated":false}
29
+ {"repo_id":"SuperAlignment","entity_id":"file:test_train_example.py","uri":"program://SuperAlignment/file/test_train_example.py","kind":"file","name":"test_train_example.py","path":"test_train_example.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torchvision.models import resnet18, resnet50\nfrom torch.utils.data import DataLoader, TensorDataset\nimport numpy as np\nfrom train_example import train_model\n\n# Define the teacher (weak model) and student (strong model)\nteacher_model = resnet18(pretrained=False) # Using pretrained=False for simplicity\nstudent_model = resnet50(pretrained=False)\n\n# Define a simple synthetic dataset resembling CIFAR-100\n# CIFAR-100 has 32x32 images with 3 channels\n# We'll create random data with similar dimensions\nnum_samples = 1000\ninput_channels = 3\ninput_height = 32\ninput_width = 32\nnum_classes = 100\n","source_hash":"6e808ad91b17c4e12df91f6ed188bfe810f9d6cb3ef55c61df0055a57b0abc0b","truncated":false}
30
+ {"repo_id":"SuperAlignment","entity_id":"file:dataset.py","uri":"program://SuperAlignment/file/dataset.py","kind":"file","name":"dataset.py","path":"dataset.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import torch\nfrom torch.utils.data import Dataset\nimport os\nfrom PIL import Image\nfrom generate_labels import generate_label_for_single_image\nimport json\n\n\n# Custom Dataset Class\nclass CustomImageDataset(Dataset):\n def __init__(\n self, image_dir, transform=None, model_name=\"google/vit-base-patch16-224\"\n ):\n self.image_dir = image_dir\n self.transform = transform\n self.memory_bank = load_memory_bank() # Load existing labels from memory bank\n self.image_paths = [\n os.path.join(image_dir, img)\n for img in os.listdir(image_dir)\n if img.endswith((\".png\", \".jpg\", \".jpeg\"))\n ]","source_hash":"981d68dd2e2858f57d74c1cd302ee09901a2fa38c665753fa9e6a5a0b08f1267","truncated":false}
31
+ {"repo_id":"SuperAlignment","entity_id":"file:train.py","uri":"program://SuperAlignment/file/train.py","kind":"file","name":"train.py","path":"train.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import torch\nimport torch.optim as optim\nfrom torchvision import transforms\nfrom torchvision.models import resnet18, resnet50\nfrom torch.utils.data import DataLoader\nimport numpy as np\nimport os\nimport json\nfrom utils import plot_and_save_metrics\nfrom dataset import CustomImageDataset\nfrom AdaptiveConfidenceDistillation import AdaptiveConfidenceDistillationLoss\n\n# Define the teacher (weak model) and student (strong model)\nteacher_model = resnet18(pretrained=True) # Using pretrained=False for simplicity\nstudent_model = resnet50(pretrained=True)\n\n# Define a simple synthetic dataset resembling CIFAR-100\n# CIFAR-100 has 32x32 images with 3 channels\n# We'll create random data with similar dimensions\nnum_samples = 1000\ninput_channels = 3","source_hash":"aec049768a636ee5c1da4badd75c577ef9b0a0665268f1006af96fee0e488a23","truncated":false}
32
+ {"repo_id":"SuperAlignment","entity_id":"file:utils.py","uri":"program://SuperAlignment/file/utils.py","kind":"file","name":"utils.py","path":"utils.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import matplotlib.pyplot as plt\nimport json\n\n\ndef plot_and_save_metrics(\n metrics, filename=\"training_metrics.png\", metrics_path=\"training_metrics.json\"\n):\n epochs = range(1, len(metrics[\"train_loss\"]) + 1)\n\n plt.figure(figsize=(10, 5))\n plt.subplot(1, 2, 1)\n plt.plot(epochs, metrics[\"train_loss\"], label=\"Training Loss\")\n plt.plot(epochs, metrics[\"val_loss\"], label=\"Validation Loss\")\n plt.title(\"Loss Metrics\")\n plt.xlabel(\"Epoch\")\n plt.ylabel(\"Loss\")\n plt.legend()\n\n # If you track accuracy, you can plot it here similarly.\n # plt.subplot(1, 2, 2)\n # plt.plot(epochs, metrics['train_accuracy'], label='Training Accuracy')","source_hash":"7804c1866cae172702f44d671accd34ee657dc7840952f9d6700cc17f267e8bd","truncated":false}
33
+ {"repo_id":"SuperAlignment","entity_id":"file:generate_labels.py","uri":"program://SuperAlignment/file/generate_labels.py","kind":"file","name":"generate_labels.py","path":"generate_labels.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"import os\nfrom transformers import ViTImageProcessor, ViTForImageClassification\nfrom PIL import Image\nimport json\nimport torch\n\n\ndef generate_label_for_single_image(image_path):\n # Initialize the model and processor\n model = ViTForImageClassification.from_pretrained(\"google/vit-base-patch16-224\")\n feature_extractor = ViTImageProcessor.from_pretrained(\"google/vit-base-patch16-224\")\n\n # Load and process the image\n image = Image.open(image_path).convert(\"RGB\")\n inputs = feature_extractor(images=image, return_tensors=\"pt\")\n\n # Predict the class of the image\n with torch.no_grad():\n outputs = model(**inputs)\n\n logits = outputs.logits","source_hash":"20a6fcb44164bd9974723b003b234785c2e029411323ddda3cb2fab53143ef64","truncated":false}
source_snippets/TOLBERT.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
source_snippets/TaskMatrix.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
source_snippets/TensorRT-LLM.jsonl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b5952c71a8250bb4acccf2f9ce824ff74841eef2317a56cc7701e743556fb0ae
3
+ size 121690393
source_snippets/TinyRecursiveModels.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
source_snippets/Track-Anything.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
source_snippets/TransformerEngine.jsonl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:95a7b2ba0746f9640b90ee9a8f16e093fe93e353cf7707a510e55828fde79ed0
3
+ size 18940191
source_snippets/WorkArena.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
source_snippets/abliterator.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
source_snippets/action-transformer-environment.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
source_snippets/action-transformer.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
source_snippets/agent-knowledge-generator.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
source_snippets/arrow_multitask.jsonl ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {"repo_id":"arrow_multitask","entity_id":"py:arrow_phi3_mini","uri":"program://arrow_multitask/module/arrow_phi3_mini#L1-L383","kind":"module","name":"arrow_phi3_mini","path":"arrow_phi3_mini.py","language":"python","start_line":1,"end_line":383,"context_start_line":1,"context_end_line":383,"code":"# Copyright 2025-present the HuggingFace Inc. team.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"\nThis script provides a simple evaluation pipeline for multiple-choice reasoning datasets\n(e.g., BoolQ, HellaSwag, ARC, OpenBookQA, Winogrande) with different composition strategies.\n\nUsage examples:\n python arrow_phi3_mini.py --strategy base --ds_name arc-challenge\n python arrow_phi3_mini.py --strategy arrow --ds_name boolq\n python arrow_phi3_mini.py --strategy gks --ds_name hswag\n\nKey features:\n- Supports three strategies:\n • \"base\" → Evaluate the quantized base model directly\n • \"arrow\" → Use Arrow modular routing with task-specific adapters\n • \"gks\" → Use Arrow + GenKnowSub (subtracting general-domain knowledge)\n- Loads evaluation datasets from the Hugging Face Hub\n- Implements a batched evaluation loop that computes per-option likelihoods and selects\n the answer with the lowest average loss\n- Reports simple accuracy\n\nImplementation details:\n- The base model is quantized to 4-bit using `BitsAndBytesConfig` (nf4, bf16 compute).\n- For Arrow and GKS, task-specific adapters are loaded from the Hugging Face Hub:\n TahaBa/phi3-mini-clustered-flan/ts_expert_i\n- Task-specific adapters were trained on 10 clusters of FLAN tasks.\n- The clusters were created using Model-Based Clustering (MBC):\n 1. Train a LoRA adapter for each individual task.\n 2. Apply k-means clustering to group tasks based on these adapters.\n 3. Train a LoRA adapter for each resulting cluster.\nFor more details, see the Arrow paper: https://huggingface.co/papers/2405.11157\n\n- For GKS, general adapters are loaded from:\n TahaBa/phi3-mini-general-adapters/...\n- These adapters were trained on English, French, and German Wikipedia data\n using a causal language modeling objective with (507-token context → 5-token completion) pairs.\n- This setup encodes general knowledge into the LoRA space, which can then be\n subtracted from task-specific adapters during inference to isolate and purify them.\nFor more details, see the GenKnowSub paper: https://huggingface.co/papers/2505.10939\n\n- `evaluate_on_multi_choice_batched` handles tokenization, masking context tokens,\n and computing per-choice log-likelihoods for fair comparison.\n- Accuracy is printed at the end for the selected dataset.\n\nThis script is mainly meant for demonstration purposes and lightweight evaluation,\nnot full-scale benchmarking (batch size / max length can be tuned).\n\n=======================================================================================\n\nResults (evaluated with microsoft/Phi-3-mini-4k-instruct, 4-bit quantization):\n\n| Dataset | Base Acc. | Arrow Acc. | Arrow+GKS Acc. |\n|--------------|-----------|------------|----------------|\n| ARC-Challenge| 0.4515 | 0.5418 | 0.5585 |\n| ARC-Easy | 0.6894 | 0.8404 | 0.8473 |\n| Winogrande | 0.5769 | 0.6550 | 0.6724 |\n| BoolQ | 0.8146 | 0.8030 | 0.8247 |\n| OpenBookQA | 0.43 | 0.448 | 0.472 |\n| HellaSwag | 0.7318 | 0.7150 | 0.7376 |\n\nObservations:\n- Arrow generally improves over the base model by routing tokens to the most relevant task adapters.\n- Applying GKS (general knowledge subtraction) consistently gives further gains compared to Arrow and Base.\n\nThese numbers are not meant as leaderboard results, but as a sanity check\nto verify that the implementation works as expected and demonstrates\nthe benefits of Arrow and GenKnowSub.\n\"\"\"\n\nimport argparse\nimport random\n\nimport numpy as np\nimport torch\nfrom datasets import load_dataset\nfrom sklearn.metrics import accuracy_score\nfrom tqdm import tqdm\nfrom transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig\n\nfrom peft import ArrowConfig, create_arrow_model\n\n\nMODEL_NAME = \"microsoft/Phi-3-mini-4k-instruct\"\nMODEL_MAX_LEN = 2048\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(description=\"Training script with strategy selection\")\n\n parser.add_argument(\n \"--strategy\",\n type=str,\n choices=[\"base\", \"arrow\", \"gks\"],\n default=\"base\",\n help=\"Training strategy to use: base, arrow, or gks\",\n )\n parser.add_argument(\n \"--ds_name\",\n type=str,\n choices=[\"boolq\", \"hswag\", \"arc-easy\", \"arc-challenge\", \"oqa\", \"wg\"],\n default=\"arc-challenge\",\n help=\"Dataset to use: boolq, hswag, arc-easy, arc-challenge, oqa, wg\",\n )\n\n return parser.parse_args()\n\n\ndef read_test_dataset(ds_name):\n if ds_name == \"boolq\":\n ds = load_dataset(\"google/boolq\", split=\"validation\", trust_remote_code=True)\n elif ds_name == \"hswag\":\n ds = load_dataset(\"Rowan/hellaswag\", split=\"validation\", trust_remote_code=True)\n elif ds_name == \"arc-challenge\":\n ds = load_dataset(\"allenai/ai2_arc\", \"ARC-Challenge\", split=\"validation\", trust_remote_code=True)\n elif ds_name == \"arc-easy\":\n ds = load_dataset(\"allenai/ai2_arc\", \"ARC-Easy\", split=\"validation\", trust_remote_code=True)\n elif ds_name == \"oqa\":\n ds = load_dataset(\"allenai/openbookqa\", split=\"validation\", trust_remote_code=True)\n elif ds_name == \"wg\":\n ds = load_dataset(\"allenai/winogrande\", \"winogrande_xl\", split=\"validation\", trust_remote_code=True)\n else:\n raise f\"Dataset {ds_name} is not supported yet.\"\n\n return ds\n\n\ndef extract_input_content(ds_name, row):\n if ds_name == \"boolq\":\n return f\"[passage]{row['passage']}[question]{row['question']}\"\n if ds_name == \"hswag\":\n return row[\"ctx\"]\n if (ds_name == \"arc-challenge\") or (ds_name == \"arc-easy\"):\n return row[\"question\"]\n if ds_name == \"oqa\":\n return row[\"question_stem\"]\n if ds_name == \"wg\":\n return row[\"sentence\"]\n\n\ndef create_multi_choice_options(row, ds_name):\n options_texts = []\n content = extract_input_content(ds_name, row)\n if ds_name == \"boolq\":\n choices = [\"true\", \"false\"]\n if ds_name == \"hswag\":\n choices = row[\"endings\"]\n if (ds_name == \"arc-challenge\") or (ds_name == \"arc-easy\"):\n choices = row[\"choices\"][\"text\"]\n if ds_name == \"wg\":\n choices = [row[\"option1\"], row[\"option2\"]]\n if ds_name == \"oqa\":\n choices = row[\"choices\"][\"text\"]\n\n for choice in choices:\n options_texts.append(f\"<|user|>\\n{content}<|end|>\\n<|assistant|>{choice}<|end|>\\n\")\n\n return options_texts\n\n\ndef extract_multi_choice_target_index(row, ds_name):\n if ds_name == \"boolq\":\n return 0 if row[\"answer\"] is True else 1\n if ds_name == \"hswag\":\n return int(row[\"label\"])\n if (ds_name == \"arc-challenge\") or (ds_name == \"arc-easy\"):\n return row[\"choices\"][\"label\"].index(row[\"answerKey\"])\n if ds_name == \"wg\":\n return int(row[\"answer\"]) - 1\n if ds_name == \"oqa\":\n return row[\"choices\"][\"label\"].index(row[\"answerKey\"])\n\n\ndef set_seed(seed: int):\n random.seed(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n if torch.cuda.is_available():\n torch.cuda.manual_seed_all(seed)\n elif hasattr(torch, \"xpu\") and torch.xpu.is_available():\n torch.xpu.manual_seed_all(seed)\n\n\ndef compute_loglike_loss(logits, labels, reduction=\"none\"):\n bs = logits.size(0)\n vocab_size = logits.size(-1)\n labels = labels.squeeze(-1)\n shift_logits = logits[..., :-1, :].contiguous()\n shift_labels = labels[..., 1:].contiguous()\n\n # Flatten the tokens\n loss_fct = torch.nn.CrossEntropyLoss(reduction=reduction)\n shift_logits = shift_logits.view(-1, vocab_size)\n shift_labels = shift_labels.view(-1)\n\n shift_labels = shift_labels.to(shift_logits.device)\n loss = loss_fct(shift_logits, shift_labels)\n\n # reshape back\n if reduction == \"none\":\n loss = loss.view((bs, -1))\n non_zero_loss = (loss != 0).sum(dim=-1)\n non_zero_loss[non_zero_loss == 0] = 1\n loss = loss.sum(dim=-1) / non_zero_loss\n\n return loss.float() # Convert to float32 before returning\n\n\ndef evaluate_on_multi_choice_batched(\n eval_dataset, model, tokenizer, ds_name, labels, predictions, args, batch_size=32, max_length=512, device=\"auto\"\n):\n # Local import to mirror your original function\n model.eval()\n\n if device == \"auto\":\n device = torch.accelerator.current_accelerator().type if hasattr(torch, \"accelerator\") else \"cuda\"\n else:\n device = torch.device(device)\n\n for start in tqdm(\n range(0, len(eval_dataset), batch_size), total=(len(eval_dataset) + batch_size - 1) // batch_size\n ):\n rows = [eval_dataset[i] for i in range(start, min(start + batch_size, len(eval_dataset)))]\n\n # Build the flattened option texts for this batch\n all_texts = []\n options_per_sample = [] # number of options for each sample\n ctx_lens_per_option = [] # context length replicated per option\n\n for row in rows:\n # options: [\"<|user|>...<|assistant|>choiceA<|end|>\", ...]\n options = create_multi_choice_options(row, ds_name)\n options_per_sample.append(len(options))\n\n # compute context length once per sample (align with your -1 shift)\n content = extract_input_content(ds_name, row)\n context_prompt = f\"<|user|>\\n{content}<|end|>\\n<|assistant|>\"\n ctx_len = len(tokenizer.encode(context_prompt)) - 1\n\n all_texts.extend(options)\n ctx_lens_per_option.extend([ctx_len] * len(options))\n\n # collect gold label\n labels.append(extract_multi_choice_target_index(row, ds_name))\n\n # Tokenize all options in one go\n tokenized = tokenizer(\n all_texts,\n return_tensors=\"pt\",\n padding=True,\n truncation=True,\n max_length=max_length,\n )\n tokenized = {k: v.to(device) for k, v in tokenized.items()}\n\n # Create masked labels: ignore context and padding\n masked_labels = tokenized[\"input_ids\"].clone()\n for i, ctx_len in enumerate(ctx_lens_per_option):\n masked_labels[i, :ctx_len] = -100\n masked_labels[tokenized[\"attention_mask\"] == 0] = -100\n\n with torch.no_grad():\n logits = model(input_ids=tokenized[\"input_ids\"], attention_mask=tokenized[\"attention_mask\"]).logits\n # per-sequence losses\n losses = compute_loglike_loss(logits, masked_labels, reduction=\"none\").detach().cpu()\n\n # Reduce per sample (argmin across its options)\n idx = 0\n for n_opt in options_per_sample:\n pred = torch.argmin(losses[idx : idx + n_opt]).item()\n predictions.append(pred)\n idx += n_opt\n\n print(\n f\"Accuracy for dataset {args.ds_name} and strategy {args.strategy} is: {accuracy_score(labels, predictions)}\"\n )\n\n\nif __name__ == \"__main__\":\n args = parse_args()\n print(f\"Selected strategy: {args.strategy}\")\n print(f\"Dataset name: {args.ds_name}\")\n\n # Loading the tokeniser\n tokenizer = AutoTokenizer.from_pretrained(\n MODEL_NAME,\n use_fast=True,\n padding_side=\"right\",\n model_max_length=MODEL_MAX_LEN,\n )\n\n # Quantisation config\n bnb_config = BitsAndBytesConfig(\n load_in_4bit=True,\n bnb_4bit_quant_type=\"nf4\",\n bnb_4bit_compute_dtype=torch.bfloat16,\n bnb_4bit_use_double_quant=False,\n )\n\n # Loading the model\n base_model = AutoModelForCausalLM.from_pretrained(\n MODEL_NAME,\n dtype=torch.bfloat16,\n device_map=\"auto\",\n quantization_config=bnb_config,\n )\n\n # Loading the test dataset\n test_dataset = read_test_dataset(args.ds_name)\n print(f\"{args.ds_name} is loaded with size: {len(test_dataset)}.\")\n\n labels, predictions = [], []\n if args.strategy == \"base\":\n # Batch-wise inference\n with torch.no_grad():\n evaluate_on_multi_choice_batched(\n test_dataset,\n base_model,\n tokenizer,\n args.ds_name,\n labels,\n predictions,\n args,\n batch_size=64, # tune this\n max_length=512, # tune if options are long\n device=\"auto\",\n )\n else:\n general_adapter_paths = []\n if args.strategy == \"gks\":\n arrow_config = ArrowConfig(\n top_k=3,\n router_temperature=1.0,\n use_gks=True,\n )\n # General adapter paths from the hub\n general_adapter_paths = [\n \"TahaBa/phi3-mini-general-adapters/cluster0_batch16_prop1.0_langen/checkpoint-17\",\n \"TahaBa/phi3-mini-general-adapters/cluster0_batch16_prop1.0_langfr/checkpoint-35\",\n \"TahaBa/phi3-mini-general-adapters/cluster0_batch16_prop1.0_langger/checkpoint-17\",\n ]\n else:\n arrow_config = ArrowConfig(\n top_k=3,\n router_temperature=1.0,\n )\n\n # Task-specific adapter paths from the hub\n task_specific_adapter_paths = [f\"TahaBa/phi3-mini-clustered-flan/ts_expert_{i}\" for i in range(10)]\n\n # Creating the Arrow model\n model = create_arrow_model(\n base_model=base_model,\n task_specific_adapter_paths=task_specific_adapter_paths,\n general_adapter_paths=general_adapter_paths,\n arrow_config=arrow_config,\n )\n\n # Batch-wise inference\n with torch.no_grad():\n evaluate_on_multi_choice_batched(\n test_dataset,\n model,\n tokenizer,\n args.ds_name,\n labels,\n predictions,\n args,\n batch_size=32, # tune this\n max_length=512, # tune if options are long\n device=\"auto\",\n )","source_hash":"4f22c0ec4edfc3887174d817f9a09e92d96d632bbe84e6abba6cb620e7cb368c","truncated":false}
2
+ {"repo_id":"arrow_multitask","entity_id":"py:arrow_phi3_mini.parse_args","uri":"program://arrow_multitask/function/arrow_phi3_mini.parse_args#L99-L117","kind":"function","name":"parse_args","path":"arrow_phi3_mini.py","language":"python","start_line":99,"end_line":117,"context_start_line":79,"context_end_line":137,"code":"the benefits of Arrow and GenKnowSub.\n\"\"\"\n\nimport argparse\nimport random\n\nimport numpy as np\nimport torch\nfrom datasets import load_dataset\nfrom sklearn.metrics import accuracy_score\nfrom tqdm import tqdm\nfrom transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig\n\nfrom peft import ArrowConfig, create_arrow_model\n\n\nMODEL_NAME = \"microsoft/Phi-3-mini-4k-instruct\"\nMODEL_MAX_LEN = 2048\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(description=\"Training script with strategy selection\")\n\n parser.add_argument(\n \"--strategy\",\n type=str,\n choices=[\"base\", \"arrow\", \"gks\"],\n default=\"base\",\n help=\"Training strategy to use: base, arrow, or gks\",\n )\n parser.add_argument(\n \"--ds_name\",\n type=str,\n choices=[\"boolq\", \"hswag\", \"arc-easy\", \"arc-challenge\", \"oqa\", \"wg\"],\n default=\"arc-challenge\",\n help=\"Dataset to use: boolq, hswag, arc-easy, arc-challenge, oqa, wg\",\n )\n\n return parser.parse_args()\n\n\ndef read_test_dataset(ds_name):\n if ds_name == \"boolq\":\n ds = load_dataset(\"google/boolq\", split=\"validation\", trust_remote_code=True)\n elif ds_name == \"hswag\":\n ds = load_dataset(\"Rowan/hellaswag\", split=\"validation\", trust_remote_code=True)\n elif ds_name == \"arc-challenge\":\n ds = load_dataset(\"allenai/ai2_arc\", \"ARC-Challenge\", split=\"validation\", trust_remote_code=True)\n elif ds_name == \"arc-easy\":\n ds = load_dataset(\"allenai/ai2_arc\", \"ARC-Easy\", split=\"validation\", trust_remote_code=True)\n elif ds_name == \"oqa\":\n ds = load_dataset(\"allenai/openbookqa\", split=\"validation\", trust_remote_code=True)\n elif ds_name == \"wg\":\n ds = load_dataset(\"allenai/winogrande\", \"winogrande_xl\", split=\"validation\", trust_remote_code=True)\n else:\n raise f\"Dataset {ds_name} is not supported yet.\"\n\n return ds\n","source_hash":"4f22c0ec4edfc3887174d817f9a09e92d96d632bbe84e6abba6cb620e7cb368c","truncated":false}
3
+ {"repo_id":"arrow_multitask","entity_id":"py:arrow_phi3_mini.read_test_dataset","uri":"program://arrow_multitask/function/arrow_phi3_mini.read_test_dataset#L120-L136","kind":"function","name":"read_test_dataset","path":"arrow_phi3_mini.py","language":"python","start_line":120,"end_line":136,"context_start_line":100,"context_end_line":156,"code":" parser = argparse.ArgumentParser(description=\"Training script with strategy selection\")\n\n parser.add_argument(\n \"--strategy\",\n type=str,\n choices=[\"base\", \"arrow\", \"gks\"],\n default=\"base\",\n help=\"Training strategy to use: base, arrow, or gks\",\n )\n parser.add_argument(\n \"--ds_name\",\n type=str,\n choices=[\"boolq\", \"hswag\", \"arc-easy\", \"arc-challenge\", \"oqa\", \"wg\"],\n default=\"arc-challenge\",\n help=\"Dataset to use: boolq, hswag, arc-easy, arc-challenge, oqa, wg\",\n )\n\n return parser.parse_args()\n\n\ndef read_test_dataset(ds_name):\n if ds_name == \"boolq\":\n ds = load_dataset(\"google/boolq\", split=\"validation\", trust_remote_code=True)\n elif ds_name == \"hswag\":\n ds = load_dataset(\"Rowan/hellaswag\", split=\"validation\", trust_remote_code=True)\n elif ds_name == \"arc-challenge\":\n ds = load_dataset(\"allenai/ai2_arc\", \"ARC-Challenge\", split=\"validation\", trust_remote_code=True)\n elif ds_name == \"arc-easy\":\n ds = load_dataset(\"allenai/ai2_arc\", \"ARC-Easy\", split=\"validation\", trust_remote_code=True)\n elif ds_name == \"oqa\":\n ds = load_dataset(\"allenai/openbookqa\", split=\"validation\", trust_remote_code=True)\n elif ds_name == \"wg\":\n ds = load_dataset(\"allenai/winogrande\", \"winogrande_xl\", split=\"validation\", trust_remote_code=True)\n else:\n raise f\"Dataset {ds_name} is not supported yet.\"\n\n return ds\n\n\ndef extract_input_content(ds_name, row):\n if ds_name == \"boolq\":\n return f\"[passage]{row['passage']}[question]{row['question']}\"\n if ds_name == \"hswag\":\n return row[\"ctx\"]\n if (ds_name == \"arc-challenge\") or (ds_name == \"arc-easy\"):\n return row[\"question\"]\n if ds_name == \"oqa\":\n return row[\"question_stem\"]\n if ds_name == \"wg\":\n return row[\"sentence\"]\n\n\ndef create_multi_choice_options(row, ds_name):\n options_texts = []\n content = extract_input_content(ds_name, row)\n if ds_name == \"boolq\":\n choices = [\"true\", \"false\"]","source_hash":"4f22c0ec4edfc3887174d817f9a09e92d96d632bbe84e6abba6cb620e7cb368c","truncated":false}
4
+ {"repo_id":"arrow_multitask","entity_id":"py:arrow_phi3_mini.extract_input_content","uri":"program://arrow_multitask/function/arrow_phi3_mini.extract_input_content#L139-L149","kind":"function","name":"extract_input_content","path":"arrow_phi3_mini.py","language":"python","start_line":139,"end_line":149,"context_start_line":119,"context_end_line":169,"code":"\ndef read_test_dataset(ds_name):\n if ds_name == \"boolq\":\n ds = load_dataset(\"google/boolq\", split=\"validation\", trust_remote_code=True)\n elif ds_name == \"hswag\":\n ds = load_dataset(\"Rowan/hellaswag\", split=\"validation\", trust_remote_code=True)\n elif ds_name == \"arc-challenge\":\n ds = load_dataset(\"allenai/ai2_arc\", \"ARC-Challenge\", split=\"validation\", trust_remote_code=True)\n elif ds_name == \"arc-easy\":\n ds = load_dataset(\"allenai/ai2_arc\", \"ARC-Easy\", split=\"validation\", trust_remote_code=True)\n elif ds_name == \"oqa\":\n ds = load_dataset(\"allenai/openbookqa\", split=\"validation\", trust_remote_code=True)\n elif ds_name == \"wg\":\n ds = load_dataset(\"allenai/winogrande\", \"winogrande_xl\", split=\"validation\", trust_remote_code=True)\n else:\n raise f\"Dataset {ds_name} is not supported yet.\"\n\n return ds\n\n\ndef extract_input_content(ds_name, row):\n if ds_name == \"boolq\":\n return f\"[passage]{row['passage']}[question]{row['question']}\"\n if ds_name == \"hswag\":\n return row[\"ctx\"]\n if (ds_name == \"arc-challenge\") or (ds_name == \"arc-easy\"):\n return row[\"question\"]\n if ds_name == \"oqa\":\n return row[\"question_stem\"]\n if ds_name == \"wg\":\n return row[\"sentence\"]\n\n\ndef create_multi_choice_options(row, ds_name):\n options_texts = []\n content = extract_input_content(ds_name, row)\n if ds_name == \"boolq\":\n choices = [\"true\", \"false\"]\n if ds_name == \"hswag\":\n choices = row[\"endings\"]\n if (ds_name == \"arc-challenge\") or (ds_name == \"arc-easy\"):\n choices = row[\"choices\"][\"text\"]\n if ds_name == \"wg\":\n choices = [row[\"option1\"], row[\"option2\"]]\n if ds_name == \"oqa\":\n choices = row[\"choices\"][\"text\"]\n\n for choice in choices:\n options_texts.append(f\"<|user|>\\n{content}<|end|>\\n<|assistant|>{choice}<|end|>\\n\")\n\n return options_texts","source_hash":"4f22c0ec4edfc3887174d817f9a09e92d96d632bbe84e6abba6cb620e7cb368c","truncated":false}
5
+ {"repo_id":"arrow_multitask","entity_id":"py:arrow_phi3_mini.create_multi_choice_options","uri":"program://arrow_multitask/function/arrow_phi3_mini.create_multi_choice_options#L152-L169","kind":"function","name":"create_multi_choice_options","path":"arrow_phi3_mini.py","language":"python","start_line":152,"end_line":169,"context_start_line":132,"context_end_line":189,"code":" ds = load_dataset(\"allenai/winogrande\", \"winogrande_xl\", split=\"validation\", trust_remote_code=True)\n else:\n raise f\"Dataset {ds_name} is not supported yet.\"\n\n return ds\n\n\ndef extract_input_content(ds_name, row):\n if ds_name == \"boolq\":\n return f\"[passage]{row['passage']}[question]{row['question']}\"\n if ds_name == \"hswag\":\n return row[\"ctx\"]\n if (ds_name == \"arc-challenge\") or (ds_name == \"arc-easy\"):\n return row[\"question\"]\n if ds_name == \"oqa\":\n return row[\"question_stem\"]\n if ds_name == \"wg\":\n return row[\"sentence\"]\n\n\ndef create_multi_choice_options(row, ds_name):\n options_texts = []\n content = extract_input_content(ds_name, row)\n if ds_name == \"boolq\":\n choices = [\"true\", \"false\"]\n if ds_name == \"hswag\":\n choices = row[\"endings\"]\n if (ds_name == \"arc-challenge\") or (ds_name == \"arc-easy\"):\n choices = row[\"choices\"][\"text\"]\n if ds_name == \"wg\":\n choices = [row[\"option1\"], row[\"option2\"]]\n if ds_name == \"oqa\":\n choices = row[\"choices\"][\"text\"]\n\n for choice in choices:\n options_texts.append(f\"<|user|>\\n{content}<|end|>\\n<|assistant|>{choice}<|end|>\\n\")\n\n return options_texts\n\n\ndef extract_multi_choice_target_index(row, ds_name):\n if ds_name == \"boolq\":\n return 0 if row[\"answer\"] is True else 1\n if ds_name == \"hswag\":\n return int(row[\"label\"])\n if (ds_name == \"arc-challenge\") or (ds_name == \"arc-easy\"):\n return row[\"choices\"][\"label\"].index(row[\"answerKey\"])\n if ds_name == \"wg\":\n return int(row[\"answer\"]) - 1\n if ds_name == \"oqa\":\n return row[\"choices\"][\"label\"].index(row[\"answerKey\"])\n\n\ndef set_seed(seed: int):\n random.seed(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n if torch.cuda.is_available():","source_hash":"4f22c0ec4edfc3887174d817f9a09e92d96d632bbe84e6abba6cb620e7cb368c","truncated":false}
6
+ {"repo_id":"arrow_multitask","entity_id":"py:arrow_phi3_mini.extract_multi_choice_target_index","uri":"program://arrow_multitask/function/arrow_phi3_mini.extract_multi_choice_target_index#L172-L182","kind":"function","name":"extract_multi_choice_target_index","path":"arrow_phi3_mini.py","language":"python","start_line":172,"end_line":182,"context_start_line":152,"context_end_line":202,"code":"def create_multi_choice_options(row, ds_name):\n options_texts = []\n content = extract_input_content(ds_name, row)\n if ds_name == \"boolq\":\n choices = [\"true\", \"false\"]\n if ds_name == \"hswag\":\n choices = row[\"endings\"]\n if (ds_name == \"arc-challenge\") or (ds_name == \"arc-easy\"):\n choices = row[\"choices\"][\"text\"]\n if ds_name == \"wg\":\n choices = [row[\"option1\"], row[\"option2\"]]\n if ds_name == \"oqa\":\n choices = row[\"choices\"][\"text\"]\n\n for choice in choices:\n options_texts.append(f\"<|user|>\\n{content}<|end|>\\n<|assistant|>{choice}<|end|>\\n\")\n\n return options_texts\n\n\ndef extract_multi_choice_target_index(row, ds_name):\n if ds_name == \"boolq\":\n return 0 if row[\"answer\"] is True else 1\n if ds_name == \"hswag\":\n return int(row[\"label\"])\n if (ds_name == \"arc-challenge\") or (ds_name == \"arc-easy\"):\n return row[\"choices\"][\"label\"].index(row[\"answerKey\"])\n if ds_name == \"wg\":\n return int(row[\"answer\"]) - 1\n if ds_name == \"oqa\":\n return row[\"choices\"][\"label\"].index(row[\"answerKey\"])\n\n\ndef set_seed(seed: int):\n random.seed(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n if torch.cuda.is_available():\n torch.cuda.manual_seed_all(seed)\n elif hasattr(torch, \"xpu\") and torch.xpu.is_available():\n torch.xpu.manual_seed_all(seed)\n\n\ndef compute_loglike_loss(logits, labels, reduction=\"none\"):\n bs = logits.size(0)\n vocab_size = logits.size(-1)\n labels = labels.squeeze(-1)\n shift_logits = logits[..., :-1, :].contiguous()\n shift_labels = labels[..., 1:].contiguous()\n\n # Flatten the tokens","source_hash":"4f22c0ec4edfc3887174d817f9a09e92d96d632bbe84e6abba6cb620e7cb368c","truncated":false}
7
+ {"repo_id":"arrow_multitask","entity_id":"py:arrow_phi3_mini.set_seed","uri":"program://arrow_multitask/function/arrow_phi3_mini.set_seed#L185-L192","kind":"function","name":"set_seed","path":"arrow_phi3_mini.py","language":"python","start_line":185,"end_line":192,"context_start_line":165,"context_end_line":212,"code":"\n for choice in choices:\n options_texts.append(f\"<|user|>\\n{content}<|end|>\\n<|assistant|>{choice}<|end|>\\n\")\n\n return options_texts\n\n\ndef extract_multi_choice_target_index(row, ds_name):\n if ds_name == \"boolq\":\n return 0 if row[\"answer\"] is True else 1\n if ds_name == \"hswag\":\n return int(row[\"label\"])\n if (ds_name == \"arc-challenge\") or (ds_name == \"arc-easy\"):\n return row[\"choices\"][\"label\"].index(row[\"answerKey\"])\n if ds_name == \"wg\":\n return int(row[\"answer\"]) - 1\n if ds_name == \"oqa\":\n return row[\"choices\"][\"label\"].index(row[\"answerKey\"])\n\n\ndef set_seed(seed: int):\n random.seed(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n if torch.cuda.is_available():\n torch.cuda.manual_seed_all(seed)\n elif hasattr(torch, \"xpu\") and torch.xpu.is_available():\n torch.xpu.manual_seed_all(seed)\n\n\ndef compute_loglike_loss(logits, labels, reduction=\"none\"):\n bs = logits.size(0)\n vocab_size = logits.size(-1)\n labels = labels.squeeze(-1)\n shift_logits = logits[..., :-1, :].contiguous()\n shift_labels = labels[..., 1:].contiguous()\n\n # Flatten the tokens\n loss_fct = torch.nn.CrossEntropyLoss(reduction=reduction)\n shift_logits = shift_logits.view(-1, vocab_size)\n shift_labels = shift_labels.view(-1)\n\n shift_labels = shift_labels.to(shift_logits.device)\n loss = loss_fct(shift_logits, shift_labels)\n\n # reshape back\n if reduction == \"none\":\n loss = loss.view((bs, -1))","source_hash":"4f22c0ec4edfc3887174d817f9a09e92d96d632bbe84e6abba6cb620e7cb368c","truncated":false}
8
+ {"repo_id":"arrow_multitask","entity_id":"py:arrow_phi3_mini.compute_loglike_loss","uri":"program://arrow_multitask/function/arrow_phi3_mini.compute_loglike_loss#L195-L217","kind":"function","name":"compute_loglike_loss","path":"arrow_phi3_mini.py","language":"python","start_line":195,"end_line":217,"context_start_line":175,"context_end_line":237,"code":" if ds_name == \"hswag\":\n return int(row[\"label\"])\n if (ds_name == \"arc-challenge\") or (ds_name == \"arc-easy\"):\n return row[\"choices\"][\"label\"].index(row[\"answerKey\"])\n if ds_name == \"wg\":\n return int(row[\"answer\"]) - 1\n if ds_name == \"oqa\":\n return row[\"choices\"][\"label\"].index(row[\"answerKey\"])\n\n\ndef set_seed(seed: int):\n random.seed(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n if torch.cuda.is_available():\n torch.cuda.manual_seed_all(seed)\n elif hasattr(torch, \"xpu\") and torch.xpu.is_available():\n torch.xpu.manual_seed_all(seed)\n\n\ndef compute_loglike_loss(logits, labels, reduction=\"none\"):\n bs = logits.size(0)\n vocab_size = logits.size(-1)\n labels = labels.squeeze(-1)\n shift_logits = logits[..., :-1, :].contiguous()\n shift_labels = labels[..., 1:].contiguous()\n\n # Flatten the tokens\n loss_fct = torch.nn.CrossEntropyLoss(reduction=reduction)\n shift_logits = shift_logits.view(-1, vocab_size)\n shift_labels = shift_labels.view(-1)\n\n shift_labels = shift_labels.to(shift_logits.device)\n loss = loss_fct(shift_logits, shift_labels)\n\n # reshape back\n if reduction == \"none\":\n loss = loss.view((bs, -1))\n non_zero_loss = (loss != 0).sum(dim=-1)\n non_zero_loss[non_zero_loss == 0] = 1\n loss = loss.sum(dim=-1) / non_zero_loss\n\n return loss.float() # Convert to float32 before returning\n\n\ndef evaluate_on_multi_choice_batched(\n eval_dataset, model, tokenizer, ds_name, labels, predictions, args, batch_size=32, max_length=512, device=\"auto\"\n):\n # Local import to mirror your original function\n model.eval()\n\n if device == \"auto\":\n device = torch.accelerator.current_accelerator().type if hasattr(torch, \"accelerator\") else \"cuda\"\n else:\n device = torch.device(device)\n\n for start in tqdm(\n range(0, len(eval_dataset), batch_size), total=(len(eval_dataset) + batch_size - 1) // batch_size\n ):\n rows = [eval_dataset[i] for i in range(start, min(start + batch_size, len(eval_dataset)))]\n\n # Build the flattened option texts for this batch\n all_texts = []","source_hash":"4f22c0ec4edfc3887174d817f9a09e92d96d632bbe84e6abba6cb620e7cb368c","truncated":false}
9
+ {"repo_id":"arrow_multitask","entity_id":"py:arrow_phi3_mini.evaluate_on_multi_choice_batched","uri":"program://arrow_multitask/function/arrow_phi3_mini.evaluate_on_multi_choice_batched#L220-L287","kind":"function","name":"evaluate_on_multi_choice_batched","path":"arrow_phi3_mini.py","language":"python","start_line":220,"end_line":287,"context_start_line":200,"context_end_line":307,"code":" shift_labels = labels[..., 1:].contiguous()\n\n # Flatten the tokens\n loss_fct = torch.nn.CrossEntropyLoss(reduction=reduction)\n shift_logits = shift_logits.view(-1, vocab_size)\n shift_labels = shift_labels.view(-1)\n\n shift_labels = shift_labels.to(shift_logits.device)\n loss = loss_fct(shift_logits, shift_labels)\n\n # reshape back\n if reduction == \"none\":\n loss = loss.view((bs, -1))\n non_zero_loss = (loss != 0).sum(dim=-1)\n non_zero_loss[non_zero_loss == 0] = 1\n loss = loss.sum(dim=-1) / non_zero_loss\n\n return loss.float() # Convert to float32 before returning\n\n\ndef evaluate_on_multi_choice_batched(\n eval_dataset, model, tokenizer, ds_name, labels, predictions, args, batch_size=32, max_length=512, device=\"auto\"\n):\n # Local import to mirror your original function\n model.eval()\n\n if device == \"auto\":\n device = torch.accelerator.current_accelerator().type if hasattr(torch, \"accelerator\") else \"cuda\"\n else:\n device = torch.device(device)\n\n for start in tqdm(\n range(0, len(eval_dataset), batch_size), total=(len(eval_dataset) + batch_size - 1) // batch_size\n ):\n rows = [eval_dataset[i] for i in range(start, min(start + batch_size, len(eval_dataset)))]\n\n # Build the flattened option texts for this batch\n all_texts = []\n options_per_sample = [] # number of options for each sample\n ctx_lens_per_option = [] # context length replicated per option\n\n for row in rows:\n # options: [\"<|user|>...<|assistant|>choiceA<|end|>\", ...]\n options = create_multi_choice_options(row, ds_name)\n options_per_sample.append(len(options))\n\n # compute context length once per sample (align with your -1 shift)\n content = extract_input_content(ds_name, row)\n context_prompt = f\"<|user|>\\n{content}<|end|>\\n<|assistant|>\"\n ctx_len = len(tokenizer.encode(context_prompt)) - 1\n\n all_texts.extend(options)\n ctx_lens_per_option.extend([ctx_len] * len(options))\n\n # collect gold label\n labels.append(extract_multi_choice_target_index(row, ds_name))\n\n # Tokenize all options in one go\n tokenized = tokenizer(\n all_texts,\n return_tensors=\"pt\",\n padding=True,\n truncation=True,\n max_length=max_length,\n )\n tokenized = {k: v.to(device) for k, v in tokenized.items()}\n\n # Create masked labels: ignore context and padding\n masked_labels = tokenized[\"input_ids\"].clone()\n for i, ctx_len in enumerate(ctx_lens_per_option):\n masked_labels[i, :ctx_len] = -100\n masked_labels[tokenized[\"attention_mask\"] == 0] = -100\n\n with torch.no_grad():\n logits = model(input_ids=tokenized[\"input_ids\"], attention_mask=tokenized[\"attention_mask\"]).logits\n # per-sequence losses\n losses = compute_loglike_loss(logits, masked_labels, reduction=\"none\").detach().cpu()\n\n # Reduce per sample (argmin across its options)\n idx = 0\n for n_opt in options_per_sample:\n pred = torch.argmin(losses[idx : idx + n_opt]).item()\n predictions.append(pred)\n idx += n_opt\n\n print(\n f\"Accuracy for dataset {args.ds_name} and strategy {args.strategy} is: {accuracy_score(labels, predictions)}\"\n )\n\n\nif __name__ == \"__main__\":\n args = parse_args()\n print(f\"Selected strategy: {args.strategy}\")\n print(f\"Dataset name: {args.ds_name}\")\n\n # Loading the tokeniser\n tokenizer = AutoTokenizer.from_pretrained(\n MODEL_NAME,\n use_fast=True,\n padding_side=\"right\",\n model_max_length=MODEL_MAX_LEN,\n )\n\n # Quantisation config\n bnb_config = BitsAndBytesConfig(\n load_in_4bit=True,\n bnb_4bit_quant_type=\"nf4\",\n bnb_4bit_compute_dtype=torch.bfloat16,","source_hash":"4f22c0ec4edfc3887174d817f9a09e92d96d632bbe84e6abba6cb620e7cb368c","truncated":false}
10
+ {"repo_id":"arrow_multitask","entity_id":"file:arrow_phi3_mini.py","uri":"program://arrow_multitask/file/arrow_phi3_mini.py","kind":"file","name":"arrow_phi3_mini.py","path":"arrow_phi3_mini.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# Copyright 2025-present the HuggingFace Inc. team.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"\nThis script provides a simple evaluation pipeline for multiple-choice reasoning datasets\n(e.g., BoolQ, HellaSwag, ARC, OpenBookQA, Winogrande) with different composition strategies.\n\nUsage examples:\n python arrow_phi3_mini.py --strategy base --ds_name arc-challenge\n python arrow_phi3_mini.py --strategy arrow --ds_name boolq","source_hash":"4f22c0ec4edfc3887174d817f9a09e92d96d632bbe84e6abba6cb620e7cb368c","truncated":false}
source_snippets/augmentoolkit.jsonl ADDED
The diff for this file is too large to render. See raw diff