Siddharth63 commited on
Commit
3de6052
·
verified ·
1 Parent(s): cfae895

Update README.md

Browse files
Files changed (1) hide show
  1. README.md +64 -3
README.md CHANGED
@@ -1,3 +1,64 @@
1
- ---
2
- license: artistic-2.0
3
- ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: artistic-2.0
3
+ ---
4
+ Inference:
5
+ ```
6
+ from transformers import AutoModelForCausalLM, AutoTokenizer
7
+ from transformers.models.llama.modeling_llama import *
8
+
9
+ # Load a pretrained BitNet model
10
+ model = "Siddharth63/Bitnet-250M"
11
+ tokenizer = AutoTokenizer.from_pretrained(model)
12
+ model = AutoModelForCausalLM.from_pretrained(model)
13
+
14
+
15
+ def activation_quant(x):
16
+ scale = 127.0 / x.abs().max(dim=-1, keepdim=True).values.clamp_(min=1e-5)
17
+ y = (x * scale).round().clamp_(-128, 127)
18
+ y = y / scale
19
+ return y
20
+ def weight_quant(w):
21
+ scale = 1.0 / w.abs().mean().clamp_(min=1e-5)
22
+ u = (w * scale).round().clamp_(-1, 1)
23
+ u = u / scale
24
+ return u
25
+
26
+ class BitLinear(nn.Linear):
27
+ def forward(self, x):
28
+ w = self.weight # a weight tensor with shape [d, k]
29
+ x = x.to(w.device)
30
+ RMSNorm = LlamaRMSNorm(x.shape[-1]).to(w.device)
31
+ x_norm = RMSNorm(x)
32
+ # A trick for implementing Straight−Through−Estimator (STE) using detach()
33
+ x_quant = x_norm + (activation_quant(x_norm) - x_norm).detach()
34
+ w_quant = w + (weight_quant(w) - w).detach()
35
+ y = F.linear(x_quant, w_quant)
36
+ return y
37
+
38
+ def convert_to_bitnet(model, copy_weights):
39
+ for name, module in model.named_modules():
40
+ # Replace linear layers with BitNet
41
+ if isinstance(module, LlamaSdpaAttention) or isinstance(module, LlamaMLP):
42
+ for child_name, child_module in module.named_children():
43
+ if isinstance(child_module, nn.Linear):
44
+ bitlinear = BitLinear(child_module.in_features, child_module.out_features, child_module.bias is not None).to(device="cuda:0")
45
+ if copy_weights:
46
+ bitlinear.weight = child_module.weight
47
+ if child_module.bias is not None:
48
+ bitlinear.bias = child_module.bias
49
+ setattr(module, child_name, bitlinear)
50
+ # Remove redundant input_layernorms
51
+ elif isinstance(module, LlamaDecoderLayer):
52
+ for child_name, child_module in module.named_children():
53
+ if isinstance(child_module, LlamaRMSNorm) and child_name == "input_layernorm":
54
+ setattr(module, child_name, nn.Identity().to(device="cuda:0"))
55
+
56
+
57
+ convert_to_bitnet(model, copy_weights=True)
58
+ model.to(device="cuda:0")
59
+
60
+ prompt = "Atherosclerosis is"
61
+ inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
62
+ generate_ids = model.generate(inputs.input_ids, max_length=50)
63
+ tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
64
+ ```