84basi commited on
Commit
7adf650
·
verified ·
1 Parent(s): 73103bf

update readme

Browse files
Files changed (1) hide show
  1. README.md +84 -98
README.md CHANGED
@@ -21,109 +21,34 @@ This llama model was trained 2x faster with [Unsloth](https://github.com/unsloth
21
 
22
  [<img src="https://raw.githubusercontent.com/unslothai/unsloth/main/images/unsloth%20made%20with%20love.png" width="200"/>](https://github.com/unslothai/unsloth)
23
 
24
- !pip uninstall unsloth -y
25
- !pip install --upgrade --no-cache-dir "unsloth[colab-new] @ git+https://github.com/unslothai/unsloth.git"
26
- !pip install --upgrade torch
27
- !pip install --upgrade xformers
28
- !pip install ipywidgets --upgrade
29
 
30
- import torch
31
- if torch.cuda.get_device_capability()[0] >= 8:
32
- !pip install --no-deps packaging ninja einops "flash-attn>=2.6.3"
33
 
34
- from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
35
  from unsloth import FastLanguageModel
36
  import torch
37
- max_seq_length = 512
 
 
 
 
 
38
  dtype = None
39
  load_in_4bit = True
40
 
41
- model_id = "llm-jp/llm-jp-3-13b"
42
- new_model_id = "llm-jp-3-13b-finetune-2"
43
  model, tokenizer = FastLanguageModel.from_pretrained(
44
- model_name=model_id,
45
- dtype=dtype,
46
- load_in_4bit=load_in_4bit,
47
- trust_remote_code=True,
48
- )
49
-
50
- model = FastLanguageModel.get_peft_model(
51
- model,
52
- r = 32,
53
- target_modules = ["q_proj", "k_proj", "v_proj", "o_proj",
54
- "gate_proj", "up_proj", "down_proj",],
55
- lora_alpha = 32,
56
- lora_dropout = 0.05,
57
- bias = "none",
58
- use_gradient_checkpointing = "unsloth",
59
- random_state = 3407,
60
- use_rslora = False,
61
- loftq_config = None,
62
- max_seq_length = max_seq_length,
63
- )
64
-
65
- HF_TOKEN = "" #@param {type:"string"}
66
-
67
- from datasets import load_dataset
68
- dataset = load_dataset("json", data_files="/content/ichikara-instruction-003-001-1.json")
69
-
70
- prompt = """### 指示
71
- {}
72
- ### 回答
73
- {}"""
74
-
75
-
76
- """
77
- formatting_prompts_func: 各データをプロンプトに合わせた形式に合わせる
78
- """
79
- EOS_TOKEN = tokenizer.eos_token
80
- def formatting_prompts_func(examples):
81
- input = examples["text"]
82
- output = examples["output"]
83
- text = prompt.format(input, output) + EOS_TOKEN
84
- return { "formatted_text" : text, }
85
- pass
86
-
87
- dataset = dataset.map(
88
- formatting_prompts_func,
89
- num_proc= 4,
90
- )
91
-
92
- from trl import SFTTrainer
93
- from transformers import TrainingArguments
94
- from unsloth import is_bfloat16_supported
95
-
96
- trainer = SFTTrainer(
97
- model = model,
98
- tokenizer = tokenizer,
99
- train_dataset=dataset["train"],
100
  max_seq_length = max_seq_length,
101
- dataset_text_field="formatted_text",
102
- packing = False,
103
- args = TrainingArguments(
104
- per_device_train_batch_size = 2,
105
- gradient_accumulation_steps = 4,
106
- num_train_epochs = 1,
107
- logging_steps = 10,
108
- warmup_steps = 10,
109
- save_steps=100,
110
- save_total_limit=2,
111
- max_steps=-1,
112
- learning_rate = 2e-4,
113
- fp16 = not is_bfloat16_supported(),
114
- bf16 = is_bfloat16_supported(),
115
- group_by_length=True,
116
- seed = 3407,
117
- output_dir = "outputs",
118
- report_to = "none",
119
- ),
120
  )
 
121
 
122
- trainer_stats = trainer.train()
123
-
124
- import json
125
  datasets = []
126
- with open("/content/elyza-tasks-100-TV_0.jsonl", "r") as f:
127
  item = ""
128
  for line in f:
129
  line = line.strip()
@@ -134,22 +59,83 @@ with open("/content/elyza-tasks-100-TV_0.jsonl", "r") as f:
134
 
135
  from tqdm import tqdm
136
 
137
- FastLanguageModel.for_inference(model)
138
-
139
  results = []
140
  for dt in tqdm(datasets):
141
  input = dt["input"]
142
-
143
  prompt = f"""### 指示\n{input}\n### 回答\n"""
144
-
145
  inputs = tokenizer([prompt], return_tensors = "pt").to(model.device)
146
-
147
  outputs = model.generate(**inputs, max_new_tokens = 512, use_cache = True, do_sample=False, repetition_penalty=1.2)
148
  prediction = tokenizer.decode(outputs[0], skip_special_tokens=True).split('\n### 回答')[-1]
149
-
150
  results.append({"task_id": dt["task_id"], "input": input, "output": prediction})
151
 
152
- with open(f"{new_model_id}_output.jsonl", 'w', encoding='utf-8') as f:
153
  for result in results:
154
  json.dump(result, f, ensure_ascii=False)
155
  f.write('\n')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
 
22
  [<img src="https://raw.githubusercontent.com/unslothai/unsloth/main/images/unsloth%20made%20with%20love.png" width="200"/>](https://github.com/unslothai/unsloth)
23
 
24
+ ```python
 
 
 
 
25
 
26
+ %%capture
27
+ !pip install unsloth
28
+ !pip uninstall unsloth -y && pip install --upgrade --no-cache-dir "unsloth[colab-new] @ git+https://github.com/unslothai/unsloth.git"
29
 
 
30
  from unsloth import FastLanguageModel
31
  import torch
32
+ import json
33
+
34
+ model_name = "84basi/llm-jp-3-13b-finetune-2.1"
35
+ token = "Hugging Face Token" #@param {type:"string"}
36
+
37
+ max_seq_length = 2048
38
  dtype = None
39
  load_in_4bit = True
40
 
 
 
41
  model, tokenizer = FastLanguageModel.from_pretrained(
42
+ model_name = model_name,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
  max_seq_length = max_seq_length,
44
+ dtype = dtype,
45
+ load_in_4bit = load_in_4bit,
46
+ token = token,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
  )
48
+ FastLanguageModel.for_inference(model)
49
 
 
 
 
50
  datasets = []
51
+ with open("./elyza-tasks-100-TV_0.jsonl", "r") as f:
52
  item = ""
53
  for line in f:
54
  line = line.strip()
 
59
 
60
  from tqdm import tqdm
61
 
 
 
62
  results = []
63
  for dt in tqdm(datasets):
64
  input = dt["input"]
 
65
  prompt = f"""### 指示\n{input}\n### 回答\n"""
 
66
  inputs = tokenizer([prompt], return_tensors = "pt").to(model.device)
 
67
  outputs = model.generate(**inputs, max_new_tokens = 512, use_cache = True, do_sample=False, repetition_penalty=1.2)
68
  prediction = tokenizer.decode(outputs[0], skip_special_tokens=True).split('\n### 回答')[-1]
 
69
  results.append({"task_id": dt["task_id"], "input": input, "output": prediction})
70
 
71
+ with open(f"/content/llm-jp-3-13b-finetune-2.1_output-2.jsonl", 'w', encoding='utf-8') as f:
72
  for result in results:
73
  json.dump(result, f, ensure_ascii=False)
74
  f.write('\n')
75
+
76
+ !pip install python-docx
77
+
78
+ import json
79
+
80
+ from docx import Document # pip install python-docxでインストールする
81
+ from docx.shared import Inches, Pt, RGBColor
82
+ from docx.enum.text import WD_ALIGN_PARAGRAPH
83
+
84
+
85
+ def read_jsonl_data(jsonl_path):
86
+ """
87
+ 提出用jsonlを読み、json形式で返す
88
+
89
+ Args:
90
+ jsonl_path (str): 提出用jsonlへのパス
91
+
92
+ Returns:
93
+ jsonデータ (list of dict)
94
+ """
95
+ results = []
96
+ with open(jsonl_path, 'r', encoding='utf-8') as f:
97
+ for line in f:
98
+ line = line.strip()
99
+ if line:
100
+ try:
101
+ results.append(json.loads(line))
102
+ except json.JSONDecodeError as e:
103
+ print(f"JSONデコードエラー(行内容を確認してください): {e}")
104
+ return results
105
+
106
+
107
+ def json_to_word(json_data, output_file):
108
+ """
109
+ JSONデータをWord文書に変換する
110
+
111
+ Args:
112
+ json_data (list of dict): JSONデータのリスト
113
+ output_file (str): 出力するWordファイルの名前
114
+ """
115
+ doc = Document()
116
+
117
+ title = doc.add_heading('LLM Output Analysis', 0)
118
+ title.alignment = WD_ALIGN_PARAGRAPH.CENTER
119
+
120
+ for item in json_data:
121
+ task_id = item.get("task_id", "No Task ID")
122
+ doc.add_heading(f'Task ID: {task_id}', level=1)
123
+
124
+ doc.add_heading('Input:', level=2)
125
+ input_text = item.get("input", "No Input")
126
+ input_para = doc.add_paragraph()
127
+ input_para.add_run(input_text).bold = False
128
+
129
+ doc.add_heading('Output:', level=2)
130
+ output_text = item.get("output", "No Output")
131
+ output_para = doc.add_paragraph()
132
+ output_para.add_run(output_text).bold = False
133
+
134
+ doc.add_paragraph('=' * 50)
135
+ doc.save(output_file)
136
+
137
+ jsonl_path = '/content/llm-jp-3-13b-finetune-2.1_output-2.jsonl'
138
+ output_file = '/content/llm-jp-3-13b-finetune-2.1_output-2.docx'
139
+ jsonl_data = read_jsonl_data(jsonl_path)
140
+ json_to_word(jsonl_data, output_file)
141
+ ```