dh-mc commited on
Commit
c73d190
1 Parent(s): 07320d0

ready for gpu cluster

Browse files
llm_toolkit/chat.py DELETED
@@ -1,88 +0,0 @@
1
- import os
2
- import sys
3
- from llamafactory.chat import ChatModel
4
- from llamafactory.extras.misc import torch_gc
5
-
6
- from dotenv import find_dotenv, load_dotenv
7
-
8
- found_dotenv = find_dotenv(".env")
9
-
10
- if len(found_dotenv) == 0:
11
- found_dotenv = find_dotenv(".env.example")
12
- print(f"loading env vars from: {found_dotenv}")
13
- load_dotenv(found_dotenv, override=False)
14
-
15
- path = os.path.dirname(found_dotenv)
16
- print(f"Adding {path} to sys.path")
17
- sys.path.append(path)
18
-
19
- from llm_toolkit.translation_engine import *
20
- from llm_toolkit.translation_utils import *
21
-
22
- model_name = os.getenv("MODEL_NAME")
23
- load_in_4bit = os.getenv("LOAD_IN_4BIT") == "true"
24
- eval_base_model = os.getenv("EVAL_BASE_MODEL") == "true"
25
- eval_fine_tuned = os.getenv("EVAL_FINE_TUNED") == "true"
26
- save_fine_tuned_model = os.getenv("SAVE_FINE_TUNED") == "true"
27
- num_train_epochs = int(os.getenv("NUM_TRAIN_EPOCHS") or 0)
28
- data_path = os.getenv("DATA_PATH")
29
- results_path = os.getenv("RESULTS_PATH")
30
-
31
- max_seq_length = 2048 # Choose any! We auto support RoPE Scaling internally!
32
- dtype = (
33
- None # None for auto detection. Float16 for Tesla T4, V100, Bfloat16 for Ampere+
34
- )
35
-
36
- print(
37
- model_name,
38
- load_in_4bit,
39
- max_seq_length,
40
- num_train_epochs,
41
- dtype,
42
- data_path,
43
- results_path,
44
- eval_base_model,
45
- eval_fine_tuned,
46
- save_fine_tuned_model,
47
- )
48
-
49
- adapter_name_or_path = (
50
- sys.argv[1]
51
- if len(sys.argv) > 1
52
- else "llama-factory/saves/qwen2-0.5b/lora/sft/checkpoint-560"
53
- )
54
-
55
- args = dict(
56
- model_name_or_path=model_name, # use bnb-4bit-quantized Llama-3-8B-Instruct model
57
- adapter_name_or_path=adapter_name_or_path, # load the saved LoRA adapters
58
- template="chatml", # same to the one in training
59
- finetuning_type="lora", # same to the one in training
60
- quantization_bit=4, # load 4-bit quantized model
61
- )
62
- chat_model = ChatModel(args)
63
-
64
- messages = []
65
- print(
66
- "Welcome to the CLI application, use `clear` to remove the history, use `exit` to exit the application."
67
- )
68
- while True:
69
- query = input("\nUser: ")
70
- if query.strip() == "exit":
71
- break
72
- if query.strip() == "clear":
73
- messages = []
74
- torch_gc()
75
- print("History has been removed.")
76
- continue
77
-
78
- messages.append({"role": "user", "content": query})
79
- print("Assistant: ", end="", flush=True)
80
-
81
- response = ""
82
- for new_text in chat_model.stream_chat(messages):
83
- print(new_text, end="", flush=True)
84
- response += new_text
85
- print()
86
- messages.append({"role": "assistant", "content": response})
87
-
88
- torch_gc()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
llm_toolkit/eval.py CHANGED
@@ -17,6 +17,9 @@ sys.path.append(path)
17
  from llm_toolkit.llm_utils import *
18
  from llm_toolkit.translation_utils import *
19
 
 
 
 
20
  model_name = os.getenv("MODEL_NAME")
21
  adapter_name_or_path = os.getenv("ADAPTER_NAME_OR_PATH")
22
  load_in_4bit = os.getenv("LOAD_IN_4BIT") == "true"
@@ -25,21 +28,26 @@ results_path = os.getenv("RESULTS_PATH")
25
 
26
  print(model_name, adapter_name_or_path, load_in_4bit, data_path, results_path)
27
 
