Views
No views yet
1from transformers import AutoModelForCausalLM, AutoTokenizer
2from transformers.generation import GenerationConfig
3
4model_path = 'CjangCjengh/LN-Thai-14B-v0.1'
5tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
6model = AutoModelForCausalLM.from_pretrained(model_path, device_map='auto', trust_remote_code=True).eval()
7model.generation_config = GenerationConfig.from_pretrained(model_path, trust_remote_code=True)
8
9# 段落之间用\n分隔
10text = '''“อาจารย์คะ ช่วยรับหนูเป็นลูกศิษย์ด้วยนะคะ”
11มิยุจัง เด็กสาวได้รับรู้ความลับของ ชาลี เด็กหนุ่มว่า ตัวจริงของคือท่านอาจารย์ 007H นักเขียนนิยายลามกชื่อดังที่เธอคลั่งไคล้ เด็กสาวผู้อยากจะเขียนนิยายลามกแบบนี้บ้างจึงมาขอฝากตัวเป็นลูกศิษย์ของชาลี พร้อมกับเรื่องวุ่น ๆ ของเด็กหนุ่มที่อยากไล่เธอออกไปก่อนที่ชีวิตส่วนตัวของตัวเองจะพินาศไปในพริบตา ทว่า นานวันเข้าความสัมพันธ์ของอาจารย์หนุ่มกับลูกศิษย์ตัวน้อยก็เริ่มแน่นแฟ้นมากขึ้น
12นิยายลามกเรื่องใหม่ครั้งนี้ชาลีจะเขียนเสร็จก่อนหรือเข้าไปนอนในดาวหมีก่อนกันนะ ?'''
13
14# 去除零宽空格
15text = text.replace('\u200b','')
16
17# 文本长度控制在2048以内
18assert len(text) < 2048
19
20messages = [
21 {'role': 'user', 'content': f'翻译成中文:\n{text}'}
22]
23
24text = tokenizer.apply_chat_template(
25 messages,
26 tokenize=False,
27 add_generation_prompt=True
28)
29
30model_inputs = tokenizer([text], return_tensors='pt').to('cuda')
31
32generated_ids = model.generate(
33 model_inputs.input_ids,
34 max_new_tokens=1024
35)
36
37generated_ids = [
38 output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)
39]
40
41response = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
42print(response)