Views
No views yet
1import torch
2from peft import AutoPeftModelForCausalLM
3from transformers import AutoTokenizer
4import pandas as pd
5
6ADAPTER_REPO = "barbaroo/gptsw3_translate_synth_6.7B"
7BASE_MODEL = "AI-Sweden-Models/gpt-sw3-6.7b-v2"
8
9# 1. Load the tokenizer from the base model
10tokenizer = AutoTokenizer.from_pretrained(BASE_MODEL)
11
12model = AutoPeftModelForCausalLM.from_pretrained(
13 ADAPTER_REPO,
14 load_in_8bit=True, # Optional: 8-bit quantization for GPU memory efficiency
15 device_map="auto", # Automatically spread layers across available GPUs
16 dtype=torch.float16,
17)
18
19# Ensure the model is in evaluation mode
20model.eval()
21
22# Alpaca-style prompt template
23alpaca_prompt = """
24### Instruction:
25{}
26
27### Input:
28{}
29
30### Response:
31{}
32"""
33
34# EOS token from the tokenizer
35EOS_TOKEN = tokenizer.eos_token
36print(EOS_TOKEN)
37
38sentences = ['hello world']
39
40translations = []
41
42for sentence in sentences:
43 # Tokenize the input sentence and prepare the prompt for each sentence
44 inputs = tokenizer(
45 [
46 alpaca_prompt.format(
47 "Translate this sentence from English to Faroese:", # instruction
48 sentence, # input sentence to translate
49 "", # output - leave blank for generation
50 )
51 ],
52 return_tensors="pt"
53 ).to("cuda")
54
55 # Generate the output
56 outputs = model.generate(**inputs,
57 max_new_tokens=500,
58 eos_token_id=tokenizer.eos_token_id, # Ensure EOS token is used
59 pad_token_id=tokenizer.pad_token_id, # Ensure padding token is used
60 use_cache=True,
61 do_sample = True,
62 temperature = 0.1,
63 top_p=1)
64
65 # Decode the generated tokens into a string
66 output_string = tokenizer.batch_decode(outputs, skip_special_tokens=False)[0]
67 #print(output_string)
68
69 # Use a regular expression to extract the response part
70 try:
71 spl_word_1 = 'Response:\n'
72 res = output_string.split(spl_word_1, 1)
73 response = res[1]
74 translation = response.replace(EOS_TOKEN, '')
75 translations.append(translation)
76
77 except:
78 translation = ''
79 translations.append(translation)
80
81
82
83 print(translation)AI-Sweden-Models/gpt-sw3-6.7b-v2.