28
- gpu_stats = torch.cuda.get_device_properties(0)
29
- start_gpu_memory = round(torch.cuda.max_memory_reserved() / 1024 / 1024 / 1024, 3)
30
- max_memory = round(gpu_stats.total_memory / 1024 / 1024 / 1024, 3)
31
- print(f"(1) GPU = {gpu_stats.name}. Max memory = {max_memory} GB.")
32
- print(f"{start_gpu_memory} GB of memory reserved.")
 
 
 
 
33
 
34
  model, tokenizer = load_model(
35
  model_name, load_in_4bit=load_in_4bit, adapter_name_or_path=adapter_name_or_path
36
  )
37
 
38
- gpu_stats = torch.cuda.get_device_properties(0)
39
- start_gpu_memory = round(torch.cuda.max_memory_reserved() / 1024 / 1024 / 1024, 3)
40
- max_memory = round(gpu_stats.total_memory / 1024 / 1024 / 1024, 3)
41
- print(f"(2) GPU = {gpu_stats.name}. Max memory = {max_memory} GB.")
42
- print(f"{start_gpu_memory} GB of memory reserved.")
 
43
 
44
  datasets = load_translation_dataset(data_path, tokenizer)
45
 
@@ -51,25 +59,37 @@ if len(sys.argv) > 1:
51
 
52
  print_row_details(datasets["test"].to_pandas(), indices=[0, -1])
53
 
54
- print("Evaluating model: " + model_name)
55
- predictions = eval_model(model, tokenizer, datasets["test"])
56
 
57
- gpu_stats = torch.cuda.get_device_properties(0)
58
- start_gpu_memory = round(torch.cuda.max_memory_reserved() / 1024 / 1024 / 1024, 3)
59
- max_memory = round(gpu_stats.total_memory / 1024 / 1024 / 1024, 3)
60
- print(f"(3) GPU = {gpu_stats.name}. Max memory = {max_memory} GB.")
61
- print(f"{start_gpu_memory} GB of memory reserved.")
 
 
 
 
 
 
62
 
63
  if adapter_name_or_path is not None:
64
- model_name += "_" + adapter_name_or_path.split("/")[-1]
65
 
66
- save_results(
 
 
67
  model_name,
68
- results_path,
69
  datasets["test"],
70
- predictions,
71
- debug=True,
 
 
 
72
  )
73
 
74
- metrics = calc_metrics(datasets["test"]["english"], predictions, debug=True)
75
- print(metrics)
 
 
 
 
 
17
  from llm_toolkit.llm_utils import *
18
  from llm_toolkit.translation_utils import *
19
 
20
+ device = check_gpu()
21
+ is_cuda = torch.cuda.is_available()
22
+
23
  model_name = os.getenv("MODEL_NAME")
24
  adapter_name_or_path = os.getenv("ADAPTER_NAME_OR_PATH")
25
  load_in_4bit = os.getenv("LOAD_IN_4BIT") == "true"
 
28
 
29
  print(model_name, adapter_name_or_path, load_in_4bit, data_path, results_path)
30
 
31
+ if is_cuda:
32
+ torch.cuda.empty_cache()
33
+ gpu_stats = torch.cuda.get_device_properties(0)
34
+ start_gpu_memory = round(torch.cuda.max_memory_reserved() / 1024 / 1024 / 1024, 3)
35
+ max_memory = round(gpu_stats.total_memory / 1024 / 1024 / 1024, 3)
36
+ print(f"(0) GPU = {gpu_stats.name}. Max memory = {max_memory} GB.")
37
+ print(f"{start_gpu_memory} GB of memory reserved.")
38
+
39
+ torch.cuda.empty_cache()
40
 
41
  model, tokenizer = load_model(
42
  model_name, load_in_4bit=load_in_4bit, adapter_name_or_path=adapter_name_or_path
43
  )
44
 
45
+ if is_cuda:
46
+ gpu_stats = torch.cuda.get_device_properties(0)
47
+ start_gpu_memory = round(torch.cuda.max_memory_reserved() / 1024 / 1024 / 1024, 3)
48
+ max_memory = round(gpu_stats.total_memory / 1024 / 1024 / 1024, 3)
49
+ print(f"(2) GPU = {gpu_stats.name}. Max memory = {max_memory} GB.")
50
+ print(f"{start_gpu_memory} GB of memory reserved.")
51
 
52
  datasets = load_translation_dataset(data_path, tokenizer)
53
 
 
59
 
60
  print_row_details(datasets["test"].to_pandas(), indices=[0, -1])
61
 
 
 
62
 
