Views
No views yet

1LlamaForCausalLM(
2 (model): LlamaModel(
3 (embed_tokens): Embedding(128256, 4096)
4 (layers): ModuleList(
5 (0-5): 6 x LlamaDecoderLayer(
6 (self_attn): LlamaSdpaAttention(
7 (q_proj): BitLinear(in_features=4096, out_features=4096, bias=False)
8 (k_proj): BitLinear(in_features=4096, out_features=1024, bias=False)
9 (v_proj): BitLinear(in_features=4096, out_features=1024, bias=False)
10 (o_proj): BitLinear(in_features=4096, out_features=4096, bias=False)
11 (rotary_emb): LlamaRotaryEmbedding()
12 )
13 (mlp): LlamaMLP(
14 (gate_proj): BitLinear(in_features=4096, out_features=14336, bias=False)
15 (up_proj): BitLinear(in_features=4096, out_features=14336, bias=False)
16 (down_proj): BitLinear(in_features=14336, out_features=4096, bias=False)
17 (act_fn): SiLU()
18 )
19 (input_layernorm): Identity()
20 (post_attention_layernorm): LlamaRMSNorm((4096,), eps=1e-05)
21 )
22 )
23 (norm): LlamaRMSNorm((4096,), eps=1e-05)
24 (rotary_emb): LlamaRotaryEmbedding()
25 )
26 (lm_head): Linear(in_features=4096, out_features=128256, bias=False)
27)pip install transformers torch huggingface_hub wandb coloredlogs1from transformers import AutoModelForCausalLM, AutoTokenizer
2from transformers.models.llama.modeling_llama import *
3import torch
4from torch import nn
5import torch.nn.functional as F
6import coloredlogs
7import logging
8
9
10coloredlogs.install(level='INFO', fmt='%(asctime)s - %(levelname)s - %(message)s', logger=logging.getLogger())
11logger = logging.getLogger(__name__)
12
13
14
15
16HF_TOKEN = "you_api_key_here"
17
18model = "ejbejaranos/Llama3-8B-ITCL-Bitnet1.6B"
19
20# Load a pretrained BitNet model
21tokenizer = AutoTokenizer.from_pretrained(model)
22
23model = AutoModelForCausalLM.from_pretrained(
24 model,
25 token=HF_TOKEN
26)
27
28# Establece el pad_token_id
29model.config.pad_token_id = tokenizer.eos_token_id
30
31def count_parameters(model):
32 # Calculate the number of parameters in billions
33 num_params = sum(p.numel() for p in model.parameters() if p.requires_grad) / 10**9
34 print(f"Model size: {num_params:.3f}B parameters")
35 return int(num_params)
36
37def activation_quant(x):
38 scale = 127.0 / x.abs().max(dim=-1, keepdim=True).values.clamp_(min=1e-5)
39 y = (x * scale).round().clamp_(-128, 127)
40 y = y / scale
41 return y
42
43def weight_quant(w):
44 scale = 1.0 / w.abs().mean().clamp_(min=1e-5)
45 u = (w * scale).round().clamp_(-1, 1)
46 u = u / scale
47 return u
48
49class BitLinear(nn.Linear):
50 def forward(self, x):
51 w = self.weight # a weight tensor with shape [d, k]
52 x = x.to(w.device)
53 RMSNorm = LlamaRMSNorm(x.shape[-1]).to(w.device)
54 x_norm = RMSNorm(x)
55 x_quant = x_norm + (activation_quant(x_norm) - x_norm).detach()
56 w_quant = w + (weight_quant(w) - w).detach()
57 y = F.linear(x_quant, w_quant)
58 return y
59
60def convert_to_bitnet(model, copy_weights):
61 for name, module in model.named_modules():
62 if isinstance(module, LlamaSdpaAttention) or isinstance(module, LlamaMLP):
63 for child_name, child_module in module.named_children():
64 if isinstance(child_module, nn.Linear):
65 bitlinear = BitLinear(child_module.in_features, child_module.out_features, child_module.bias is not None).to(device="cuda:0")
66 if copy_weights:
67 bitlinear.weight = child_module.weight
68 if child_module.bias is not None:
69 bitlinear.bias = child_module.bias
70 setattr(module, child_name, bitlinear)
71 elif isinstance(module, LlamaDecoderLayer):
72 for child_name, child_module in module.named_children():
73 if isinstance(child_module, LlamaRMSNorm) and child_name == "input_layernorm":
74 setattr(module, child_name, nn.Identity().to(device="cuda:0"))
75
76convert_to_bitnet(model, copy_weights=True)
77model.to(device="cuda:0")
78
79
80logger.info(f"🔢 Number of parameters in the model after extracting weights: {count_parameters(model)}")
81logger.info(f"📏 Reduced model structure:\n{model}")
82
83
84
85
86
87prompt = "What is the color of sky?"
88inputs = tokenizer(prompt, return_tensors="pt", padding=True, truncation=True).to(model.device)
89inputs['attention_mask'] = inputs['input_ids'] != model.config.pad_token_id
90
91generate_ids = model.generate(inputs.input_ids, attention_mask=inputs['attention_mask'], max_length=250)
92decoded_output = tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)
93
94print(decoded_output[0]) # Print the generated response
95
961- What role does explainability play in your AI solutions?
2
3How can you ensure that your AI system is able to accurately predict and respond to user inputs?
4These are some of the questions that AI developers have been asking themselves in the last few years.
5In this section, we will explore some of the key concepts and techniques that AI developers have used to develop in their AI systems.
6
7First, let's consider the importance of understanding the role of AI in AI.
8AI systems can be incredibly powerful tools for automating tasks, analyzing data, and identifying patterns.
9They can analyze large datasets and identify patterns, trends, and anomalies that might be missed by human analysts.
10By analyzing large datasets, AI can help identify patterns and trends that might otherwise go unnoticed.
11
12One of the most significant challenges in AI development is the lack of transparency and accountability.
13With AI systems becoming increasingly sophisticated, there is a growing need for transparency and accountability in AI development.
14This means that there is a growing need for transparency and accountability in AI development.
15However, as AI becomes more sophisticated, it can also lead to unintended consequences, such as job loss or reputational damage.