ejbejaranos commited on
Commit
17da5f9
verified
1 Parent(s): 4f6bf36

Create README.md

Browse files
Files changed (1) hide show
  1. README.md +157 -0
README.md ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ language:
4
+ - en
5
+ tags:
6
+ - bitnet
7
+ ---
8
+
9
+
10
+ # Bitnet-Nous-Llama3-225M 馃殌
11
+
12
+ Este modelo es una variante optimizada del **Llama3** utilizando la arquitectura **BitNet**, lo que reduce los pesos a los valores `-1`, `0`, y `1` para mejorar la eficiencia en el c贸mputo sin perder precisi贸n.
13
+
14
+ ## Modelo Base 馃
15
+
16
+ - **Modelo Original**: [Meta-Llama3-8B](https://huggingface.co/meta-llama/Meta-Llama-3-8B)
17
+ - **Par谩metros Reducidos**: 225M
18
+
19
+ ## Arquitectura 馃敡
20
+
21
+ El modelo transforma las capas lineales de Llama3 en capas **BitLinear**, aprovechando las siguientes t茅cnicas de cuantizaci贸n:
22
+
23
+ - **Cuantizaci贸n de activaciones**: Escala a 卤127
24
+ - **Cuantizaci贸n de pesos**: Escala a 卤1
25
+
26
+ ### Especificaciones T茅cnicas 馃搵
27
+
28
+ - **Dimensiones**: 768
29
+ - **Capas**: 6
30
+ - **Contexto**: 256 tokens
31
+ - **Tama帽o intermedio**: 1024
32
+ - **N煤mero de cabezas de atenci贸n**: 6
33
+
34
+
35
+ ## Dataset 馃摎
36
+
37
+ El modelo fue entrenado usando el dataset [Cosmopedia-100k-pretrain](https://huggingface.co/datasets/abideen/Cosmopedia-100k-pretrain), que contiene una variedad de datos de texto.
38
+
39
+ ## Entrenamiento 鈿欙笍
40
+
41
+ El modelo fue entrenado con la siguiente configuraci贸n:
42
+
43
+ - **Lote**: 16
44
+ - **Tasa de aprendizaje**: 1.5e-4
45
+ - **脡pocas**: 2
46
+ - **Acumulaci贸n de gradientes**: 2 pasos
47
+ - **Decaimiento de pesos**: 0.01
48
+ - **Precisi贸n Mixta**: FP16
49
+
50
+ ### Monitoreo 馃搳
51
+
52
+ El proceso de entrenamiento fue monitoreado usando **Weights & Biases**.
53
+
54
+ ## Uso del Modelo 馃捇
55
+
56
+ Para usar este modelo, puedes cargarlo desde Hugging Face con el siguiente c贸digo:
57
+ ```python
58
+ from transformers import AutoModelForCausalLM, AutoTokenizer
59
+ from transformers.models.llama.modeling_llama import *
60
+ import torch
61
+ from torch import nn
62
+ import torch.nn.functional as F
63
+ import coloredlogs
64
+ import logging
65
+
66
+ from utils.utils import count_parameters
67
+
68
+ coloredlogs.install(level='INFO', fmt='%(asctime)s - %(levelname)s - %(message)s', logger=logging.getLogger())
69
+ logger = logging.getLogger(__name__)
70
+
71
+
72
+
73
+
74
+ HF_TOKEN = "tuclaveaqui"
75
+ #model = "ejbejaranos/Bitnet-Llama3-from8BM-now2B"
76
+ model = "ejbejaranos/Bitnet-Nous-Llama3-225M" ## Working
77
+
78
+ # Load a pretrained BitNet model
79
+ tokenizer = AutoTokenizer.from_pretrained(model)
80
+
81
+ model = AutoModelForCausalLM.from_pretrained(
82
+ model,
83
+ token=HF_TOKEN
84
+ )
85
+
86
+
87
+ def count_parameters(model):
88
+ # Calculate the number of parameters in billions
89
+ num_params = sum(p.numel() for p in model.parameters() if p.requires_grad) / 10**9
90
+ print(f"Model size: {num_params:.3f}B parameters")
91
+ return int(num_params)
92
+
93
+
94
+
95
+ # Establece el pad_token_id
96
+ model.config.pad_token_id = tokenizer.eos_token_id
97
+
98
+ def activation_quant(x):
99
+ scale = 127.0 / x.abs().max(dim=-1, keepdim=True).values.clamp_(min=1e-5)
100
+ y = (x * scale).round().clamp_(-128, 127)
101
+ y = y / scale
102
+ return y
103
+
104
+ def weight_quant(w):
105
+ scale = 1.0 / w.abs().mean().clamp_(min=1e-5)
106
+ u = (w * scale).round().clamp_(-1, 1)
107
+ u = u / scale
108
+ return u
109
+
110
+ class BitLinear(nn.Linear):
111
+ def forward(self, x):
112
+ w = self.weight # a weight tensor with shape [d, k]
113
+ x = x.to(w.device)
114
+ RMSNorm = LlamaRMSNorm(x.shape[-1]).to(w.device)
115
+ x_norm = RMSNorm(x)
116
+ x_quant = x_norm + (activation_quant(x_norm) - x_norm).detach()
117
+ w_quant = w + (weight_quant(w) - w).detach()
118
+ y = F.linear(x_quant, w_quant)
119
+ return y
120
+
121
+ def convert_to_bitnet(model, copy_weights):
122
+ for name, module in model.named_modules():
123
+ if isinstance(module, LlamaSdpaAttention) or isinstance(module, LlamaMLP):
124
+ for child_name, child_module in module.named_children():
125
+ if isinstance(child_module, nn.Linear):
126
+ bitlinear = BitLinear(child_module.in_features, child_module.out_features, child_module.bias is not None).to(device="cuda:0")
127
+ if copy_weights:
128
+ bitlinear.weight = child_module.weight
129
+ if child_module.bias is not None:
130
+ bitlinear.bias = child_module.bias
131
+ setattr(module, child_name, bitlinear)
132
+ elif isinstance(module, LlamaDecoderLayer):
133
+ for child_name, child_module in module.named_children():
134
+ if isinstance(child_module, LlamaRMSNorm) and child_name == "input_layernorm":
135
+ setattr(module, child_name, nn.Identity().to(device="cuda:0"))
136
+
137
+ convert_to_bitnet(model, copy_weights=True)
138
+ model.to(device="cuda:0")
139
+
140
+
141
+ logger.info(f"馃敘 Number of parameters in the model after extracting weights: {count_parameters(model)}")
142
+ logger.info(f"馃搹 Reduced model structure:\n{model}")
143
+
144
+
145
+
146
+
147
+
148
+ prompt = "What is Machine Learning?"
149
+ inputs = tokenizer(prompt, return_tensors="pt", padding=True, truncation=True).to(model.device)
150
+ inputs['attention_mask'] = inputs['input_ids'] != model.config.pad_token_id
151
+
152
+ generate_ids = model.generate(inputs.input_ids, attention_mask=inputs['attention_mask'], max_length=250)
153
+ decoded_output = tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)
154
+
155
+ print(decoded_output[0]) # Print the generated response
156
+
157
+ ```