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