Views
No views yet
pip install torch transformers1# Tests were run with the following package versions
2# You can try with different versions as well but these should at least work
3import transformers
4import flash_attn
5import torch
6
7assert transformers.__version__ == 4.48.1
8assert torch.__version__ == 2.1.2+cu121
9assert flash_attn.__version__ == 2.7.31import torch
2from transformers import AutoModelForCausalLM, AutoTokenizer, GenerationConfig
3
4def load_llama_model(model_path, max_seq_length=2048, dtype=None):
5 """
6 Loads the LLaMA model with the given configuration.
7
8 Args:
9 model_path (str): Path or name of the pre-trained model.
10 max_seq_length (int): Maximum sequence length for the model.
11 dtype (torch.dtype or None): Data type for the model. Default is auto-detected.
12
13 Returns:
14 model, tokenizer, generation_config: Loaded model, tokenizer, and generation config.
15 """
16 # Set default dtype based on available hardware
17 torch_dtype = torch.bfloat16 if dtype is None else dtype
18
19 # Load model with appropriate configuration
20 model = AutoModelForCausalLM.from_pretrained(
21 model_path,
22 torch_dtype=torch_dtype,
23 device_map='auto',
24 attn_implementation="flash_attention_2" # If you do not have access to GPU supporting flash_attention_2 you can commit this line
25 )
26
27 tokenizer = AutoTokenizer.from_pretrained(model_path)
28
29 generation_config = GenerationConfig(
30 pad_token_id=tokenizer.eos_token_id,
31 eos_token_id=tokenizer.convert_tokens_to_ids("</s>")
32 )
33
34 return model, tokenizer, generation_config
35
36model_path = "RASMUS/AHMA-3B-RAG"1def generate_rag_prompt_message(row):
2 prompt = f'Olet tekoälyavustaja joka vastaa annetun kontekstin perusteella asiantuntevasti ja ystävällisesti käyttäjän kysymyksiin\n\nKonteksti: {row["text"]}\n\nKysymys: {row["question"]}\n\nVastaa yllä olevaan kysymykseen annetun kontekstin perusteella.'
3 row["messages"] = [{'role': 'user', 'content': prompt}]
4 return row1model, tokenizer, generation_config = load_llama_model(model_path)
2
3row = {"text": "Rasmus Toivanen loi tämän mallin", "question": "Kuka loi tämän mallin?"}
4row = generate_rag_prompt_message(row)
5
6inputs = tokenizer(
7 [
8 tokenizer.apply_chat_template(row["messages"], tokenize=False)
9 ] * 1, return_tensors="pt"
10).to("cuda")
11
12with torch.no_grad():
13 generated_ids = model.generate(
14 input_ids=inputs["input_ids"],
15 attention_mask=inputs["attention_mask"],
16 generation_config=generation_config, **{
17 "temperature": 0.1,
18 "penalty_alpha": 0.6,
19 "min_p": 0.3,
20 "do_sample": True,
21 "max_new_tokens": 300
22 }
23 )
24
25generated_text = tokenizer.batch_decode(generated_ids, skip_special_tokens=False, clean_up_tokenization_spaces=True)[0]
26generated_text_cleaned = generated_text.split('[/INST]')[1].replace('</s>', '').strip() if '[/INST]' in generated_text else generated_text.strip()
27
28print(generated_text_cleaned)