63
+ def on_repetition_penalty_step_completed(model_name, predictions):
64
+ save_results(
65
+ model_name,
66
+ results_path,
67
+ datasets["test"],
68
+ predictions,
69
+ )
70
+
71
+ metrics = calc_metrics(datasets["test"]["english"], predictions, debug=True)
72
+ print(f"{model_name} metrics: {metrics}")
73
+
74
 
75
  if adapter_name_or_path is not None:
76
+ model_name += "/" + adapter_name_or_path.split("/")[-1]
77
 
78
+ evaluate_model_with_repetition_penalty(
79
+ model,
80
+ tokenizer,
81
  model_name,
 
82
  datasets["test"],
83
+ on_repetition_penalty_step_completed,
84
+ start_repetition_penalty=1.0,
85
+ end_repetition_penalty=1.3,
86
+ step_repetition_penalty=0.02,
87
+ device=device,
88
  )
89
 
90
+ if is_cuda:
91
+ gpu_stats = torch.cuda.get_device_properties(0)
92
+ start_gpu_memory = round(torch.cuda.max_memory_reserved() / 1024 / 1024 / 1024, 3)
93
+ max_memory = round(gpu_stats.total_memory / 1024 / 1024 / 1024, 3)
94
+ print(f"(3) GPU = {gpu_stats.name}. Max memory = {max_memory} GB.")
95
+ print(f"{start_gpu_memory} GB of memory reserved.")
llm_toolkit/eval_lf.py DELETED
@@ -1,110 +0,0 @@
1
- import os
2
- import sys
3
- import torch
4
- from dotenv import find_dotenv, load_dotenv
5
- from llamafactory.chat import ChatModel
6
- from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
7
-
8
- found_dotenv = find_dotenv(".env")
9
-
10
- if len(found_dotenv) == 0:
11
- found_dotenv = find_dotenv(".env.example")
12
- print(f"loading env vars from: {found_dotenv}")
13
- load_dotenv(found_dotenv, override=False)
14
-
15
- path = os.path.dirname(found_dotenv)
16
- print(f"Adding {path} to sys.path")
17
- sys.path.append(path)
18
-
19
- from llm_toolkit.translation_utils import *
20
-
21
- model_name = os.getenv("MODEL_NAME")
22
- adapter_name_or_path = os.getenv("ADAPTER_NAME_OR_PATH")
23
- load_in_4bit = os.getenv("LOAD_IN_4BIT") == "true"
24
- data_path = os.getenv("DATA_PATH")
25
- results_path = os.getenv("RESULTS_PATH")
26
-
27
- print(model_name, adapter_name_or_path, load_in_4bit, data_path, results_path)
28
-
29
-
30
- def load_model(
31
- model_name,
32
- max_seq_length=2048,
33
- dtype=torch.bfloat16,
34
- load_in_4bit=False,
35
- adapter_name_or_path=None,
36
- ):
37
- print(f"loading model: {model_name}")
38
-
39
- if adapter_name_or_path:
40
- template = "llama3" if "llama-3" in model_name.lower() else "chatml"
41
-
42
- args = dict(
43
- model_name_or_path=model_name,
44
- adapter_name_or_path=adapter_name_or_path, # load the saved LoRA adapters
45
- template=template, # same to the one in training
46
- finetuning_type="lora", # same to the one in training
47
- quantization_bit=4 if load_in_4bit else None, # load 4-bit quantized model
48
- )
49
- chat_model = ChatModel(args)
50
- return chat_model.engine.model, chat_model.engine.tokenizer
51
-
52
- tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
53
- bnb_config = BitsAndBytesConfig(
54
- load_in_4bit=load_in_4bit,
55
- bnb_4bit_quant_type="nf4",
56
- bnb_4bit_use_double_quant=False,
57
- bnb_4bit_compute_dtype=dtype,
58
- )
59
-
60
- model = AutoModelForCausalLM.from_pretrained(
61
- model_name,
62
- quantization_config=bnb_config,
63
- torch_dtype=dtype,
64
- trust_remote_code=True,
65
- device_map="auto",
66
- )
67
-
68
- return model, tokenizer
69
-
70
-
71
- gpu_stats = torch.cuda.get_device_properties(0)
72
- start_gpu_memory = round(torch.cuda.max_memory_reserved() / 1024 / 1024 / 1024, 3)
73
- max_memory = round(gpu_stats.total_memory / 1024 / 1024 / 1024, 3)
74
- print(f"(1) GPU = {gpu_stats.name}. Max memory = {max_memory} GB.")
75
- print(f"{start_gpu_memory} GB of memory reserved.")
76
-
77
- model, tokenizer = load_model(
78
- model_name, load_in_4bit=load_in_4bit, adapter_name_or_path=adapter_name_or_path
79
- )
80
-
81
- gpu_stats = torch.cuda.get_device_properties(0)
82
- start_gpu_memory = round(torch.cuda.max_memory_reserved() / 1024 / 1024 / 1024, 3)
83
- max_memory = round(gpu_stats.total_memory / 1024 / 1024 / 1024, 3)
84
- print(f"(2) GPU = {gpu_stats.name}. Max memory = {max_memory} GB.")
85
- print(f"{start_gpu_memory} GB of memory reserved.")
86
-
87
- datasets = load_translation_dataset(data_path, tokenizer)
88
-
89
- print("Evaluating model: " + model_name)
90
- predictions = eval_model(model, tokenizer, datasets["test"])
91
-
92
- gpu_stats = torch.cuda.get_device_properties(0)
93
- start_gpu_memory = round(torch.cuda.max_memory_reserved() / 1024 / 1024 / 1024, 3)
94
- max_memory = round(gpu_stats.total_memory / 1024 / 1024 / 1024, 3)
95
- print(f"(3) GPU = {gpu_stats.name}. Max memory = {max_memory} GB.")
96
- print(f"{start_gpu_memory} GB of memory reserved.")
97
-
98
- if adapter_name_or_path is not None:
99
- model_name += "_" + adapter_name_or_path.split("/")[-1]
100
-
101
- save_results(
102
- model_name,
103
- results_path,
104
- datasets["test"],
105
- predictions,
106
- debug=True,
107
- )
108
-
109
- metrics = calc_metrics(datasets["test"]["english"], predictions, debug=True)
110
- print(metrics)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
llm_toolkit/llm_utils.py CHANGED
@@ -1,5 +1,6 @@
1
  import os
2
  import re
 
3
  import torch
4
  from transformers import (
5
  AutoModelForCausalLM,
@@ -197,6 +198,46 @@ def eval_model(
197
  return predictions
198
 
199
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
200
  def save_model(
201
  model,
202
  tokenizer,
 
1
  import os
2
  import re
3
+ import numpy as np
4
  import torch
5
  from transformers import (
6
  AutoModelForCausalLM,
 
198
  return predictions
199
 
200
 
201
+ def evaluate_model_with_repetition_penalty(
202
+ model,
203
+ tokenizer,
204
+ model_name,
205
+ dataset,
206
+ on_repetition_penalty_step_completed,
207
+ start_repetition_penalty=1.0,
208
+ end_repetition_penalty=1.3,
209
+ step_repetition_penalty=0.02,
210
+ device="cuda",
211
+ ):
212
+ print(f"Evaluating model: {model_name} on {device}")
213
+
214
+ for repetition_penalty in np.arange(
215
+ start_repetition_penalty,
216
+ end_repetition_penalty + step_repetition_penalty / 2,
217
+ step_repetition_penalty,
218
+ ):
219
+ # round to 2 decimal places
220
+ repetition_penalty = round(repetition_penalty, 2)
221
+ print(f"*** Evaluating with repetition_penalty: {repetition_penalty}")
222
+ predictions = eval_model(
223
+ model,
224
+ tokenizer,
225
+ dataset,
226
+ device=device,
227
+ repetition_penalty=repetition_penalty,
228
+ )
229
+
230
+ model_name_with_rp = f"{model_name}/rpp-{repetition_penalty:.2f}"
231
+
232
+ try:
233
+ on_repetition_penalty_step_completed(
234
+ model_name_with_rp,
235
+ predictions,
236
+ )
237
+ except Exception as e:
238
+ print(e)
239
+
240
+
241
  def save_model(
242
  model,
243
  tokenizer,
llm_toolkit/translation_engine.py DELETED
@@ -1,130 +0,0 @@
1
- import os
2
- import pandas as pd
3
- import torch
4
- from unsloth import FastLanguageModel, is_bfloat16_supported
5
- from trl import SFTTrainer
6
- from transformers import TrainingArguments, TextStreamer
7
- from llm_toolkit.translation_utils import *
8
- from llamafactory.chat import ChatModel
9
-
10
- print(f"loading {__file__}")
11
-
12
-
13
- def get_model_names(
14
- model_name, save_method="merged_4bit_forced", quantization_method="q5_k_m"
15
- ):
16
- hub_model = model_name.split("/")[-1] + "-MAC-"
17
- local_model = "models/" + hub_model
18
-
19
- return {
20
- "local": local_model + save_method,
21
- "local-gguf": local_model + quantization_method,
22
- "hub": hub_model + save_method,
23
- "hub-gguf": hub_model + "gguf-" + quantization_method,
24
- }
25
-
26
-
27
- def load_model(
28
- model_name,
29
- max_seq_length=2048,
30
- dtype=None,
31
- load_in_4bit=False,
32
- template="chatml",
33
- adapter_name_or_path=None,
34
- ):
35
- print(f"loading model: {model_name}")
36
-
37
- if adapter_name_or_path:
38
- args = dict(
39
- model_name_or_path=model_name,
40
- adapter_name_or_path=adapter_name_or_path, # load the saved LoRA adapters
41
- template=template, # same to the one in training
42
- finetuning_type="lora", # same to the one in training
43
- quantization_bit=4, # load 4-bit quantized model
44
- )
45
- chat_model = ChatModel(args)
46
- return chat_model.engine.model, chat_model.engine.tokenizer
47
-
48
- model, tokenizer = FastLanguageModel.from_pretrained(
49
- model_name=model_name, # YOUR MODEL YOU USED FOR TRAINING
50
- max_seq_length=max_seq_length,
51
- dtype=dtype,
52
- load_in_4bit=load_in_4bit,
53
- trust_remote_code=True,
54
- )
55
- FastLanguageModel.for_inference(model)
56
-
57
- return model, tokenizer
58
-
59
-
60
- def test_model(model, tokenizer, prompt):
61
- inputs = tokenizer(
62
- [prompt],
63
- return_tensors="pt",
64
- ).to("cuda")
65
-
66
- text_streamer = TextStreamer(tokenizer)
67
-
68
- _ = model.generate(
69
- **inputs, max_new_tokens=128, streamer=text_streamer, use_cache=True
70
- )
71
-
72
-
73
- def load_trainer(
74
- model,
75
- tokenizer,
76
- dataset,
77
- num_train_epochs,
78
- max_seq_length=2048,
79
- fp16=False,
80
- bf16=False,
81
- output_dir="./outputs",
82
- ):
83
- model = FastLanguageModel.get_peft_model(
84
- model,
85
- r=16, # Choose any number > 0 ! Suggested 8, 16, 32, 64, 128
86
- target_modules=[
87
- "q_proj",
88
- "k_proj",
89
- "v_proj",
90
- "o_proj",
91
- "gate_proj",
92
- "up_proj",
93
- "down_proj",
94
- ],
95
- lora_alpha=16,
96
- lora_dropout=0, # Supports any, but = 0 is optimized
97
- bias="none", # Supports any, but = "none" is optimized
98
- # [NEW] "unsloth" uses 30% less VRAM, fits 2x larger batch sizes!
99
- use_gradient_checkpointing="unsloth", # True or "unsloth" for very long context
100
- random_state=3407,
101
- use_rslora=False, # We support rank stabilized LoRA
102
- loftq_config=None, # And LoftQ
103
- )
104
-
105
- trainer = SFTTrainer(
106
- model=model,
107
- tokenizer=tokenizer,
108
- train_dataset=dataset,
109
- dataset_text_field="text",
110
- max_seq_length=max_seq_length,
111
- dataset_num_proc=2,
112
- packing=False, # Can make training 5x faster for short sequences.
113
- args=TrainingArguments(
114
- per_device_train_batch_size=2,
115
- gradient_accumulation_steps=4,
116
- warmup_steps=5,
117
- num_train_epochs=num_train_epochs,
118
- learning_rate=2e-4,
119
- fp16=not is_bfloat16_supported(),
120
- bf16=is_bfloat16_supported(),
121
- logging_steps=100,
122
- optim="adamw_8bit",
123
- weight_decay=0.01,
124
- lr_scheduler_type="linear",
125
- seed=3407,
126
- output_dir=output_dir,
127
- ),
128
- )
129
-
130
- return trainer
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
llm_toolkit/translation_utils.py CHANGED
@@ -159,14 +159,14 @@ def load_translation_dataset(data_path, tokenizer=None):
159
  return datasets
160
 
161
 
162
- def eval_model(model, tokenizer, eval_dataset):
163
  total = len(eval_dataset)
164
  predictions = []
165
  for i in tqdm(range(total)):
166
  inputs = tokenizer(
167
  eval_dataset["prompt"][i : i + 1],
168
  return_tensors="pt",
169
- ).to("cuda")
170
 
171
  outputs = model.generate(**inputs, max_new_tokens=4096, use_cache=False)
172
  decoded_output = tokenizer.batch_decode(outputs)
 
159
  return datasets
160
 
161
 
162
+ def eval_model(model, tokenizer, eval_dataset, device="cuda"):
163
  total = len(eval_dataset)
164
  predictions = []
165
  for i in tqdm(range(total)):
166
  inputs = tokenizer(
167
  eval_dataset["prompt"][i : i + 1],
168
  return_tensors="pt",
169
+ ).to(device)
170
 
171
  outputs = model.generate(**inputs, max_new_tokens=4096, use_cache=False)
172
  decoded_output = tokenizer.batch_decode(outputs)
llm_toolkit/tune.py DELETED
@@ -1,143 +0,0 @@
1
- import os
2
- import sys
3
- import torch
4
- from dotenv import find_dotenv, load_dotenv
5
-
6
- found_dotenv = find_dotenv(".env")
7
-
8
- if len(found_dotenv) == 0:
9
- found_dotenv = find_dotenv(".env.example")
10
- print(f"loading env vars from: {found_dotenv}")
11
- load_dotenv(found_dotenv, override=False)
12
-
13
- path = os.path.dirname(found_dotenv)
14
- print(f"Adding {path} to sys.path")
15
- sys.path.append(path)
16
-
17
- from llm_toolkit.translation_engine import *
18
- from llm_toolkit.translation_utils import *
19
-
20
-
21
- model_name = os.getenv("MODEL_NAME")
22
- load_in_4bit = os.getenv("LOAD_IN_4BIT") == "true"
23
- eval_base_model = os.getenv("EVAL_BASE_MODEL") == "true"
24
- eval_fine_tuned = os.getenv("EVAL_FINE_TUNED") == "true"
25
- save_fine_tuned_model = os.getenv("SAVE_FINE_TUNED") == "true"
26
- num_train_epochs = int(os.getenv("NUM_TRAIN_EPOCHS") or 0)
27
- data_path = os.getenv("DATA_PATH")
28
- results_path = os.getenv("RESULTS_PATH")
29
-
30
- max_seq_length = 2048 # Choose any! We auto support RoPE Scaling internally!
31
- dtype = (
32
- None # None for auto detection. Float16 for Tesla T4, V100, Bfloat16 for Ampere+
33
- )
34
-
35
- print(
36
- model_name,
37
- load_in_4bit,
38
- max_seq_length,
39
- num_train_epochs,
40
- dtype,
41
- data_path,
42
- results_path,
43
- eval_base_model,
44
- eval_fine_tuned,
45
- save_fine_tuned_model,
46
- )
47
-
48
- gpu_stats = torch.cuda.get_device_properties(0)
49
- start_gpu_memory = round(torch.cuda.max_memory_reserved() / 1024 / 1024 / 1024, 3)
50
- max_memory = round(gpu_stats.total_memory / 1024 / 1024 / 1024, 3)
51
- print(f"(1) GPU = {gpu_stats.name}. Max memory = {max_memory} GB.")
52
- print(f"{start_gpu_memory} GB of memory reserved.")
53
-
54
- model, tokenizer = load_model(model_name, load_in_4bit=load_in_4bit)
55
-
56
- gpu_stats = torch.cuda.get_device_properties(0)
57
- start_gpu_memory = round(torch.cuda.max_memory_reserved() / 1024 / 1024 / 1024, 3)
58
- max_memory = round(gpu_stats.total_memory / 1024 / 1024 / 1024, 3)
59
- print(f"(2) GPU = {gpu_stats.name}. Max memory = {max_memory} GB.")
60
- print(f"{start_gpu_memory} GB of memory reserved.")
61
-
62
- datasets = load_translation_dataset(data_path, tokenizer)
63
-
64
- if eval_base_model:
65
- print("Evaluating base model: " + model_name)
66
- predictions = eval_model(model, tokenizer, datasets["test"])
67
-
68
- # calc_metrics(datasets["test"]["english"], predictions, debug=True)
69
-
70
- save_results(
71
- model_name,
72
- results_path,
73
- datasets["test"],
74
- predictions,
75
- debug=True,
76
- )
77
-
78
- gpu_stats = torch.cuda.get_device_properties(0)
79
- start_gpu_memory = round(torch.cuda.max_memory_reserved() / 1024 / 1024 / 1024, 3)
80
- max_memory = round(gpu_stats.total_memory / 1024 / 1024 / 1024, 3)
81
- print(f"(3) GPU = {gpu_stats.name}. Max memory = {max_memory} GB.")
82
- print(f"{start_gpu_memory} GB of memory reserved.")
83
-
84
-
85
- def is_bfloat16_supported():
86
- return True
87
-
88
-
89
- trainer = load_trainer(
90
- model,
91
- tokenizer,
92
- datasets["train"],
93
- num_train_epochs,
94
- fp16=not is_bfloat16_supported(),
95
- bf16=is_bfloat16_supported(),
96
- )
97
-
98
- gpu_stats = torch.cuda.get_device_properties(0)
99
- start_gpu_memory = round(torch.cuda.max_memory_reserved() / 1024 / 1024 / 1024, 3)
100
- max_memory = round(gpu_stats.total_memory / 1024 / 1024 / 1024, 3)
101
- print(f"(4) GPU = {gpu_stats.name}. Max memory = {max_memory} GB.")
102
- print(f"{start_gpu_memory} GB of memory reserved.")
103
-
104
- trainer_stats = trainer.train()
105
-
106
- # @title Show final memory and time stats
107
- used_memory = round(torch.cuda.max_memory_reserved() / 1024 / 1024 / 1024, 3)
108
- used_memory_for_lora = round(used_memory - start_gpu_memory, 3)
109
- used_percentage = round(used_memory / max_memory * 100, 3)
110
- lora_percentage = round(used_memory_for_lora / max_memory * 100, 3)
111
- print(f"(5) GPU = {gpu_stats.name}. Max memory = {max_memory} GB.")
112
- print(f"{trainer_stats.metrics['train_runtime']} seconds used for training.")
113
- print(
114
- f"{round(trainer_stats.metrics['train_runtime']/60, 2)} minutes used for training."
115
- )
116
- print(f"Peak reserved memory = {used_memory} GB.")
117
- print(f"Peak reserved memory for training = {used_memory_for_lora} GB.")
118
- print(f"Peak reserved memory % of max memory = {used_percentage} %.")
119
- print(f"Peak reserved memory for training % of max memory = {lora_percentage} %.")
120
-
121
- if eval_fine_tuned:
122
- print("Evaluating fine-tuned model: " + model_name)
123
- FastLanguageModel.for_inference(model) # Enable native 2x faster inference
124
- predictions = eval_model(model, tokenizer, datasets["test"])
125
-
126
- # calc_metrics(datasets["test"]["english"], predictions, debug=True)
127
-
128
- save_results(
129
- model_name + "(finetuned)",
130
- results_path,
131
- datasets["test"],
132
- predictions,
133
- debug=True,
134
- )
135
-
136
- gpu_stats = torch.cuda.get_device_properties(0)
137
- start_gpu_memory = round(torch.cuda.max_memory_reserved() / 1024 / 1024 / 1024, 3)
138
- max_memory = round(gpu_stats.total_memory / 1024 / 1024 / 1024, 3)
139
- print(f"(6) GPU = {gpu_stats.name}. Max memory = {max_memory} GB.")
140
- print(f"{start_gpu_memory} GB of memory reserved.")
141
-
142
- if save_fine_tuned_model:
143
- save_model(model, tokenizer)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
notebooks/00_Data_Analysis.ipynb DELETED
The diff for this file is too large to render. See raw diff
 
notebooks/01_Qwen2-0.5B_Unsloth.ipynb DELETED
The diff for this file is too large to render. See raw diff
 
notebooks/02_Qwen2-1.5B_Unsloth.ipynb DELETED
The diff for this file is too large to render. See raw diff
 
notebooks/03_Qwen2-0.5B_1.5B-4bit.ipynb DELETED
The diff for this file is too large to render. See raw diff
 
notebooks/04_tune-small-no-flash-attn.ipynb DELETED
The diff for this file is too large to render. See raw diff
 
notebooks/05_tune-small-with-flash-attn.ipynb DELETED
The diff for this file is too large to render. See raw diff
 
notebooks/06_tune-small-py3.11.ipynb DELETED
The diff for this file is too large to render. See raw diff
 
notebooks/07_tune-lf-py3.11.ipynb DELETED
The diff for this file is too large to render. See raw diff
 
notebooks/07r2_tune-lf-py3.11.ipynb DELETED
The diff for this file is too large to render. See raw diff
 
notebooks/08_eval-lf-py3.11.ipynb DELETED
The diff for this file is too large to render. See raw diff
 
results/experiment-1-results.csv DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:bfb0c7a3813e9c98c9245c9303b2fb95c1fd7d6a92dd4e0d9d3fe4e4d29a8849
3
- size 2072299
 
 
 
 
results/experiment-2-results.csv DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:b1c99b9bb0c6539a9ff3c9198d730f110c5b6371cba803e1992802beb13e3600
3
- size 2038783
 
 
 
 
results/experiment-3-results.csv DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:f0b8dcb783ed847422ca4f2000b5106742b992537f4b84da6b5ca0b4c22bf0dd
3
- size 1427300
 
 
 
 
results/mac-results-no-flash-attn.csv DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:89144b0a3e727b326be559637312e353208a7e506b7c0c701ce8e4392e4cbb5e
3
- size 2129451
 
 
 
 
results/mac-results-with-flash-attn.csv DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:4c73be2c390511d0a59090b57c53f0a66c0d4c4648c209ef7155aa97ff73c0b9
3
- size 1461478
 
 
 
 
results/mac-results.csv DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:7eb1c66dd7162f27a969599ddb3695c3ac82a88bff15cd57d7ed00ca86ab19cd
3
- size 2072299
 
 
 
 
results/mac-results_final.csv DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:aacf61087ae3b1fd622407c75d0a969b232517c7489841da722e0228bb69a310
3
- size 2334006
 
 
 
 
results/mac-results_lf-r2.csv DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:25c14d76c8d71ecbce6bc83d641ec4f54f6c0e188fccfcfd8536758a12ed456a
3
- size 2442353
 
 
 
 
results/mac-results_lf-r3.csv DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:0ea9402ad5c87e3b7dcb570cf0a3c0bf33bef093c522d4d2ba6dbf633e21f035
3
- size 531603
 
 
 
 
results/mac-results_lf.csv DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:c5acc087808de5df6839cbf7b170094c6e63445aab4bea15e4be9564b905eb51
3
- size 3236072
 
 
 
 
results/mac-results_py3.11.csv DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:4adb0922c02cc435858b4ba44b4cdaaee4afe6fcc8721a795d740c36d8d94c2c
3
- size 1463058
 
 
 
 
results/mac-results_v3.csv DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:8bfe9ce9720d0cf67ba118d8b2d82f8f6c0bd0f763a8aa00fc1f43f58e544157
3
- size 1683953
 
 
 
 
results/model_training_evaluation_times.csv DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:5691ccd7fafb765772c2e5da0ada82bd2f3532459dcfed8517565e7cc0d9f1a8
3
- size 441
 
 
 
 
scripts/eval-mac.sh CHANGED
@@ -11,9 +11,14 @@ cat /etc/os-release
11
  lscpu
12
  grep MemTotal /proc/meminfo
13
 
14
- export EVAL_BASE_MODEL=true
15
- export DO_FINE_TUNING=false
16
 
17
- export MODEL_NAME=$1
18
- echo Evaluating $MODEL_NAME
19
- python llm_toolkit/tune_mac.py
 
 
 
 
 
 
 
11
  lscpu
12
  grep MemTotal /proc/meminfo
13
 
14
+ ./scripts/eval-model.sh Qwen/Qwen2-7B-Instruct
 
15
 
16
+ ./scripts/eval-model.sh internlm/internlm2_5-7b-chat-1m
17
+
18
+ ./scripts/eval-model.sh THUDM/glm-4-9b-chat-1m
19
+
20
+ ./scripts/eval-model.sh shenzhi-wang/Llama3.1-8B-Chinese-Chat
21
+
22
+ ./scripts/eval-model.sh shenzhi-wang/Gemma-2-9B-Chinese-Chat
23
+
24
+ ./scripts/eval-model.sh shenzhi-wang/Mistral-7B-v0.3-Chinese-Chat
scripts/eval-model.sh ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/sh
2
+
3
+ BASEDIR=$(dirname "$0")
4
+ cd $BASEDIR/..
5
+ echo Current Directory:
6
+ pwd
7
+
8
+ export MODEL_NAME=$1
9
+ echo Evaluating $MODEL_NAME
10
+ python llm_toolkit/eval.py