dh-mc commited on
Commit
0156aec
·
1 Parent(s): 6b279ca

ready for few shots prompting 4gpu

Browse files
llm_toolkit/eval_rpp.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.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"
26
+ data_path = os.getenv("DATA_PATH")
27
+ results_path = os.getenv("RESULTS_PATH")
28
+ batch_size = int(os.getenv("BATCH_SIZE", 1))
29
+ use_english_datasets = os.getenv("USE_ENGLISH_DATASETS") == "true"
30
+ max_new_tokens = int(os.getenv("MAX_NEW_TOKENS", 2048))
31
+ start_repetition_penalty = float(os.getenv("START_REPETITION_PENALTY", 1.0))
32
+
33
+ print(
34
+ model_name,
35
+ adapter_name_or_path,
36
+ load_in_4bit,
37
+ data_path,
38
+ results_path,
39
+ use_english_datasets,
40
+ max_new_tokens,
41
+ batch_size,
42
+ )
43
+
44
+ if is_cuda:
45
+ torch.cuda.empty_cache()
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"(0) GPU = {gpu_stats.name}. Max memory = {max_memory} GB.")
50
+ print(f"{start_gpu_memory} GB of memory reserved.")
51
+
52
+ torch.cuda.empty_cache()
53
+
54
+ model, tokenizer = load_model(
55
+ model_name, load_in_4bit=load_in_4bit, adapter_name_or_path=adapter_name_or_path
56
+ )
57
+
58
+ if is_cuda:
59
+ gpu_stats = torch.cuda.get_device_properties(0)
60
+ start_gpu_memory = round(torch.cuda.max_memory_reserved() / 1024 / 1024 / 1024, 3)
61
+ max_memory = round(gpu_stats.total_memory / 1024 / 1024 / 1024, 3)
62
+ print(f"(2) GPU = {gpu_stats.name}. Max memory = {max_memory} GB.")
63
+ print(f"{start_gpu_memory} GB of memory reserved.")
64
+
65
+ datasets = load_translation_dataset(data_path, tokenizer)
66
+
67
+ if len(sys.argv) > 1:
68
+ num = int(sys.argv[1])
69
+ if num > 0:
70
+ print(f"--- evaluating {num} entries")
71
+ datasets["test"] = datasets["test"].select(range(num))
72
+
73
+ print_row_details(datasets["test"].to_pandas(), indices=[0, -1])
74
+
75
+
76
+ def on_repetition_penalty_step_completed(model_name, predictions):
77
+ save_results(
78
+ model_name,
79
+ results_path,
80
+ datasets["test"],
81
+ predictions,
82
+ )
83
+
84
+ metrics = calc_metrics(datasets["test"]["english"], predictions, debug=True)
85
+ print(f"{model_name} metrics: {metrics}")
86
+
87
+
88
+ if adapter_name_or_path is not None:
89
+ model_name += "/" + adapter_name_or_path.split("/")[-1]
90
+
91
+ evaluate_model_with_repetition_penalty(
92
+ model,
93
+ tokenizer,
94
+ model_name,
95
+ datasets["test"],
96
+ on_repetition_penalty_step_completed,
97
+ start_repetition_penalty=start_repetition_penalty,
98
+ end_repetition_penalty=1.3,
99
+ step_repetition_penalty=0.02,
100
+ batch_size=batch_size,
101
+ max_new_tokens=max_new_tokens,
102
+ device=device,
103
+ )
104
+
105
+ if is_cuda:
106
+ gpu_stats = torch.cuda.get_device_properties(0)
107
+ start_gpu_memory = round(torch.cuda.max_memory_reserved() / 1024 / 1024 / 1024, 3)
108
+ max_memory = round(gpu_stats.total_memory / 1024 / 1024 / 1024, 3)
109
+ print(f"(3) GPU = {gpu_stats.name}. Max memory = {max_memory} GB.")
110
+ print(f"{start_gpu_memory} GB of memory reserved.")
llm_toolkit/translation_utils.py CHANGED
@@ -207,11 +207,15 @@ def detect_repetition_scores(row, col, debug=False):
207
  )
208
 
209
 
210
- def get_metrics(df, max_output_tokens=2048):
211
  metrics_df = pd.DataFrame(df.columns.T)[2:]
212
  metrics_df.rename(columns={0: "model"}, inplace=True)
213
- metrics_df["rpp"] = metrics_df["model"].apply(lambda x: x.split("rpp-")[-1])
214
- metrics_df["model"] = metrics_df["model"].apply(lambda x: x.split("/rpp-")[0])
 
 
 
 
215
  metrics_df.reset_index(inplace=True)
216
  metrics_df = metrics_df.drop(columns=["index"])
217
 
@@ -251,7 +255,7 @@ def get_metrics(df, max_output_tokens=2048):
251
  repetition_score.append(df["repetition_score"].mean())
252
  total_repetitions.append(df["total_repetitions"].mean())
253
 
254
- model = col.split("/rpp")[0]
255
 
256
  new_col = f"ground_truth_tokens-{model}"
257
  df[new_col] = df["english"].apply(
 
207
  )
208
 
209
 
210
+ def get_metrics(df, max_output_tokens=2048, variant="rpp"):
211
  metrics_df = pd.DataFrame(df.columns.T)[2:]
212
  metrics_df.rename(columns={0: "model"}, inplace=True)
213
+ metrics_df[variant] = metrics_df["model"].apply(
214
+ lambda x: x.split(f"{variant}-")[-1]
215
+ )
216
+ metrics_df["model"] = metrics_df["model"].apply(
217
+ lambda x: x.split(f"/{variant}-")[0]
218
+ )
219
  metrics_df.reset_index(inplace=True)
220
  metrics_df = metrics_df.drop(columns=["index"])
221
 
 
255
  repetition_score.append(df["repetition_score"].mean())
256
  total_repetitions.append(df["total_repetitions"].mean())
257
 
258
+ model = col.split(f"/{variant}")[0]
259
 
260
  new_col = f"ground_truth_tokens-{model}"
261
  df[new_col] = df["english"].apply(
llm_toolkit/translation_utils_v1.py ADDED
@@ -0,0 +1,421 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import re
3
+ import pandas as pd
4
+ import evaluate
5
+ import seaborn as sns
6
+ import matplotlib.pyplot as plt
7
+ from datasets import load_dataset
8
+ from langchain_openai import ChatOpenAI
9
+ from langchain_core.prompts import ChatPromptTemplate
10
+ from tqdm import tqdm
11
+ from eval_modules.calc_repetitions import *
12
+ from llm_toolkit.llm_utils import load_tokenizer
13
+
14
+ print(f"loading {__file__}")
15
+
16
+ bleu = evaluate.load("bleu")
17
+ rouge = evaluate.load("rouge")
18
+ meteor = evaluate.load("meteor")
19
+ accuracy = evaluate.load("accuracy")
20
+
21
+
22
+ def extract_answer(text, debug=False):
23
+ if text:
24
+ # Remove the begin and end tokens
25
+ text = re.sub(
26
+ r".*?(assistant|\[/INST\]).+?\b", "", text, flags=re.DOTALL | re.MULTILINE
27
+ )
28
+ if debug:
29
+ print("--------\nstep 1:", text)
30
+
31
+ text = re.sub(r"<.+?>.*", "", text, flags=re.DOTALL | re.MULTILINE)
32
+ if debug:
33
+ print("--------\nstep 2:", text)
34
+
35
+ text = re.sub(
36
+ r".*?end_header_id\|>\n\n", "", text, flags=re.DOTALL | re.MULTILINE
37
+ )
38
+ if debug:
39
+ print("--------\nstep 3:", text)
40
+
41
+ return text
42
+
43
+
44
+ def calc_metrics(references, predictions, debug=False):
45
+ assert len(references) == len(
46
+ predictions
47
+ ), f"lengths are difference: {len(references)} != {len(predictions)}"
48
+
49
+ predictions = [extract_answer(text) for text in predictions]
50
+ results = {}
51
+
52
+ results["meteor"] = meteor.compute(predictions=predictions, references=references)[
53
+ "meteor"
54
+ ]
55
+
56
+ results["bleu_scores"] = bleu.compute(
57
+ predictions=predictions, references=references, max_order=4
58
+ )
59
+ results["rouge_scores"] = rouge.compute(
60
+ predictions=predictions, references=references
61
+ )
62
+
63
+ correct = [1 if ref == pred else 0 for ref, pred in zip(references, predictions)]
64
+ accuracy = sum(correct) / len(references)
65
+
66
+ results["accuracy"] = accuracy
67
+ if debug:
68
+ correct_ids = [i for i, c in enumerate(correct) if c == 1]
69
+ results["correct_ids"] = correct_ids
70
+
71
+ return results
72
+
73
+
74
+ def save_results(model_name, results_path, dataset, predictions, debug=False):
75
+ if not os.path.exists(results_path):
76
+ # Get the directory part of the file path
77
+ dir_path = os.path.dirname(results_path)
78
+
79
+ # Create all directories in the path (if they don't exist)
80
+ os.makedirs(dir_path, exist_ok=True)
81
+ df = dataset.to_pandas()
82
+ df.drop(columns=["text", "prompt"], inplace=True)
83
+ else:
84
+ df = pd.read_csv(results_path, on_bad_lines="warn")
85
+
86
+ df[model_name] = predictions
87
+
88
+ if debug:
89
+ print(df.head(1))
90
+
91
+ df.to_csv(results_path, index=False)
92
+
93
+
94
+ def load_translation_dataset(data_path, tokenizer=None):
95
+ train_data_file = data_path.replace(".tsv", "-train.tsv")
96
+ test_data_file = data_path.replace(".tsv", "-test.tsv")
97
+
98
+ if not os.path.exists(train_data_file):
99
+ print("generating train/test data files")
100
+ dataset = load_dataset(
101
+ "csv", data_files=data_path, delimiter="\t", split="train"
102
+ )
103
+ print(len(dataset))
104
+ dataset = dataset.filter(lambda x: x["chinese"] and x["english"])
105
+
106
+ datasets = dataset.train_test_split(test_size=0.2)
107
+ print(len(dataset))
108
+
109
+ # Convert to pandas DataFrame
110
+ train_df = pd.DataFrame(datasets["train"])
111
+ test_df = pd.DataFrame(datasets["test"])
112
+
113
+ # Save to TSV
114
+ train_df.to_csv(train_data_file, sep="\t", index=False)
115
+ test_df.to_csv(test_data_file, sep="\t", index=False)
116
+
117
+ print("loading train/test data files")
118
+ datasets = load_dataset(
119
+ "csv",
120
+ data_files={"train": train_data_file, "test": test_data_file},
121
+ delimiter="\t",
122
+ )
123
+
124
+ if tokenizer:
125
+ translation_prompt = "Please translate the following Chinese text into English and provide only the translated content, nothing else.\n{}"
126
+
127
+ def formatting_prompts_func(examples):
128
+ inputs = examples["chinese"]
129
+ outputs = examples["english"]
130
+
131
+ messages = [
132
+ {
133
+ "role": "system",
134
+ "content": "You are an expert in translating Chinese to English.",
135
+ },
136
+ None,
137
+ ]
138
+
139
+ model_name = os.getenv("MODEL_NAME")
140
+
141
+ # if "mistral" in model_name.lower():
142
+ # messages = messages[1:]
143
+
144
+ texts = []
145
+ prompts = []
146
+ for input, output in zip(inputs, outputs):
147
+ prompt = translation_prompt.format(input)
148
+ messages[-1] = {"role": "user", "content": prompt}
149
+
150
+ prompt = tokenizer.apply_chat_template(
151
+ messages, tokenize=False, add_generation_prompt=True
152
+ )
153
+ prompts.append(prompt)
154
+ texts.append(prompt + output + tokenizer.eos_token)
155
+ return {"text": texts, "prompt": prompts}
156
+
157
+ datasets = datasets.map(
158
+ formatting_prompts_func,
159
+ batched=True,
160
+ )
161
+
162
+ print(datasets)
163
+ return datasets
164
+
165
+
166
+ def count_entries_with_max_tokens(entries, max_tokens):
167
+ """
168
+ Count the number of entries with the max output tokens or more.
169
+
170
+ Parameters:
171
+ entries (list of int): List of token counts for each entry.
172
+ max_tokens (int): The maximum token threshold.
173
+
174
+ Returns:
175
+ int: The number of entries with token counts greater than or equal to max_tokens.
176
+ """
177
+ count = 0
178
+ for tokens in entries:
179
+ if tokens >= max_tokens:
180
+ count += 1
181
+ return count
182
+
183
+
184
+ def detect_repetition_scores(row, col, debug=False):
185
+ # print(f"row: {row}")
186
+ newline_score, repetition_score, total_repetitions = detect_repetitions(
187
+ row[col], debug=debug
188
+ )
189
+ newline_score -= row["ground_truth_ews_score"]
190
+ repetition_score -= row["ground_truth_repetition_score"]
191
+ total_repetitions -= row["ground_truth_total_repetitions"]
192
+
193
+ return pd.Series(
194
+ [
195
+ newline_score if newline_score > 0 else 0,
196
+ repetition_score if repetition_score > 0 else 0,
197
+ total_repetitions if total_repetitions > 0 else 0,
198
+ ]
199
+ )
200
+
201
+
202
+ def get_metrics(df, max_output_tokens=2048):
203
+ metrics_df = pd.DataFrame(df.columns.T)[2:]
204
+ metrics_df.rename(columns={0: "model"}, inplace=True)
205
+ metrics_df["rpp"] = metrics_df["model"].apply(lambda x: x.split("rpp-")[-1])
206
+ metrics_df["model"] = metrics_df["model"].apply(lambda x: x.split("/rpp-")[0])
207
+ metrics_df.reset_index(inplace=True)
208
+ metrics_df = metrics_df.drop(columns=["index"])
209
+
210
+ tokenizers = {
211
+ model: load_tokenizer(model) for model in metrics_df["model"].unique()
212
+ }
213
+
214
+ meteor = []
215
+ bleu_1 = []
216
+ rouge_l = []
217
+ ews_score = []
218
+ repetition_score = []
219
+ total_repetitions = []
220
+ num_max_output_tokens = []
221
+ columns = df.columns[2:]
222
+
223
+ df[
224
+ [
225
+ "ground_truth_ews_score",
226
+ "ground_truth_repetition_score",
227
+ "ground_truth_total_repetitions",
228
+ ]
229
+ ] = df["english"].apply(detect_scores)
230
+
231
+ for col in columns:
232
+ metrics = calc_metrics(df["english"], df[col], debug=True)
233
+ print(f"{col}: {metrics}")
234
+
235
+ meteor.append(metrics["meteor"])
236
+ bleu_1.append(metrics["bleu_scores"]["bleu"])
237
+ rouge_l.append(metrics["rouge_scores"]["rougeL"])
238
+
239
+ df[["ews_score", "repetition_score", "total_repetitions"]] = df.apply(
240
+ lambda x: detect_repetition_scores(x, col), axis=1
241
+ )
242
+ ews_score.append(df["ews_score"].mean())
243
+ repetition_score.append(df["repetition_score"].mean())
244
+ total_repetitions.append(df["total_repetitions"].mean())
245
+
246
+ model = col.split("/rpp")[0]
247
+
248
+ new_col = f"ground_truth_tokens-{model}"
249
+ df[new_col] = df["english"].apply(
250
+ lambda x: len(tokenizers[model](x)["input_ids"])
251
+ )
252
+
253
+ new_col = f"output_tokens-{col}"
254
+ df[new_col] = df[col].apply(lambda x: len(tokenizers[model](x)["input_ids"]))
255
+
256
+ num_max_output_tokens.append(
257
+ count_entries_with_max_tokens(df[new_col], max_output_tokens)
258
+ )
259
+
260
+ metrics_df["meteor"] = meteor
261
+ metrics_df["bleu_1"] = bleu_1
262
+ metrics_df["rouge_l"] = rouge_l
263
+ metrics_df["ews_score"] = ews_score
264
+ metrics_df["repetition_score"] = repetition_score
265
+ metrics_df["total_repetitions"] = total_repetitions
266
+ metrics_df["rap"] = metrics_df.apply(
267
+ lambda x: x["meteor"] / math.log10(10 + x["total_repetitions"]), axis=1
268
+ )
269
+
270
+ metrics_df["num_max_output_tokens"] = num_max_output_tokens
271
+
272
+ return metrics_df
273
+
274
+
275
+ def plot_metrics(metrics_df, figsize=(14, 5), ylim=(0, 0.44)):
276
+ plt.figure(figsize=figsize)
277
+ df_melted = pd.melt(
278
+ metrics_df, id_vars="model", value_vars=["meteor", "bleu_1", "rouge_l"]
279
+ )
280
+
281
+ barplot = sns.barplot(x="variable", y="value", hue="model", data=df_melted)
282
+
283
+ # Set different hatches for each model
284
+ hatches = ["/", "\\", "|", "-", "+", "x", "o", "O", ".", "*", "//", "\\\\"]
285
+
286
+ # Create a dictionary to map models to hatches
287
+ model_hatches = {
288
+ model: hatches[i % len(hatches)]
289
+ for i, model in enumerate(metrics_df["model"].unique())
290
+ }
291
+
292
+ # Apply hatches based on the model
293
+ num_vars = len(df_melted["variable"].unique())
294
+ for i, bar in enumerate(barplot.patches):
295
+ model = df_melted["model"].iloc[i // num_vars]
296
+ bar.set_hatch(model_hatches[model])
297
+
298
+ # Manually update legend to match the bar hatches
299
+ handles, labels = barplot.get_legend_handles_labels()
300
+ for handle, model in zip(handles, metrics_df["model"].unique()):
301
+ handle.set_hatch(model_hatches[model])
302
+
303
+ barplot.set_xticklabels(["METEOR", "BLEU-1", "ROUGE-L"])
304
+ for p in barplot.patches:
305
+ if p.get_height() == 0:
306
+ continue
307
+ barplot.annotate(
308
+ f"{p.get_height():.2f}",
309
+ (p.get_x() + p.get_width() / 2.0, p.get_height()),
310
+ ha="center",
311
+ va="center",
312
+ xytext=(0, 10),
313
+ textcoords="offset points",
314
+ )
315
+
316
+ barplot.set(ylim=ylim, ylabel="Scores", xlabel="Metrics")
317
+ plt.legend(bbox_to_anchor=(0.5, -0.1), loc="upper center")
318
+ plt.show()
319
+
320
+
321
+ def plot_times(perf_df, ylim=0.421):
322
+ # Adjusted code to put "train-time" bars in red at the bottom
323
+
324
+ fig, ax1 = plt.subplots(figsize=(12, 10))
325
+
326
+ color_train = "tab:red"
327
+ color_eval = "orange"
328
+ ax1.set_xlabel("Models")
329
+ ax1.set_ylabel("Time (mins)")
330
+ ax1.set_xticks(range(len(perf_df["model"]))) # Set x-ticks positions
331
+ ax1.set_xticklabels(perf_df["model"], rotation=90)
332
+
333
+ # Plot "train-time" first so it's at the bottom
334
+ ax1.bar(
335
+ perf_df["model"],
336
+ perf_df["train-time(mins)"],
337
+ color=color_train,
338
+ label="train-time",
339
+ )
340
+
341
+ # Then, plot "eval-time" on top of "train-time"
342
+ ax1.bar(
343
+ perf_df["model"],
344
+ perf_df["eval-time(mins)"],
345
+ bottom=perf_df["train-time(mins)"],
346
+ color=color_eval,
347
+ label="eval-time",
348
+ )
349
+
350
+ ax1.tick_params(axis="y")
351
+ ax1.legend(loc="upper left")
352
+
353
+ if "meteor" in perf_df.columns:
354
+ ax2 = ax1.twinx()
355
+ color_meteor = "tab:blue"
356
+ ax2.set_ylabel("METEOR", color=color_meteor)
357
+ ax2.plot(
358
+ perf_df["model"],
359
+ perf_df["meteor"],
360
+ color=color_meteor,
361
+ marker="o",
362
+ label="meteor",
363
+ )
364
+ ax2.tick_params(axis="y", labelcolor=color_meteor)
365
+ ax2.legend(loc="upper right")
366
+ ax2.set_ylim(ax2.get_ylim()[0], ylim)
367
+
368
+ # Show numbers in bars
369
+ for p in ax1.patches:
370
+ height = p.get_height()
371
+ if height == 0: # Skip bars with height 0
372
+ continue
373
+ ax1.annotate(
374
+ f"{height:.2f}",
375
+ (p.get_x() + p.get_width() / 2.0, p.get_y() + height),
376
+ ha="center",
377
+ va="center",
378
+ xytext=(0, -10),
379
+ textcoords="offset points",
380
+ )
381
+
382
+ fig.tight_layout()
383
+ plt.show()
384
+
385
+
386
+ def translate_via_llm(text):
387
+ base_url = os.getenv("OPENAI_BASE_URL") or "http://localhost:8000/v1"
388
+ llm = ChatOpenAI(
389
+ model="gpt-4o",
390
+ temperature=0,
391
+ max_tokens=None,
392
+ timeout=None,
393
+ max_retries=2,
394
+ base_url=base_url,
395
+ )
396
+
397
+ prompt = ChatPromptTemplate.from_messages(
398
+ [
399
+ (
400
+ "human",
401
+ "Please translate the following Chinese text into English and provide only the translated content, nothing else.\n{input}",
402
+ ),
403
+ ]
404
+ )
405
+
406
+ chain = prompt | llm
407
+ response = chain.invoke(
408
+ {
409
+ "input": text,
410
+ }
411
+ )
412
+ return response.content
413
+
414
+
415
+ def translate(text, cache_dict):
416
+ if text in cache_dict:
417
+ return cache_dict[text]
418
+ else:
419
+ translated_text = translate_via_llm(text)
420
+ cache_dict[text] = translated_text
421
+ return translated_text
notebooks/00_Data Analysis.ipynb CHANGED
The diff for this file is too large to render. See raw diff
 
notebooks/00b_Data Analysis_Few_Shots.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
notebooks/01_Few-shot_Prompting.ipynb ADDED
@@ -0,0 +1,895 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 1,
6
+ "metadata": {
7
+ "executionInfo": {
8
+ "elapsed": 476,
9
+ "status": "ok",
10
+ "timestamp": 1720679526275,
11
+ "user": {
12
+ "displayName": "HUANG DONGHAO _",
13
+ "userId": "00977795705617022768"
14
+ },
15
+ "user_tz": -480
16
+ },
17
+ "id": "uWKRSV6eZsCn"
18
+ },
19
+ "outputs": [],
20
+ "source": [
21
+ "%load_ext autoreload\n",
22
+ "%autoreload 2"
23
+ ]
24
+ },
25
+ {
26
+ "cell_type": "code",
27
+ "execution_count": 2,
28
+ "metadata": {
29
+ "application/vnd.databricks.v1+cell": {
30
+ "cellMetadata": {
31
+ "byteLimit": 2048000,
32
+ "rowLimit": 10000
33
+ },
34
+ "inputWidgets": {},
35
+ "nuid": "6d394937-6c99-4a7c-9d32-7600a280032f",
36
+ "showTitle": false,
37
+ "title": ""
38
+ },
39
+ "colab": {
40
+ "base_uri": "https://localhost:8080/"
41
+ },
42
+ "executionInfo": {
43
+ "elapsed": 5,
44
+ "status": "ok",
45
+ "timestamp": 1720679529345,
46
+ "user": {
47
+ "displayName": "HUANG DONGHAO _",
48
+ "userId": "00977795705617022768"
49
+ },
50
+ "user_tz": -480
51
+ },
52
+ "id": "G5pNu3zgZBrL",
53
+ "outputId": "160a554f-fb08-4aa0-bc00-0422fb7c1fac"
54
+ },
55
+ "outputs": [
56
+ {
57
+ "name": "stdout",
58
+ "output_type": "stream",
59
+ "text": [
60
+ "workding dir: /Users/inflaton/code/engd/papers/rapget-translation\n"
61
+ ]
62
+ }
63
+ ],
64
+ "source": [
65
+ "import os\n",
66
+ "import sys\n",
67
+ "from pathlib import Path\n",
68
+ "\n",
69
+ "# check if workding_dir is in local variables\n",
70
+ "if \"workding_dir\" not in locals():\n",
71
+ " workding_dir = str(Path.cwd().parent)\n",
72
+ "\n",
73
+ "os.chdir(workding_dir)\n",
74
+ "sys.path.append(workding_dir)\n",
75
+ "print(\"workding dir:\", workding_dir)"
76
+ ]
77
+ },
78
+ {
79
+ "cell_type": "code",
80
+ "execution_count": 3,
81
+ "metadata": {
82
+ "application/vnd.databricks.v1+cell": {
83
+ "cellMetadata": {
84
+ "byteLimit": 2048000,
85
+ "rowLimit": 10000
86
+ },
87
+ "inputWidgets": {},
88
+ "nuid": "9f67ec60-2f24-411c-84eb-0dd664b44775",
89
+ "showTitle": false,
90
+ "title": ""
91
+ },
92
+ "colab": {
93
+ "base_uri": "https://localhost:8080/"
94
+ },
95
+ "executionInfo": {
96
+ "elapsed": 3,
97
+ "status": "ok",
98
+ "timestamp": 1720679529345,
99
+ "user": {
100
+ "displayName": "HUANG DONGHAO _",
101
+ "userId": "00977795705617022768"
102
+ },
103
+ "user_tz": -480
104
+ },
105
+ "id": "hPCC-6m7ZBrM",
106
+ "outputId": "c7aa2c96-5e99-440a-c148-201d79465ff9"
107
+ },
108
+ "outputs": [
109
+ {
110
+ "name": "stdout",
111
+ "output_type": "stream",
112
+ "text": [
113
+ "loading env vars from: /Users/inflaton/code/engd/papers/rapget-translation/.env\n"
114
+ ]
115
+ },
116
+ {
117
+ "data": {
118
+ "text/plain": [
119
+ "True"
120
+ ]
121
+ },
122
+ "execution_count": 3,
123
+ "metadata": {},
124
+ "output_type": "execute_result"
125
+ }
126
+ ],
127
+ "source": [
128
+ "from dotenv import find_dotenv, load_dotenv\n",
129
+ "\n",
130
+ "found_dotenv = find_dotenv(\".env\")\n",
131
+ "\n",
132
+ "if len(found_dotenv) == 0:\n",
133
+ " found_dotenv = find_dotenv(\".env.example\")\n",
134
+ "print(f\"loading env vars from: {found_dotenv}\")\n",
135
+ "load_dotenv(found_dotenv, override=True)"
136
+ ]
137
+ },
138
+ {
139
+ "cell_type": "code",
140
+ "execution_count": 4,
141
+ "metadata": {
142
+ "application/vnd.databricks.v1+cell": {
143
+ "cellMetadata": {
144
+ "byteLimit": 2048000,
145
+ "rowLimit": 10000
146
+ },
147
+ "inputWidgets": {},
148
+ "nuid": "f1597656-8042-4878-9d3b-9ebfb8dd86dc",
149
+ "showTitle": false,
150
+ "title": ""
151
+ },
152
+ "colab": {
153
+ "base_uri": "https://localhost:8080/"
154
+ },
155
+ "executionInfo": {
156
+ "elapsed": 3,
157
+ "status": "ok",
158
+ "timestamp": 1720679529345,
159
+ "user": {
160
+ "displayName": "HUANG DONGHAO _",
161
+ "userId": "00977795705617022768"
162
+ },
163
+ "user_tz": -480
164
+ },
165
+ "id": "1M3IraVtZBrM",
166
+ "outputId": "29ab35f6-2970-4ade-d85d-3174acf8cda0"
167
+ },
168
+ "outputs": [
169
+ {
170
+ "name": "stdout",
171
+ "output_type": "stream",
172
+ "text": [
173
+ "Qwen/Qwen2-7B-Instruct None False datasets/mac/mac.tsv results/mac-results.csv False 300\n"
174
+ ]
175
+ }
176
+ ],
177
+ "source": [
178
+ "import os\n",
179
+ "\n",
180
+ "model_name = os.getenv(\"MODEL_NAME\")\n",
181
+ "adapter_name_or_path = os.getenv(\"ADAPTER_NAME_OR_PATH\")\n",
182
+ "load_in_4bit = os.getenv(\"LOAD_IN_4BIT\") == \"true\"\n",
183
+ "data_path = os.getenv(\"DATA_PATH\")\n",
184
+ "results_path = os.getenv(\"RESULTS_PATH\")\n",
185
+ "use_english_datasets = os.getenv(\"USE_ENGLISH_DATASETS\") == \"true\"\n",
186
+ "max_new_tokens = int(os.getenv(\"MAX_NEW_TOKENS\", 2048))\n",
187
+ "\n",
188
+ "print(model_name, adapter_name_or_path, load_in_4bit, data_path, results_path, use_english_datasets, max_new_tokens)"
189
+ ]
190
+ },
191
+ {
192
+ "cell_type": "code",
193
+ "execution_count": 5,
194
+ "metadata": {
195
+ "application/vnd.databricks.v1+cell": {
196
+ "cellMetadata": {
197
+ "byteLimit": 2048000,
198
+ "rowLimit": 10000
199
+ },
200
+ "inputWidgets": {},
201
+ "nuid": "b2a43943-9324-4839-9a47-cfa72de2244b",
202
+ "showTitle": false,
203
+ "title": ""
204
+ },
205
+ "colab": {
206
+ "base_uri": "https://localhost:8080/"
207
+ },
208
+ "executionInfo": {
209
+ "elapsed": 564,
210
+ "status": "ok",
211
+ "timestamp": 1720679529907,
212
+ "user": {
213
+ "displayName": "HUANG DONGHAO _",
214
+ "userId": "00977795705617022768"
215
+ },
216
+ "user_tz": -480
217
+ },
218
+ "id": "UgMvt6dIZBrM",
219
+ "outputId": "ce37581c-fd26-46c2-ad87-d933d99f68f7"
220
+ },
221
+ "outputs": [
222
+ {
223
+ "name": "stdout",
224
+ "output_type": "stream",
225
+ "text": [
226
+ "Python 3.11.9\n",
227
+ "Name: torch\n",
228
+ "Version: 2.4.0\n",
229
+ "Summary: Tensors and Dynamic neural networks in Python with strong GPU acceleration\n",
230
+ "Home-page: https://pytorch.org/\n",
231
+ "Author: PyTorch Team\n",
232
+ "Author-email: packages@pytorch.org\n",
233
+ "License: BSD-3\n",
234
+ "Location: /Users/inflaton/anaconda3/envs/rapget/lib/python3.11/site-packages\n",
235
+ "Requires: filelock, fsspec, jinja2, networkx, sympy, typing-extensions\n",
236
+ "Required-by: accelerate, peft, torchaudio, torchvision\n",
237
+ "---\n",
238
+ "Name: transformers\n",
239
+ "Version: 4.43.3\n",
240
+ "Summary: State-of-the-art Machine Learning for JAX, PyTorch and TensorFlow\n",
241
+ "Home-page: https://github.com/huggingface/transformers\n",
242
+ "Author: The Hugging Face team (past and future) with the help of all our contributors (https://github.com/huggingface/transformers/graphs/contributors)\n",
243
+ "Author-email: transformers@huggingface.co\n",
244
+ "License: Apache 2.0 License\n",
245
+ "Location: /Users/inflaton/anaconda3/envs/rapget/lib/python3.11/site-packages\n",
246
+ "Requires: filelock, huggingface-hub, numpy, packaging, pyyaml, regex, requests, safetensors, tokenizers, tqdm\n",
247
+ "Required-by: peft\n",
248
+ "CPU times: user 11.5 ms, sys: 9.96 ms, total: 21.4 ms\n",
249
+ "Wall time: 1.98 s\n"
250
+ ]
251
+ }
252
+ ],
253
+ "source": [
254
+ "%%time\n",
255
+ "os.environ[\"TOKENIZERS_PARALLELISM\"] = \"true\"\n",
256
+ "\n",
257
+ "!python --version\n",
258
+ "!pip show torch transformers"
259
+ ]
260
+ },
261
+ {
262
+ "cell_type": "code",
263
+ "execution_count": 6,
264
+ "metadata": {
265
+ "colab": {
266
+ "base_uri": "https://localhost:8080/"
267
+ },
268
+ "executionInfo": {
269
+ "elapsed": 1685,
270
+ "status": "ok",
271
+ "timestamp": 1720679531591,
272
+ "user": {
273
+ "displayName": "HUANG DONGHAO _",
274
+ "userId": "00977795705617022768"
275
+ },
276
+ "user_tz": -480
277
+ },
278
+ "id": "ZuS_FsLyZBrN",
279
+ "outputId": "2cba0105-c505-4395-afbd-2f2fee6581d0"
280
+ },
281
+ "outputs": [
282
+ {
283
+ "name": "stderr",
284
+ "output_type": "stream",
285
+ "text": [
286
+ "[nltk_data] Downloading package wordnet to\n",
287
+ "[nltk_data] /Users/inflaton/nltk_data...\n",
288
+ "[nltk_data] Package wordnet is already up-to-date!\n",
289
+ "[nltk_data] Downloading package punkt to /Users/inflaton/nltk_data...\n",
290
+ "[nltk_data] Package punkt is already up-to-date!\n",
291
+ "[nltk_data] Downloading package omw-1.4 to\n",
292
+ "[nltk_data] /Users/inflaton/nltk_data...\n",
293
+ "[nltk_data] Package omw-1.4 is already up-to-date!\n"
294
+ ]
295
+ },
296
+ {
297
+ "name": "stdout",
298
+ "output_type": "stream",
299
+ "text": [
300
+ "loading: /Users/inflaton/code/engd/papers/rapget-translation/eval_modules/calc_repetitions.py\n",
301
+ "loading /Users/inflaton/code/engd/papers/rapget-translation/llm_toolkit/translation_utils.py\n"
302
+ ]
303
+ },
304
+ {
305
+ "name": "stderr",
306
+ "output_type": "stream",
307
+ "text": [
308
+ "[nltk_data] Downloading package wordnet to\n",
309
+ "[nltk_data] /Users/inflaton/nltk_data...\n",
310
+ "[nltk_data] Package wordnet is already up-to-date!\n",
311
+ "[nltk_data] Downloading package punkt to /Users/inflaton/nltk_data...\n",
312
+ "[nltk_data] Package punkt is already up-to-date!\n",
313
+ "[nltk_data] Downloading package omw-1.4 to\n",
314
+ "[nltk_data] /Users/inflaton/nltk_data...\n",
315
+ "[nltk_data] Package omw-1.4 is already up-to-date!\n"
316
+ ]
317
+ },
318
+ {
319
+ "name": "stdout",
320
+ "output_type": "stream",
321
+ "text": [
322
+ "MPS is available\n"
323
+ ]
324
+ }
325
+ ],
326
+ "source": [
327
+ "from llm_toolkit.llm_utils import *\n",
328
+ "from llm_toolkit.translation_utils import *\n",
329
+ "\n",
330
+ "device = check_gpu()"
331
+ ]
332
+ },
333
+ {
334
+ "cell_type": "code",
335
+ "execution_count": 7,
336
+ "metadata": {},
337
+ "outputs": [
338
+ {
339
+ "name": "stdout",
340
+ "output_type": "stream",
341
+ "text": [
342
+ "loading model: Qwen/Qwen2-7B-Instruct with adapter: None\n"
343
+ ]
344
+ },
345
+ {
346
+ "data": {
347
+ "application/vnd.jupyter.widget-view+json": {
348
+ "model_id": "dc2691496b9f4ace86e2d7d140511d98",
349
+ "version_major": 2,
350
+ "version_minor": 0
351
+ },
352
+ "text/plain": [
353
+ "Loading checkpoint shards: 0%| | 0/4 [00:00<?, ?it/s]"
354
+ ]
355
+ },
356
+ "metadata": {},
357
+ "output_type": "display_data"
358
+ }
359
+ ],
360
+ "source": [
361
+ "model, tokenizer = load_model(model_name)"
362
+ ]
363
+ },
364
+ {
365
+ "cell_type": "code",
366
+ "execution_count": 8,
367
+ "metadata": {},
368
+ "outputs": [
369
+ {
370
+ "name": "stdout",
371
+ "output_type": "stream",
372
+ "text": [
373
+ "loading train/test data files\n",
374
+ "DatasetDict({\n",
375
+ " train: Dataset({\n",
376
+ " features: ['chinese', 'english', 'text', 'prompt'],\n",
377
+ " num_rows: 4528\n",
378
+ " })\n",
379
+ " test: Dataset({\n",
380
+ " features: ['chinese', 'english', 'text', 'prompt'],\n",
381
+ " num_rows: 1133\n",
382
+ " })\n",
383
+ "})\n"
384
+ ]
385
+ }
386
+ ],
387
+ "source": [
388
+ "dataset = load_translation_dataset(data_path, tokenizer=tokenizer, num_shots=5)"
389
+ ]
390
+ },
391
+ {
392
+ "cell_type": "code",
393
+ "execution_count": 9,
394
+ "metadata": {},
395
+ "outputs": [
396
+ {
397
+ "data": {
398
+ "text/plain": [
399
+ "('那刘姥姥先听见告艰苦,只当是没想头了, 又听见给他二十两银子,喜的眉开眼笑道:“我们也知道艰难的,但只俗语说的:‘瘦死的骆驼比马还大’呢。',\n",
400
+ " '后来她不挣扎了,对我说,混蛋,你要把我怎么办。')"
401
+ ]
402
+ },
403
+ "execution_count": 9,
404
+ "metadata": {},
405
+ "output_type": "execute_result"
406
+ }
407
+ ],
408
+ "source": [
409
+ "dataset[\"test\"][\"chinese\"][260], dataset[\"test\"][\"chinese\"][908]"
410
+ ]
411
+ },
412
+ {
413
+ "cell_type": "code",
414
+ "execution_count": 10,
415
+ "metadata": {},
416
+ "outputs": [],
417
+ "source": [
418
+ "eval_dataset = dataset[\"test\"].select([260, 908])"
419
+ ]
420
+ },
421
+ {
422
+ "cell_type": "code",
423
+ "execution_count": 11,
424
+ "metadata": {},
425
+ "outputs": [
426
+ {
427
+ "name": "stdout",
428
+ "output_type": "stream",
429
+ "text": [
430
+ "--------------------------------------------------\n",
431
+ "chinese: 那刘姥姥先听见告艰苦,只当是没想头了, 又听见给他二十两银子,喜的眉开眼笑道:“我们也知道艰难的,但只俗语说的:‘瘦死的骆驼比马还大’呢。\n",
432
+ "--------------------------------------------------\n",
433
+ "english: When Grannie Liu heard Xi-feng talk about 'difficulties' she concluded that there was no hope. Her delight and the way in which her face lit up with pleasure when she heard that she was, after all, to be given twenty taels of silver can be imagined. 'We knew you had your troubles,' she said, 'but as the saying goes, 'A starved camel is bigger than a fat horse.'\n",
434
+ "--------------------------------------------------\n",
435
+ "text: <|im_start|>system\n",
436
+ "You are a helpful assistant that translates Chinese to English.<|im_end|>\n",
437
+ "<|im_start|>user\n",
438
+ "You will be given a Chinese sentence to translate. If it is an incomplete sentence, or if you are unsure about the meaning, simply copy the input text as your output. Do not output any additional sentence such as explanation or reasoning.\n",
439
+ "\n",
440
+ "Example Translations:\n",
441
+ "Chinese: 全仗着狐仙搭救。\n",
442
+ "English: Because I was protected by a fox fairy.\n",
443
+ "\n",
444
+ "Chinese: 过后,表哥告诉她俩,这人是导演,在外国留过学的,还会编剧,今天拍的这戏,就是他自编自导的。\n",
445
+ "English: He was the director, the cousin later told them. He had studied abroad and was also a screenwriter; in fact he had written and directed the scene they had earlier seen being filmed.\n",
446
+ "\n",
447
+ "Chinese: 这凤姐忽然想起一件事来,便向窗外叫:“蓉儿回来!”\n",
448
+ "English: Xi-feng suddenly seemed to remember something, and called to him through the window, 'Rong, come back!'\n",
449
+ "\n",
450
+ "Chinese: 三个老红卫兵走到叶文洁面前,面对着她站成了一排——当年,她们也是这样面对叶哲泰的——试图再现那早已忘却的尊严,但她们当年那魔鬼般的精神力量显然已荡然无存。\n",
451
+ "English: The three old Red Guards stood in front of Ye in a row—just like they had stood against Ye Zhetai—trying to recapture their long-forgotten dignity. But the demonic spiritual energy that had once propelled them was gone.\n",
452
+ "\n",
453
+ "Chinese: 程先生照单全收,都是一个“谢”字,然后问王琦瑶有什么话说。\n",
454
+ "English: Mr. Cheng accepted their toast with equanimity and a 'thank you.' Then, turning to Wang Qiyao, he asked if she had anything to say.\n",
455
+ "\n",
456
+ "Chinese: 那刘姥姥先听见告艰苦,只当是没想头了, 又听见给他二十两银子,喜的眉开眼笑道:“我们也知道艰难的,但只俗语说的:‘瘦死的骆驼比马还大’呢。\n",
457
+ "English:<|im_end|>\n",
458
+ "<|im_start|>assistant\n",
459
+ "When Grannie Liu heard Xi-feng talk about 'difficulties' she concluded that there was no hope. Her delight and the way in which her face lit up with pleasure when she heard that she was, after all, to be given twenty taels of silver can be imagined. 'We knew you had your troubles,' she said, 'but as the saying goes, 'A starved camel is bigger than a fat horse.'<|im_end|>\n",
460
+ "--------------------------------------------------\n",
461
+ "prompt: <|im_start|>system\n",
462
+ "You are a helpful assistant that translates Chinese to English.<|im_end|>\n",
463
+ "<|im_start|>user\n",
464
+ "You will be given a Chinese sentence to translate. If it is an incomplete sentence, or if you are unsure about the meaning, simply copy the input text as your output. Do not output any additional sentence such as explanation or reasoning.\n",
465
+ "\n",
466
+ "Example Translations:\n",
467
+ "Chinese: 全仗着狐仙搭救。\n",
468
+ "English: Because I was protected by a fox fairy.\n",
469
+ "\n",
470
+ "Chinese: 过后,表哥告诉她俩,这人是导演,在外国留过学的,还会编剧,今天拍的这戏,就是他自编自导的。\n",
471
+ "English: He was the director, the cousin later told them. He had studied abroad and was also a screenwriter; in fact he had written and directed the scene they had earlier seen being filmed.\n",
472
+ "\n",
473
+ "Chinese: 这凤姐忽然想起一件事来,便向窗外叫:“蓉儿回来!”\n",
474
+ "English: Xi-feng suddenly seemed to remember something, and called to him through the window, 'Rong, come back!'\n",
475
+ "\n",
476
+ "Chinese: 三个老红卫兵走到叶文洁面前,面对着她站成了一排——当年,她们也是这样面对叶哲泰的——试图再现那早已忘却的尊严,但她们当年那魔鬼般的精神力量显然已荡然无存。\n",
477
+ "English: The three old Red Guards stood in front of Ye in a row—just like they had stood against Ye Zhetai—trying to recapture their long-forgotten dignity. But the demonic spiritual energy that had once propelled them was gone.\n",
478
+ "\n",
479
+ "Chinese: 程先生照单全收,都是一个“谢”字,然后问王琦瑶有什么话说。\n",
480
+ "English: Mr. Cheng accepted their toast with equanimity and a 'thank you.' Then, turning to Wang Qiyao, he asked if she had anything to say.\n",
481
+ "\n",
482
+ "Chinese: 那刘姥姥先听见告艰苦,只当是没想头了, 又听见给他二十两银子,喜的眉开眼笑道:“我们也知道艰难的,但只俗语说的:‘瘦死的骆驼比马还大’呢。\n",
483
+ "English:<|im_end|>\n",
484
+ "<|im_start|>assistant\n",
485
+ "\n",
486
+ "--------------------------------------------------\n",
487
+ "chinese: 后来她不挣扎了,对我说,混蛋,你要把我怎么办。\n",
488
+ "--------------------------------------------------\n",
489
+ "english: After a while, she no longer struggled and said, You bastard! What are you going to do with me?\n",
490
+ "--------------------------------------------------\n",
491
+ "text: <|im_start|>system\n",
492
+ "You are a helpful assistant that translates Chinese to English.<|im_end|>\n",
493
+ "<|im_start|>user\n",
494
+ "You will be given a Chinese sentence to translate. If it is an incomplete sentence, or if you are unsure about the meaning, simply copy the input text as your output. Do not output any additional sentence such as explanation or reasoning.\n",
495
+ "\n",
496
+ "Example Translations:\n",
497
+ "Chinese: 全仗着狐仙搭救。\n",
498
+ "English: Because I was protected by a fox fairy.\n",
499
+ "\n",
500
+ "Chinese: 过后,表哥告诉她俩,这人是导演,在外国留过学的,还会编剧,今天拍的这戏,就是他自编自导的。\n",
501
+ "English: He was the director, the cousin later told them. He had studied abroad and was also a screenwriter; in fact he had written and directed the scene they had earlier seen being filmed.\n",
502
+ "\n",
503
+ "Chinese: 这凤姐忽然想起一件事来,便向窗外叫:“蓉儿回来!”\n",
504
+ "English: Xi-feng suddenly seemed to remember something, and called to him through the window, 'Rong, come back!'\n",
505
+ "\n",
506
+ "Chinese: 三个老红卫兵走到叶文洁面前,面对着她站成了一排——当年,她们也是这样面对叶哲泰的——试图再现那早已忘却的尊严,但她们当年那魔鬼般的精神力量显然已荡然无存。\n",
507
+ "English: The three old Red Guards stood in front of Ye in a row—just like they had stood against Ye Zhetai—trying to recapture their long-forgotten dignity. But the demonic spiritual energy that had once propelled them was gone.\n",
508
+ "\n",
509
+ "Chinese: 程先生照单全收,都是一个“谢”字,然后问王琦瑶有什么话说。\n",
510
+ "English: Mr. Cheng accepted their toast with equanimity and a 'thank you.' Then, turning to Wang Qiyao, he asked if she had anything to say.\n",
511
+ "\n",
512
+ "Chinese: 后来她不挣扎了,对我说,混蛋,你要把我怎么办。\n",
513
+ "English:<|im_end|>\n",
514
+ "<|im_start|>assistant\n",
515
+ "After a while, she no longer struggled and said, You bastard! What are you going to do with me?<|im_end|>\n",
516
+ "--------------------------------------------------\n",
517
+ "prompt: <|im_start|>system\n",
518
+ "You are a helpful assistant that translates Chinese to English.<|im_end|>\n",
519
+ "<|im_start|>user\n",
520
+ "You will be given a Chinese sentence to translate. If it is an incomplete sentence, or if you are unsure about the meaning, simply copy the input text as your output. Do not output any additional sentence such as explanation or reasoning.\n",
521
+ "\n",
522
+ "Example Translations:\n",
523
+ "Chinese: 全仗着狐仙搭救。\n",
524
+ "English: Because I was protected by a fox fairy.\n",
525
+ "\n",
526
+ "Chinese: 过后,表哥告诉她俩,这人是导演,在外国留过学的,还会编剧,今天拍的这戏,就是他自编自导的。\n",
527
+ "English: He was the director, the cousin later told them. He had studied abroad and was also a screenwriter; in fact he had written and directed the scene they had earlier seen being filmed.\n",
528
+ "\n",
529
+ "Chinese: 这凤姐忽然想起一件事来,便向窗外叫:“蓉儿回来!”\n",
530
+ "English: Xi-feng suddenly seemed to remember something, and called to him through the window, 'Rong, come back!'\n",
531
+ "\n",
532
+ "Chinese: 三个老红卫兵走到叶文洁面前,面对着她站成了一排——当年,她们也是这样面对叶哲泰的——试图再现那早已忘却的尊严,但她们当年那魔鬼般的精神力量显然已荡然无存。\n",
533
+ "English: The three old Red Guards stood in front of Ye in a row—just like they had stood against Ye Zhetai—trying to recapture their long-forgotten dignity. But the demonic spiritual energy that had once propelled them was gone.\n",
534
+ "\n",
535
+ "Chinese: 程先生照单全收,都是一个“谢”字,然后问王琦瑶有什么话说。\n",
536
+ "English: Mr. Cheng accepted their toast with equanimity and a 'thank you.' Then, turning to Wang Qiyao, he asked if she had anything to say.\n",
537
+ "\n",
538
+ "Chinese: 后来她不挣扎了,对我说,混蛋,你要把我怎么办。\n",
539
+ "English:<|im_end|>\n",
540
+ "<|im_start|>assistant\n",
541
+ "\n"
542
+ ]
543
+ }
544
+ ],
545
+ "source": [
546
+ "print_row_details(eval_dataset.to_pandas(), range(len(eval_dataset)))"
547
+ ]
548
+ },
549
+ {
550
+ "cell_type": "code",
551
+ "execution_count": 12,
552
+ "metadata": {},
553
+ "outputs": [
554
+ {
555
+ "name": "stderr",
556
+ "output_type": "stream",
557
+ "text": [
558
+ " 50%|█████ | 1/2 [01:54<01:54, 114.95s/it]"
559
+ ]
560
+ },
561
+ {
562
+ "name": "stdout",
563
+ "output_type": "stream",
564
+ "text": [
565
+ "Batch output: ['When she first heard that they were in dire straits, she thought that all hope was lost. But when she heard that they were to receive twenty taels of silver, she beamed with delight and said, \"We understand their difficulties, but as the saying goes, \\'a skinny camel is bigger than a horse\\'.\"']\n"
566
+ ]
567
+ },
568
+ {
569
+ "name": "stderr",
570
+ "output_type": "stream",
571
+ "text": [
572
+ "100%|██████████| 2/2 [02:34<00:00, 77.40s/it] \n"
573
+ ]
574
+ }
575
+ ],
576
+ "source": [
577
+ "predictions = eval_model(\n",
578
+ " model, tokenizer, eval_dataset, device=device, max_new_tokens=max_new_tokens\n",
579
+ ")"
580
+ ]
581
+ },
582
+ {
583
+ "cell_type": "code",
584
+ "execution_count": 13,
585
+ "metadata": {},
586
+ "outputs": [
587
+ {
588
+ "name": "stdout",
589
+ "output_type": "stream",
590
+ "text": [
591
+ "['When she first heard that they were in dire straits, she thought that all hope was lost. But when she heard that they were to receive twenty taels of silver, she beamed with delight and said, \"We understand their difficulties, but as the saying goes, \\'a skinny camel is bigger than a horse\\'.\"', 'Later, she stopped struggling and said to me, \"You bastard, what are you going to do to me?\"']\n"
592
+ ]
593
+ }
594
+ ],
595
+ "source": [
596
+ "print(predictions)"
597
+ ]
598
+ },
599
+ {
600
+ "cell_type": "code",
601
+ "execution_count": 17,
602
+ "metadata": {},
603
+ "outputs": [
604
+ {
605
+ "name": "stdout",
606
+ "output_type": "stream",
607
+ "text": [
608
+ "loading train/test data files\n"
609
+ ]
610
+ },
611
+ {
612
+ "data": {
613
+ "application/vnd.jupyter.widget-view+json": {
614
+ "model_id": "306c3180fd7d4580b4954ff2e1b26e38",
615
+ "version_major": 2,
616
+ "version_minor": 0
617
+ },
618
+ "text/plain": [
619
+ "Map: 0%| | 0/4528 [00:00<?, ? examples/s]"
620
+ ]
621
+ },
622
+ "metadata": {},
623
+ "output_type": "display_data"
624
+ },
625
+ {
626
+ "data": {
627
+ "application/vnd.jupyter.widget-view+json": {
628
+ "model_id": "8fd3530de8cc48f2a6795abb1c453318",
629
+ "version_major": 2,
630
+ "version_minor": 0
631
+ },
632
+ "text/plain": [
633
+ "Map: 0%| | 0/1133 [00:00<?, ? examples/s]"
634
+ ]
635
+ },
636
+ "metadata": {},
637
+ "output_type": "display_data"
638
+ },
639
+ {
640
+ "name": "stdout",
641
+ "output_type": "stream",
642
+ "text": [
643
+ "DatasetDict({\n",
644
+ " train: Dataset({\n",
645
+ " features: ['chinese', 'english', 'text', 'prompt'],\n",
646
+ " num_rows: 4528\n",
647
+ " })\n",
648
+ " test: Dataset({\n",
649
+ " features: ['chinese', 'english', 'text', 'prompt'],\n",
650
+ " num_rows: 1133\n",
651
+ " })\n",
652
+ "})\n"
653
+ ]
654
+ }
655
+ ],
656
+ "source": [
657
+ "from llm_toolkit.translation_utils_v1 import (\n",
658
+ " load_translation_dataset as load_translation_dataset_v1,\n",
659
+ ")\n",
660
+ "\n",
661
+ "dataset_v1 = load_translation_dataset_v1(data_path, tokenizer=tokenizer)"
662
+ ]
663
+ },
664
+ {
665
+ "cell_type": "code",
666
+ "execution_count": 18,
667
+ "metadata": {},
668
+ "outputs": [
669
+ {
670
+ "name": "stdout",
671
+ "output_type": "stream",
672
+ "text": [
673
+ "--------------------------------------------------\n",
674
+ "chinese: 老耿端起枪,眯缝起一只三角眼,一搂扳机响了枪,冰雹般的金麻雀劈哩啪啦往下落,铁砂子在柳枝间飞迸着,嚓嚓有声。\n",
675
+ "--------------------------------------------------\n",
676
+ "english: Old Geng picked up his shotgun, squinted, and pulled the trigger. Two sparrows crashed to the ground like hailstones as shotgun pellets tore noisily through the branches.\n",
677
+ "--------------------------------------------------\n",
678
+ "text: <|im_start|>system\n",
679
+ "You are an expert in translating Chinese to English.<|im_end|>\n",
680
+ "<|im_start|>user\n",
681
+ "Please translate the following Chinese text into English and provide only the translated content, nothing else.\n",
682
+ "老耿端起枪,眯缝起一只三角眼,一搂扳机响了枪,冰雹般的金麻雀劈哩啪啦往下落,铁砂子在柳枝间飞迸着,嚓嚓有声。<|im_end|>\n",
683
+ "<|im_start|>assistant\n",
684
+ "Old Geng picked up his shotgun, squinted, and pulled the trigger. Two sparrows crashed to the ground like hailstones as shotgun pellets tore noisily through the branches.<|im_end|>\n",
685
+ "--------------------------------------------------\n",
686
+ "prompt: <|im_start|>system\n",
687
+ "You are an expert in translating Chinese to English.<|im_end|>\n",
688
+ "<|im_start|>user\n",
689
+ "Please translate the following Chinese text into English and provide only the translated content, nothing else.\n",
690
+ "老耿端起枪,眯缝起一只三角眼,一搂扳机响了枪,冰雹般的金麻雀劈哩啪啦往下落,铁砂子在柳枝间飞迸着,嚓嚓有声。<|im_end|>\n",
691
+ "<|im_start|>assistant\n",
692
+ "\n"
693
+ ]
694
+ }
695
+ ],
696
+ "source": [
697
+ "print_row_details(dataset_v1[\"test\"].to_pandas())"
698
+ ]
699
+ },
700
+ {
701
+ "cell_type": "code",
702
+ "execution_count": 19,
703
+ "metadata": {},
704
+ "outputs": [
705
+ {
706
+ "name": "stderr",
707
+ "output_type": "stream",
708
+ "text": [
709
+ " 50%|█████ | 1/2 [01:14<01:14, 74.72s/it]"
710
+ ]
711
+ },
712
+ {
713
+ "name": "stdout",
714
+ "output_type": "stream",
715
+ "text": [
716
+ "Batch output: ['At first, when Old Lady Liu heard that there was no hope, she thought that was the end of it. But when she heard that twenty taels of silver would be given to her, she beamed with delight, saying with a smile, \"We understand the hardships, but as the old saying goes, \\'a skinny camel is bigger than a horse.\\' \"']\n"
717
+ ]
718
+ },
719
+ {
720
+ "name": "stderr",
721
+ "output_type": "stream",
722
+ "text": [
723
+ "100%|██████████| 2/2 [01:46<00:00, 53.02s/it]\n"
724
+ ]
725
+ },
726
+ {
727
+ "data": {
728
+ "text/plain": [
729
+ "['At first, when Old Lady Liu heard that there was no hope, she thought that was the end of it. But when she heard that twenty taels of silver would be given to her, she beamed with delight, saying with a smile, \"We understand the hardships, but as the old saying goes, \\'a skinny camel is bigger than a horse.\\' \"',\n",
730
+ " 'Later, she stopped struggling and said to me, \"F*ck, what are you going to do with me?\"']"
731
+ ]
732
+ },
733
+ "execution_count": 19,
734
+ "metadata": {},
735
+ "output_type": "execute_result"
736
+ }
737
+ ],
738
+ "source": [
739
+ "eval_dataset_v1 = dataset_v1[\"test\"].select([260, 908])\n",
740
+ "predictions_v1 = eval_model(\n",
741
+ " model, tokenizer, eval_dataset_v1, device=device, max_new_tokens=max_new_tokens\n",
742
+ ")\n",
743
+ "predictions_v1"
744
+ ]
745
+ },
746
+ {
747
+ "cell_type": "code",
748
+ "execution_count": 20,
749
+ "metadata": {},
750
+ "outputs": [
751
+ {
752
+ "name": "stdout",
753
+ "output_type": "stream",
754
+ "text": [
755
+ "loading train/test data files\n"
756
+ ]
757
+ },
758
+ {
759
+ "data": {
760
+ "application/vnd.jupyter.widget-view+json": {
761
+ "model_id": "1c3fddbfa2d84b218c28a50827bcbadd",
762
+ "version_major": 2,
763
+ "version_minor": 0
764
+ },
765
+ "text/plain": [
766
+ "Map: 0%| | 0/4528 [00:00<?, ? examples/s]"
767
+ ]
768
+ },
769
+ "metadata": {},
770
+ "output_type": "display_data"
771
+ },
772
+ {
773
+ "data": {
774
+ "application/vnd.jupyter.widget-view+json": {
775
+ "model_id": "4771c292a2ad43beab497f685502631b",
776
+ "version_major": 2,
777
+ "version_minor": 0
778
+ },
779
+ "text/plain": [
780
+ "Map: 0%| | 0/1133 [00:00<?, ? examples/s]"
781
+ ]
782
+ },
783
+ "metadata": {},
784
+ "output_type": "display_data"
785
+ },
786
+ {
787
+ "name": "stdout",
788
+ "output_type": "stream",
789
+ "text": [
790
+ "DatasetDict({\n",
791
+ " train: Dataset({\n",
792
+ " features: ['chinese', 'english', 'text', 'prompt'],\n",
793
+ " num_rows: 4528\n",
794
+ " })\n",
795
+ " test: Dataset({\n",
796
+ " features: ['chinese', 'english', 'text', 'prompt'],\n",
797
+ " num_rows: 1133\n",
798
+ " })\n",
799
+ "})\n"
800
+ ]
801
+ }
802
+ ],
803
+ "source": [
804
+ "dataset_v2 = load_translation_dataset(data_path, tokenizer=tokenizer, num_shots=0)"
805
+ ]
806
+ },
807
+ {
808
+ "cell_type": "code",
809
+ "execution_count": 21,
810
+ "metadata": {},
811
+ "outputs": [
812
+ {
813
+ "name": "stderr",
814
+ "output_type": "stream",
815
+ "text": [
816
+ " 50%|█████ | 1/2 [01:02<01:02, 62.37s/it]"
817
+ ]
818
+ },
819
+ {
820
+ "name": "stdout",
821
+ "output_type": "stream",
822
+ "text": [
823
+ "Batch output: ['That Lady Liu, having first heard that there was no hope, thought that things must be bad. But when she heard that she would receive twenty taels of silver, she smiled and said, \"We know how hard it is, but the saying goes: \\'A skinny camel is bigger than a horse.\\'\"']\n"
824
+ ]
825
+ },
826
+ {
827
+ "name": "stderr",
828
+ "output_type": "stream",
829
+ "text": [
830
+ "100%|██████████| 2/2 [01:20<00:00, 40.10s/it]\n"
831
+ ]
832
+ },
833
+ {
834
+ "data": {
835
+ "text/plain": [
836
+ "['That Lady Liu, having first heard that there was no hope, thought that things must be bad. But when she heard that she would receive twenty taels of silver, she smiled and said, \"We know how hard it is, but the saying goes: \\'A skinny camel is bigger than a horse.\\'\"',\n",
837
+ " 'Later, she stopped struggling and said to me, \"F*ck, what are you going to do with me?\"']"
838
+ ]
839
+ },
840
+ "execution_count": 21,
841
+ "metadata": {},
842
+ "output_type": "execute_result"
843
+ }
844
+ ],
845
+ "source": [
846
+ "eval_dataset_v2 = dataset_v2[\"test\"].select([260, 908])\n",
847
+ "predictions_v2 = eval_model(\n",
848
+ " model, tokenizer, eval_dataset_v2, device=device, max_new_tokens=max_new_tokens\n",
849
+ ")\n",
850
+ "predictions_v2"
851
+ ]
852
+ }
853
+ ],
854
+ "metadata": {
855
+ "accelerator": "GPU",
856
+ "application/vnd.databricks.v1+notebook": {
857
+ "dashboards": [],
858
+ "environmentMetadata": null,
859
+ "language": "python",
860
+ "notebookMetadata": {
861
+ "mostRecentlyExecutedCommandWithImplicitDF": {
862
+ "commandId": -1,
863
+ "dataframes": [
864
+ "_sqldf"
865
+ ]
866
+ },
867
+ "pythonIndentUnit": 4
868
+ },
869
+ "notebookName": "10_eval-lf-medium-py3.11",
870
+ "widgets": {}
871
+ },
872
+ "colab": {
873
+ "gpuType": "L4",
874
+ "provenance": []
875
+ },
876
+ "kernelspec": {
877
+ "display_name": "Python 3",
878
+ "name": "python3"
879
+ },
880
+ "language_info": {
881
+ "codemirror_mode": {
882
+ "name": "ipython",
883
+ "version": 3
884
+ },
885
+ "file_extension": ".py",
886
+ "mimetype": "text/x-python",
887
+ "name": "python",
888
+ "nbconvert_exporter": "python",
889
+ "pygments_lexer": "ipython3",
890
+ "version": "3.11.9"
891
+ }
892
+ },
893
+ "nbformat": 4,
894
+ "nbformat_minor": 0
895
+ }
notebooks/01a_Few-shot_Prompting.ipynb ADDED
@@ -0,0 +1 @@
 
 
1
+ {"cells":[{"cell_type":"code","execution_count":1,"metadata":{"executionInfo":{"elapsed":476,"status":"ok","timestamp":1720679526275,"user":{"displayName":"HUANG DONGHAO _","userId":"00977795705617022768"},"user_tz":-480},"id":"uWKRSV6eZsCn"},"outputs":[],"source":["%load_ext autoreload\n","%autoreload 2"]},{"cell_type":"code","execution_count":2,"metadata":{"application/vnd.databricks.v1+cell":{"cellMetadata":{"byteLimit":2048000,"rowLimit":10000},"inputWidgets":{},"nuid":"6d394937-6c99-4a7c-9d32-7600a280032f","showTitle":false,"title":""},"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":5,"status":"ok","timestamp":1720679529345,"user":{"displayName":"HUANG DONGHAO _","userId":"00977795705617022768"},"user_tz":-480},"id":"G5pNu3zgZBrL","outputId":"160a554f-fb08-4aa0-bc00-0422fb7c1fac"},"outputs":[{"name":"stdout","output_type":"stream","text":["workding dir: /Users/inflaton/code/engd/papers/rapget-translation\n"]}],"source":["import os\n","import sys\n","from pathlib import Path\n","\n","# check if workding_dir is in local variables\n","if \"workding_dir\" not in locals():\n"," workding_dir = str(Path.cwd().parent)\n","\n","os.chdir(workding_dir)\n","sys.path.append(workding_dir)\n","print(\"workding dir:\", workding_dir)"]},{"cell_type":"code","execution_count":3,"metadata":{"application/vnd.databricks.v1+cell":{"cellMetadata":{"byteLimit":2048000,"rowLimit":10000},"inputWidgets":{},"nuid":"9f67ec60-2f24-411c-84eb-0dd664b44775","showTitle":false,"title":""},"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":3,"status":"ok","timestamp":1720679529345,"user":{"displayName":"HUANG DONGHAO _","userId":"00977795705617022768"},"user_tz":-480},"id":"hPCC-6m7ZBrM","outputId":"c7aa2c96-5e99-440a-c148-201d79465ff9"},"outputs":[{"name":"stdout","output_type":"stream","text":["loading env vars from: /Users/inflaton/code/engd/papers/rapget-translation/.env\n"]},{"data":{"text/plain":["True"]},"execution_count":3,"metadata":{},"output_type":"execute_result"}],"source":["from dotenv import find_dotenv, load_dotenv\n","\n","found_dotenv = find_dotenv(\".env\")\n","\n","if len(found_dotenv) == 0:\n"," found_dotenv = find_dotenv(\".env.example\")\n","print(f\"loading env vars from: {found_dotenv}\")\n","load_dotenv(found_dotenv, override=True)"]},{"cell_type":"code","execution_count":4,"metadata":{"application/vnd.databricks.v1+cell":{"cellMetadata":{"byteLimit":2048000,"rowLimit":10000},"inputWidgets":{},"nuid":"f1597656-8042-4878-9d3b-9ebfb8dd86dc","showTitle":false,"title":""},"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":3,"status":"ok","timestamp":1720679529345,"user":{"displayName":"HUANG DONGHAO _","userId":"00977795705617022768"},"user_tz":-480},"id":"1M3IraVtZBrM","outputId":"29ab35f6-2970-4ade-d85d-3174acf8cda0"},"outputs":[{"name":"stdout","output_type":"stream","text":["01-ai/Yi-1.5-9B-Chat None False datasets/mac/mac.tsv results/mac-results.csv False 300\n"]}],"source":["import os\n","\n","model_name = os.getenv(\"MODEL_NAME\")\n","adapter_name_or_path = os.getenv(\"ADAPTER_NAME_OR_PATH\")\n","load_in_4bit = os.getenv(\"LOAD_IN_4BIT\") == \"true\"\n","data_path = os.getenv(\"DATA_PATH\")\n","results_path = os.getenv(\"RESULTS_PATH\")\n","use_english_datasets = os.getenv(\"USE_ENGLISH_DATASETS\") == \"true\"\n","max_new_tokens = int(os.getenv(\"MAX_NEW_TOKENS\", 2048))\n","\n","print(model_name, adapter_name_or_path, load_in_4bit, data_path, results_path, use_english_datasets, max_new_tokens)"]},{"cell_type":"code","execution_count":5,"metadata":{"application/vnd.databricks.v1+cell":{"cellMetadata":{"byteLimit":2048000,"rowLimit":10000},"inputWidgets":{},"nuid":"b2a43943-9324-4839-9a47-cfa72de2244b","showTitle":false,"title":""},"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":564,"status":"ok","timestamp":1720679529907,"user":{"displayName":"HUANG DONGHAO _","userId":"00977795705617022768"},"user_tz":-480},"id":"UgMvt6dIZBrM","outputId":"ce37581c-fd26-46c2-ad87-d933d99f68f7"},"outputs":[{"name":"stdout","output_type":"stream","text":["Python 3.11.9\n","Name: torch\n","Version: 2.4.0\n","Summary: Tensors and Dynamic neural networks in Python with strong GPU acceleration\n","Home-page: https://pytorch.org/\n","Author: PyTorch Team\n","Author-email: packages@pytorch.org\n","License: BSD-3\n","Location: /Users/inflaton/anaconda3/envs/rapget/lib/python3.11/site-packages\n","Requires: filelock, fsspec, jinja2, networkx, sympy, typing-extensions\n","Required-by: accelerate, peft, torchaudio, torchvision\n","---\n","Name: transformers\n","Version: 4.43.3\n","Summary: State-of-the-art Machine Learning for JAX, PyTorch and TensorFlow\n","Home-page: https://github.com/huggingface/transformers\n","Author: The Hugging Face team (past and future) with the help of all our contributors (https://github.com/huggingface/transformers/graphs/contributors)\n","Author-email: transformers@huggingface.co\n","License: Apache 2.0 License\n","Location: /Users/inflaton/anaconda3/envs/rapget/lib/python3.11/site-packages\n","Requires: filelock, huggingface-hub, numpy, packaging, pyyaml, regex, requests, safetensors, tokenizers, tqdm\n","Required-by: peft\n","CPU times: user 11.7 ms, sys: 10.4 ms, total: 22.1 ms\n","Wall time: 2 s\n"]}],"source":["%%time\n","os.environ[\"TOKENIZERS_PARALLELISM\"] = \"true\"\n","\n","!python --version\n","!pip show torch transformers"]},{"cell_type":"code","execution_count":6,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":1685,"status":"ok","timestamp":1720679531591,"user":{"displayName":"HUANG DONGHAO _","userId":"00977795705617022768"},"user_tz":-480},"id":"ZuS_FsLyZBrN","outputId":"2cba0105-c505-4395-afbd-2f2fee6581d0"},"outputs":[{"name":"stderr","output_type":"stream","text":["[nltk_data] Downloading package wordnet to\n","[nltk_data] /Users/inflaton/nltk_data...\n","[nltk_data] Package wordnet is already up-to-date!\n","[nltk_data] Downloading package punkt to /Users/inflaton/nltk_data...\n","[nltk_data] Package punkt is already up-to-date!\n","[nltk_data] Downloading package omw-1.4 to\n","[nltk_data] /Users/inflaton/nltk_data...\n","[nltk_data] Package omw-1.4 is already up-to-date!\n"]},{"name":"stdout","output_type":"stream","text":["loading: /Users/inflaton/code/engd/papers/rapget-translation/eval_modules/calc_repetitions.py\n","loading /Users/inflaton/code/engd/papers/rapget-translation/llm_toolkit/translation_utils.py\n"]},{"name":"stderr","output_type":"stream","text":["[nltk_data] Downloading package wordnet to\n","[nltk_data] /Users/inflaton/nltk_data...\n","[nltk_data] Package wordnet is already up-to-date!\n","[nltk_data] Downloading package punkt to /Users/inflaton/nltk_data...\n","[nltk_data] Package punkt is already up-to-date!\n","[nltk_data] Downloading package omw-1.4 to\n","[nltk_data] /Users/inflaton/nltk_data...\n","[nltk_data] Package omw-1.4 is already up-to-date!\n"]},{"name":"stdout","output_type":"stream","text":["MPS is available\n"]}],"source":["from llm_toolkit.llm_utils import *\n","from llm_toolkit.translation_utils import *\n","\n","device = check_gpu()"]},{"cell_type":"code","execution_count":7,"metadata":{},"outputs":[{"name":"stdout","output_type":"stream","text":["loading model: 01-ai/Yi-1.5-9B-Chat with adapter: None\n"]},{"data":{"application/vnd.jupyter.widget-view+json":{"model_id":"7c89049569084209a59d0209b96315f8","version_major":2,"version_minor":0},"text/plain":["Loading checkpoint shards: 0%| | 0/4 [00:00<?, ?it/s]"]},"metadata":{},"output_type":"display_data"}],"source":["model, tokenizer = load_model(model_name)"]},{"cell_type":"code","execution_count":8,"metadata":{},"outputs":[{"name":"stdout","output_type":"stream","text":["loading train/test data files\n"]},{"data":{"application/vnd.jupyter.widget-view+json":{"model_id":"580311939dc2470884444a1dee406a11","version_major":2,"version_minor":0},"text/plain":["Map: 0%| | 0/4528 [00:00<?, ? examples/s]"]},"metadata":{},"output_type":"display_data"},{"data":{"application/vnd.jupyter.widget-view+json":{"model_id":"7027653a0b1b4d4db8dda26802fd7497","version_major":2,"version_minor":0},"text/plain":["Map: 0%| | 0/1133 [00:00<?, ? examples/s]"]},"metadata":{},"output_type":"display_data"},{"name":"stdout","output_type":"stream","text":["DatasetDict({\n"," train: Dataset({\n"," features: ['chinese', 'english', 'text', 'prompt'],\n"," num_rows: 4528\n"," })\n"," test: Dataset({\n"," features: ['chinese', 'english', 'text', 'prompt'],\n"," num_rows: 1133\n"," })\n","})\n"]}],"source":["dataset = load_translation_dataset(data_path, tokenizer=tokenizer, num_shots=5)"]},{"cell_type":"code","execution_count":9,"metadata":{},"outputs":[{"data":{"text/plain":["('那刘姥姥先听见告艰苦,只当是没想头了, 又听见给他二十两银子,喜的眉开眼笑道:“我们也知道艰难的,但只俗语说的:‘瘦死的骆驼比马还大’呢。',\n"," '后来她不挣扎了,对我说,混蛋,你要把我怎么办。')"]},"execution_count":9,"metadata":{},"output_type":"execute_result"}],"source":["dataset[\"test\"][\"chinese\"][260], dataset[\"test\"][\"chinese\"][908]"]},{"cell_type":"code","execution_count":10,"metadata":{},"outputs":[],"source":["eval_dataset = dataset[\"test\"].select([260, 908])"]},{"cell_type":"code","execution_count":11,"metadata":{},"outputs":[{"name":"stdout","output_type":"stream","text":["--------------------------------------------------\n","chinese: 那刘姥姥先听见告艰苦,只当是没想头了, 又听见给他二十两银子,喜的眉开眼笑道:“我们也知道艰难的,但只俗语说的:‘瘦死的骆驼比马还大’呢。\n","--------------------------------------------------\n","english: When Grannie Liu heard Xi-feng talk about 'difficulties' she concluded that there was no hope. Her delight and the way in which her face lit up with pleasure when she heard that she was, after all, to be given twenty taels of silver can be imagined. 'We knew you had your troubles,' she said, 'but as the saying goes, 'A starved camel is bigger than a fat horse.'\n","--------------------------------------------------\n","text: You are a helpful assistant that translates Chinese to English.<|im_start|>user\n","You will be given a Chinese sentence to translate. If it is an incomplete sentence, or if you are unsure about the meaning, simply copy the input text as your output. Do not output any additional sentence such as explanation or reasoning.\n","\n","Example Translations:\n","Chinese: 全仗着狐仙搭救。\n","English: Because I was protected by a fox fairy.\n","Chinese: 过后,表哥告诉她俩,这人是导演,在外国留过学的,还会编剧,今天拍的这戏,就是他自编自导的。\n","English: He was the director, the cousin later told them. He had studied abroad and was also a screenwriter; in fact he had written and directed the scene they had earlier seen being filmed.\n","Chinese: 这凤姐忽然想起一件事来,便向窗外叫:“蓉儿回来!”\n","English: Xi-feng suddenly seemed to remember something, and called to him through the window, 'Rong, come back!'\n","Chinese: 三个老红卫兵走到叶文洁面前,面对着她站成了一排——当年,她们也是这样面对叶哲泰的——试图再现那早已忘却的尊严,但她们当年那魔鬼般的精神力量显然已荡然无存。\n","English: The three old Red Guards stood in front of Ye in a row—just like they had stood against Ye Zhetai—trying to recapture their long-forgotten dignity. But the demonic spiritual energy that had once propelled them was gone.\n","Chinese: 程先生照单全收,都是一个“谢”字,然后问王琦瑶有什么话说。\n","English: Mr. Cheng accepted their toast with equanimity and a 'thank you.' Then, turning to Wang Qiyao, he asked if she had anything to say.\n","\n","Chinese: 那刘姥姥先听见告艰苦,只当是没想头了, 又听见给他二十两银子,喜的眉开眼笑道:“我们也知道艰难的,但只俗语说的:‘瘦死的骆驼比马还大’呢。\n","English:<|im_end|>\n","<|im_start|>assistant\n","When Grannie Liu heard Xi-feng talk about 'difficulties' she concluded that there was no hope. Her delight and the way in which her face lit up with pleasure when she heard that she was, after all, to be given twenty taels of silver can be imagined. 'We knew you had your troubles,' she said, 'but as the saying goes, 'A starved camel is bigger than a fat horse.'<|im_end|>\n","--------------------------------------------------\n","prompt: You are a helpful assistant that translates Chinese to English.<|im_start|>user\n","You will be given a Chinese sentence to translate. If it is an incomplete sentence, or if you are unsure about the meaning, simply copy the input text as your output. Do not output any additional sentence such as explanation or reasoning.\n","\n","Example Translations:\n","Chinese: 全仗着狐仙搭救。\n","English: Because I was protected by a fox fairy.\n","Chinese: 过后,表哥告诉她俩,这人是导演,在外国留过学的,还会编剧,今天拍的这戏,就是他自编自导的。\n","English: He was the director, the cousin later told them. He had studied abroad and was also a screenwriter; in fact he had written and directed the scene they had earlier seen being filmed.\n","Chinese: 这凤姐忽然想起一件事来,便向窗外叫:“蓉儿回来!”\n","English: Xi-feng suddenly seemed to remember something, and called to him through the window, 'Rong, come back!'\n","Chinese: 三个老红卫兵走到叶文洁面前,面对着她站成了一排——当年,她们也是这样面对叶哲泰的——试图再现那早已忘却的尊严,但她们当年那魔鬼般的精神力量显然已荡然无存。\n","English: The three old Red Guards stood in front of Ye in a row—just like they had stood against Ye Zhetai—trying to recapture their long-forgotten dignity. But the demonic spiritual energy that had once propelled them was gone.\n","Chinese: 程先生照单全收,都是一个“谢”字,然后问王琦瑶有什么话说。\n","English: Mr. Cheng accepted their toast with equanimity and a 'thank you.' Then, turning to Wang Qiyao, he asked if she had anything to say.\n","\n","Chinese: 那刘姥姥先听见告艰苦,只当是没想头了, 又听见给他二十两银子,喜的眉开眼笑道:“我们也知道艰难的,但只俗语说的:‘瘦死的骆驼比马还大’呢。\n","English:<|im_end|>\n","<|im_start|>assistant\n","\n","--------------------------------------------------\n","chinese: 后来她不挣扎了,对我说,混蛋,你要把我怎么办。\n","--------------------------------------------------\n","english: After a while, she no longer struggled and said, You bastard! What are you going to do with me?\n","--------------------------------------------------\n","text: You are a helpful assistant that translates Chinese to English.<|im_start|>user\n","You will be given a Chinese sentence to translate. If it is an incomplete sentence, or if you are unsure about the meaning, simply copy the input text as your output. Do not output any additional sentence such as explanation or reasoning.\n","\n","Example Translations:\n","Chinese: 全仗着狐仙搭救。\n","English: Because I was protected by a fox fairy.\n","Chinese: 过后,表哥告诉她俩,这人是导演,在外国留过学的,还会编剧,今天拍的这戏,就是他自编自导的。\n","English: He was the director, the cousin later told them. He had studied abroad and was also a screenwriter; in fact he had written and directed the scene they had earlier seen being filmed.\n","Chinese: 这凤姐忽然想起一件事来,便向窗外叫:“蓉儿回来!”\n","English: Xi-feng suddenly seemed to remember something, and called to him through the window, 'Rong, come back!'\n","Chinese: 三个老红卫兵走到叶文洁面前,面对着她站成了一排——当年,她们也是这样面对叶哲泰的——试图再现那早已忘却的尊严,但她们当年那魔鬼般的精神力量显然已荡然无存。\n","English: The three old Red Guards stood in front of Ye in a row—just like they had stood against Ye Zhetai—trying to recapture their long-forgotten dignity. But the demonic spiritual energy that had once propelled them was gone.\n","Chinese: 程先生照单全收,都是一个“谢”字,然后问王琦瑶有什么话说。\n","English: Mr. Cheng accepted their toast with equanimity and a 'thank you.' Then, turning to Wang Qiyao, he asked if she had anything to say.\n","\n","Chinese: 后来她不挣扎了,对我说,混蛋,你要把我怎么办。\n","English:<|im_end|>\n","<|im_start|>assistant\n","After a while, she no longer struggled and said, You bastard! What are you going to do with me?<|im_end|>\n","--------------------------------------------------\n","prompt: You are a helpful assistant that translates Chinese to English.<|im_start|>user\n","You will be given a Chinese sentence to translate. If it is an incomplete sentence, or if you are unsure about the meaning, simply copy the input text as your output. Do not output any additional sentence such as explanation or reasoning.\n","\n","Example Translations:\n","Chinese: 全仗着狐仙搭救。\n","English: Because I was protected by a fox fairy.\n","Chinese: 过后,表哥告诉她俩,这人是导演,在外国留过学的,还会编剧,今天拍的这戏,就是他自编自导的。\n","English: He was the director, the cousin later told them. He had studied abroad and was also a screenwriter; in fact he had written and directed the scene they had earlier seen being filmed.\n","Chinese: 这凤姐忽然想起一件事来,便向窗外叫:“蓉儿回来!”\n","English: Xi-feng suddenly seemed to remember something, and called to him through the window, 'Rong, come back!'\n","Chinese: 三个老红卫兵走到叶文洁面前,面对着她站成了一排——当年,她们也是这样面对叶哲泰的——试图再现那早已忘却的尊严,但她们当年那魔鬼般的精神力量显然已荡然无存。\n","English: The three old Red Guards stood in front of Ye in a row—just like they had stood against Ye Zhetai—trying to recapture their long-forgotten dignity. But the demonic spiritual energy that had once propelled them was gone.\n","Chinese: 程先生照单全收,都是一个“谢”字,然后问王琦瑶有什么话说。\n","English: Mr. Cheng accepted their toast with equanimity and a 'thank you.' Then, turning to Wang Qiyao, he asked if she had anything to say.\n","\n","Chinese: 后来她不挣扎了,对我说,混蛋,你要把我怎么办。\n","English:<|im_end|>\n","<|im_start|>assistant\n","\n"]}],"source":["print_row_details(eval_dataset.to_pandas(), range(len(eval_dataset)))"]},{"cell_type":"code","execution_count":12,"metadata":{},"outputs":[{"name":"stderr","output_type":"stream","text":[" 50%|█████ | 1/2 [22:49<22:49, 1369.92s/it]"]},{"name":"stdout","output_type":"stream","text":["Batch output: ['The task is to translate a given Chinese sentence into English. If the sentence is incomplete or unclear, the assistant should simply copy the input text as the output without providing any additional explanation or reasoning.\\n\\nHere\\'s how to use the guidelines to find the answer:\\n\\n1. Read the given Chinese sentence carefully.\\n2. If the sentence is incomplete or unclear, copy the input text as the output.\\n3. If the sentence is clear, translate it into English while maintaining the original meaning.\\n4. Ensure that the translation is accurate and conveys the intended message.\\n\\nNow, let\\'s apply these guidelines to the given Chinese sentence:\\n\\nChinese: 那刘姥姥先听见告艰苦, 只当是没想头了, 又听见给他二十两银子, 喜的眉开眼笑道: “我们也知道艰难的, 但只俗语说的: ‘瘦死的骆驼比马还大’呢。\\n\\nFollowing the guidelines:\\n\\n1. Read the sentence carefully.\\n2. The sentence is clear, so we will translate it into English.\\n3. Translate the sentence: \"The first thing Dao-hsi heard was that they were in difficulties, and she thought there was no way out. Then she heard that they would give her twenty silver dollars, and she was overjoyed, smiling from ear to ear, saying, \\'We know the difficulties too, but']\n"]},{"name":"stderr","output_type":"stream","text":["100%|██████████| 2/2 [1:05:53<00:00, 1976.68s/it]\n"]}],"source":["predictions = eval_model(\n"," model, tokenizer, eval_dataset, device=device, max_new_tokens=max_new_tokens\n",")"]},{"cell_type":"code","execution_count":13,"metadata":{},"outputs":[{"name":"stdout","output_type":"stream","text":["['The task is to translate a given Chinese sentence into English. If the sentence is incomplete or unclear, the assistant should simply copy the input text as the output without providing any additional explanation or reasoning.\\n\\nHere\\'s how to use the guidelines to find the answer:\\n\\n1. Read the given Chinese sentence carefully.\\n2. If the sentence is incomplete or unclear, copy the input text as the output.\\n3. If the sentence is clear, translate it into English while maintaining the original meaning.\\n4. Ensure that the translation is accurate and conveys the intended message.\\n\\nNow, let\\'s apply these guidelines to the given Chinese sentence:\\n\\nChinese: 那刘姥姥先听见告艰苦, 只当是没想头了, 又听见给他二十两银子, 喜的眉开眼笑道: “我们也知道艰难的, 但只俗语说的: ‘瘦死的骆驼比马还大’呢。\\n\\nFollowing the guidelines:\\n\\n1. Read the sentence carefully.\\n2. The sentence is clear, so we will translate it into English.\\n3. Translate the sentence: \"The first thing Dao-hsi heard was that they were in difficulties, and she thought there was no way out. Then she heard that they would give her twenty silver dollars, and she was overjoyed, smiling from ear to ear, saying, \\'We know the difficulties too, but', 'Later, she stopped struggling and said to me, \"Asshole, what are you going to do with me?\"']\n"]}],"source":["print(predictions)"]},{"cell_type":"code","execution_count":14,"metadata":{},"outputs":[{"name":"stdout","output_type":"stream","text":["loading /Users/inflaton/code/engd/papers/rapget-translation/llm_toolkit/translation_utils_v1.py\n"]},{"name":"stderr","output_type":"stream","text":["[nltk_data] Downloading package wordnet to\n","[nltk_data] /Users/inflaton/nltk_data...\n","[nltk_data] Package wordnet is already up-to-date!\n","[nltk_data] Downloading package punkt to /Users/inflaton/nltk_data...\n","[nltk_data] Package punkt is already up-to-date!\n","[nltk_data] Downloading package omw-1.4 to\n","[nltk_data] /Users/inflaton/nltk_data...\n","[nltk_data] Package omw-1.4 is already up-to-date!\n"]},{"name":"stdout","output_type":"stream","text":["loading train/test data files\n","DatasetDict({\n"," train: Dataset({\n"," features: ['chinese', 'english', 'text', 'prompt'],\n"," num_rows: 4528\n"," })\n"," test: Dataset({\n"," features: ['chinese', 'english', 'text', 'prompt'],\n"," num_rows: 1133\n"," })\n","})\n"]}],"source":["from llm_toolkit.translation_utils_v1 import (\n"," load_translation_dataset as load_translation_dataset_v1,\n",")\n","\n","dataset_v1 = load_translation_dataset_v1(data_path, tokenizer=tokenizer)"]},{"cell_type":"code","execution_count":15,"metadata":{},"outputs":[{"name":"stdout","output_type":"stream","text":["--------------------------------------------------\n","chinese: 老耿端起枪,眯缝起一只三角眼,一搂扳机响了枪,冰雹般的金麻雀劈哩啪啦往下落,铁砂子在柳枝间飞迸着,嚓嚓有声。\n","--------------------------------------------------\n","english: Old Geng picked up his shotgun, squinted, and pulled the trigger. Two sparrows crashed to the ground like hailstones as shotgun pellets tore noisily through the branches.\n","--------------------------------------------------\n","text: You are an expert in translating Chinese to English.<|im_start|>user\n","Please translate the following Chinese text into English and provide only the translated content, nothing else.\n","老耿端起枪,眯缝起一只三角眼,一搂扳机响了枪,冰雹般的金麻雀劈哩啪啦往下落,铁砂子在柳枝间飞迸着,嚓嚓有声。<|im_end|>\n","<|im_start|>assistant\n","Old Geng picked up his shotgun, squinted, and pulled the trigger. Two sparrows crashed to the ground like hailstones as shotgun pellets tore noisily through the branches.<|im_end|>\n","--------------------------------------------------\n","prompt: You are an expert in translating Chinese to English.<|im_start|>user\n","Please translate the following Chinese text into English and provide only the translated content, nothing else.\n","老耿端起枪,眯缝起一只三角眼,一搂扳机响了枪,冰雹般的金麻雀劈哩啪啦往下落,铁砂子在柳枝间飞迸着,嚓嚓有声。<|im_end|>\n","<|im_start|>assistant\n","\n"]}],"source":["print_row_details(dataset_v1[\"test\"].to_pandas())"]},{"cell_type":"code","execution_count":16,"metadata":{},"outputs":[{"name":"stderr","output_type":"stream","text":[" 50%|█████ | 1/2 [31:44<31:44, 1904.57s/it]"]},{"name":"stdout","output_type":"stream","text":["Batch output: [\"First, I'll identify the key phrases and words in the Chinese text:\\n\\n1. 那刘姥姥 (that Diao Huawang)\\n2. 先听见告艰苦 (first heard of the hardship)\\n3. 只当是没想头了 (thought it was hopeless)\\n4. 又听见给他二十两银子 (also heard that he received 20 silver yuan)\\n5. 喜的眉开眼笑 (very happy, smiling broadly)\\n6. 我们也知道艰难的 (we also know the hardship)\\n7. 但只俗语说的 (but as the saying goes)\\n8. 瘦死的骆驼比马还大 (a camel that has lost weight is still larger than a horse)\\n\\nNow, I'll translate these key phrases and words into English:\\n\\n1. That Diao Huawang\\n2. First heard of the hardship\\n3. Thought it was hopeless\\n4. Also heard that he received 20 silver yuan\\n5. Was very happy, smiling broadly\\n6. We also know the hardship\\n7. But as the saying goes\\n8. A camel that has lost weight is still larger than a horse\\n\\nFinally, I'll construct the English sentence using these translated phrases:\\n\\nThat Diao Huawang first heard of the hardship, thinking it was hopeless, and then heard that he received\"]\n"]},{"name":"stderr","output_type":"stream","text":["100%|██████████| 2/2 [1:12:03<00:00, 2161.88s/it]\n"]},{"data":{"text/plain":["[\"First, I'll identify the key phrases and words in the Chinese text:\\n\\n1. 那刘姥姥 (that Diao Huawang)\\n2. 先听见告艰苦 (first heard of the hardship)\\n3. 只当是没想头了 (thought it was hopeless)\\n4. 又听见给他二十两银子 (also heard that he received 20 silver yuan)\\n5. 喜的眉开眼笑 (very happy, smiling broadly)\\n6. 我们也知道艰难的 (we also know the hardship)\\n7. 但只俗语说的 (but as the saying goes)\\n8. 瘦死的骆驼比马还大 (a camel that has lost weight is still larger than a horse)\\n\\nNow, I'll translate these key phrases and words into English:\\n\\n1. That Diao Huawang\\n2. First heard of the hardship\\n3. Thought it was hopeless\\n4. Also heard that he received 20 silver yuan\\n5. Was very happy, smiling broadly\\n6. We also know the hardship\\n7. But as the saying goes\\n8. A camel that has lost weight is still larger than a horse\\n\\nFinally, I'll construct the English sentence using these translated phrases:\\n\\nThat Diao Huawang first heard of the hardship, thinking it was hopeless, and then heard that he received\",\n"," 'Later, she stopped struggling and said to me, \"Son of a bitch, what are you going to do with me?\"']"]},"execution_count":16,"metadata":{},"output_type":"execute_result"}],"source":["eval_dataset_v1 = dataset_v1[\"test\"].select([260, 908])\n","predictions_v1 = eval_model(\n"," model, tokenizer, eval_dataset_v1, device=device, max_new_tokens=max_new_tokens\n",")\n","predictions_v1"]},{"cell_type":"code","execution_count":25,"metadata":{},"outputs":[{"name":"stdout","output_type":"stream","text":["[\"First, I'll identify the key phrases and words in the Chinese text:\\n\\n1. 那刘姥姥 (that Diao Huawang)\\n2. 先听见告艰苦 (first heard of the hardship)\\n3. 只当是没想头了 (thought it was hopeless)\\n4. 又听见给他二十两银子 (also heard that he received 20 silver yuan)\\n5. 喜的眉开眼笑 (very happy, smiling broadly)\\n6. 我们也知道艰难的 (we also know the hardship)\\n7. 但只俗语说的 (but as the saying goes)\\n8. 瘦死的骆驼比马还大 (a camel that has lost weight is still larger than a horse)\\n\\nNow, I'll translate these key phrases and words into English:\\n\\n1. That Diao Huawang\\n2. First heard of the hardship\\n3. Thought it was hopeless\\n4. Also heard that he received 20 silver yuan\\n5. Was very happy, smiling broadly\\n6. We also know the hardship\\n7. But as the saying goes\\n8. A camel that has lost weight is still larger than a horse\\n\\nFinally, I'll construct the English sentence using these translated phrases:\\n\\nThat Diao Huawang first heard of the hardship, thinking it was hopeless, and then heard that he received\", 'Later, she stopped struggling and said to me, \"Son of a bitch, what are you going to do with me?\"']\n"]}],"source":["print(predictions_v1)"]},{"cell_type":"code","execution_count":23,"metadata":{},"outputs":[{"name":"stdout","output_type":"stream","text":["--------------------------------------------------\n","chinese: 那刘姥姥先听见告艰苦,只当是没想头了, 又听见给他二十两银子,喜的眉开眼笑道:“我们也知道艰难的,但只俗语说的:‘瘦死的骆驼比马还大’呢。\n","--------------------------------------------------\n","english: When Grannie Liu heard Xi-feng talk about 'difficulties' she concluded that there was no hope. Her delight and the way in which her face lit up with pleasure when she heard that she was, after all, to be given twenty taels of silver can be imagined. 'We knew you had your troubles,' she said, 'but as the saying goes, 'A starved camel is bigger than a fat horse.'\n","--------------------------------------------------\n","text: You are an expert in translating Chinese to English.<|im_start|>user\n","Please translate the following Chinese text into English and provide only the translated content, nothing else.\n","那刘姥姥先听见告艰苦,只当是没想头了, 又听见给他二十两银子,喜的眉开眼笑道:“我们也知道艰难的,但只俗语说的:‘瘦死的骆驼比马还大’呢。<|im_end|>\n","<|im_start|>assistant\n","When Grannie Liu heard Xi-feng talk about 'difficulties' she concluded that there was no hope. Her delight and the way in which her face lit up with pleasure when she heard that she was, after all, to be given twenty taels of silver can be imagined. 'We knew you had your troubles,' she said, 'but as the saying goes, 'A starved camel is bigger than a fat horse.'<|im_end|>\n","--------------------------------------------------\n","prompt: You are an expert in translating Chinese to English.<|im_start|>user\n","Please translate the following Chinese text into English and provide only the translated content, nothing else.\n","那刘姥姥先听见告艰苦,只当是没想头了, 又听见给他二十两银子,喜的眉开眼笑道:“我们也知道艰难的,但只俗语说的:‘瘦死的骆驼比马还大’呢。<|im_end|>\n","<|im_start|>assistant\n","\n","--------------------------------------------------\n","chinese: 后来她不挣扎了,对我说,混蛋,你要把我怎么办。\n","--------------------------------------------------\n","english: After a while, she no longer struggled and said, You bastard! What are you going to do with me?\n","--------------------------------------------------\n","text: You are an expert in translating Chinese to English.<|im_start|>user\n","Please translate the following Chinese text into English and provide only the translated content, nothing else.\n","后来她不挣扎了,对我说,混蛋,你要把我怎么办。<|im_end|>\n","<|im_start|>assistant\n","After a while, she no longer struggled and said, You bastard! What are you going to do with me?<|im_end|>\n","--------------------------------------------------\n","prompt: You are an expert in translating Chinese to English.<|im_start|>user\n","Please translate the following Chinese text into English and provide only the translated content, nothing else.\n","后来她不挣扎了,对我说,混蛋,你要把我怎么办。<|im_end|>\n","<|im_start|>assistant\n","\n"]}],"source":["print_row_details(eval_dataset_v1.to_pandas(), range(len(eval_dataset_v1)))"]},{"cell_type":"code","execution_count":17,"metadata":{},"outputs":[{"name":"stdout","output_type":"stream","text":["loading train/test data files\n"]},{"data":{"application/vnd.jupyter.widget-view+json":{"model_id":"1ab2b86ace5f4210bb27b51fb5d66c7a","version_major":2,"version_minor":0},"text/plain":["Map: 0%| | 0/4528 [00:00<?, ? examples/s]"]},"metadata":{},"output_type":"display_data"},{"data":{"application/vnd.jupyter.widget-view+json":{"model_id":"e7a07f55f30249329e07e3883d6a5f03","version_major":2,"version_minor":0},"text/plain":["Map: 0%| | 0/1133 [00:00<?, ? examples/s]"]},"metadata":{},"output_type":"display_data"},{"name":"stdout","output_type":"stream","text":["DatasetDict({\n"," train: Dataset({\n"," features: ['chinese', 'english', 'text', 'prompt'],\n"," num_rows: 4528\n"," })\n"," test: Dataset({\n"," features: ['chinese', 'english', 'text', 'prompt'],\n"," num_rows: 1133\n"," })\n","})\n"]}],"source":["dataset_v2 = load_translation_dataset(data_path, tokenizer=tokenizer, num_shots=0)"]},{"cell_type":"code","execution_count":18,"metadata":{},"outputs":[{"name":"stderr","output_type":"stream","text":[" 50%|█████ | 1/2 [42:49<42:49, 2569.31s/it]"]},{"name":"stdout","output_type":"stream","text":["Batch output: ['That Dukai first heard about the hardship, thinking it was pointless, but then heard that he received twenty silver pieces, and was so happy that his eyebrows and eyes opened wide as he said, \"We know the difficulties, but as the saying goes, \\'Even a lean camel is bigger than a horse.\\'\"']\n"]},{"name":"stderr","output_type":"stream","text":["100%|██████████| 2/2 [1:00:03<00:00, 1801.76s/it]\n"]},{"data":{"text/plain":["['That Dukai first heard about the hardship, thinking it was pointless, but then heard that he received twenty silver pieces, and was so happy that his eyebrows and eyes opened wide as he said, \"We know the difficulties, but as the saying goes, \\'Even a lean camel is bigger than a horse.\\'\"',\n"," '后来她不挣扎了, 对我说, 混蛋, 你要把我怎么办。\\nBased on the given instructions, since the input is a complete sentence and there is no need for additional explanation or reasoning, the output is the same as the input:\\n\\nEnglish: 后来她不挣扎了, 对我说, 混蛋, 你要把我怎么办。']"]},"execution_count":18,"metadata":{},"output_type":"execute_result"}],"source":["eval_dataset_v2 = dataset_v2[\"test\"].select([260, 908])\n","predictions_v2 = eval_model(\n"," model, tokenizer, eval_dataset_v2, device=device, max_new_tokens=max_new_tokens\n",")\n","predictions_v2"]},{"cell_type":"code","execution_count":24,"metadata":{},"outputs":[{"name":"stdout","output_type":"stream","text":["['That Dukai first heard about the hardship, thinking it was pointless, but then heard that he received twenty silver pieces, and was so happy that his eyebrows and eyes opened wide as he said, \"We know the difficulties, but as the saying goes, \\'Even a lean camel is bigger than a horse.\\'\"', '后来她不挣扎了, 对我说, 混蛋, 你要把我怎么办。\\nBased on the given instructions, since the input is a complete sentence and there is no need for additional explanation or reasoning, the output is the same as the input:\\n\\nEnglish: 后来她不挣扎了, 对我说, 混蛋, 你要把我怎么办。']\n"]}],"source":["print(predictions_v2)"]},{"cell_type":"code","execution_count":22,"metadata":{},"outputs":[{"name":"stdout","output_type":"stream","text":["--------------------------------------------------\n","chinese: 那刘姥姥先听见告艰苦,只当是没想头了, 又听见给他二十两银子,喜的眉开眼笑道:“我们也知道艰难的,但只俗语说的:‘瘦死的骆驼比马还大’呢。\n","--------------------------------------------------\n","english: When Grannie Liu heard Xi-feng talk about 'difficulties' she concluded that there was no hope. Her delight and the way in which her face lit up with pleasure when she heard that she was, after all, to be given twenty taels of silver can be imagined. 'We knew you had your troubles,' she said, 'but as the saying goes, 'A starved camel is bigger than a fat horse.'\n","--------------------------------------------------\n","text: You are a helpful assistant that translates Chinese to English.<|im_start|>user\n","You will be given a Chinese sentence to translate. If it is an incomplete sentence, or if you are unsure about the meaning, simply copy the input text as your output. Do not output any additional sentence such as explanation or reasoning.\n","\n","Chinese: 那刘姥姥先听见告艰苦,只当是没想头了, 又听见给他二十两银子,喜的眉开眼笑道:“我们也知道艰难的,但只俗语说的:‘瘦死的骆驼比马还大’呢。\n","English:<|im_end|>\n","<|im_start|>assistant\n","When Grannie Liu heard Xi-feng talk about 'difficulties' she concluded that there was no hope. Her delight and the way in which her face lit up with pleasure when she heard that she was, after all, to be given twenty taels of silver can be imagined. 'We knew you had your troubles,' she said, 'but as the saying goes, 'A starved camel is bigger than a fat horse.'<|im_end|>\n","--------------------------------------------------\n","prompt: You are a helpful assistant that translates Chinese to English.<|im_start|>user\n","You will be given a Chinese sentence to translate. If it is an incomplete sentence, or if you are unsure about the meaning, simply copy the input text as your output. Do not output any additional sentence such as explanation or reasoning.\n","\n","Chinese: 那刘姥姥先听见告艰苦,只当是没想头了, 又听见给他二十两银子,喜的眉开眼笑道:“我们也知道艰难的,但只俗语说的:‘瘦死的骆驼比马还大’呢。\n","English:<|im_end|>\n","<|im_start|>assistant\n","\n","--------------------------------------------------\n","chinese: 后来她不挣扎了,对我说,混蛋,你要把我怎么办。\n","--------------------------------------------------\n","english: After a while, she no longer struggled and said, You bastard! What are you going to do with me?\n","--------------------------------------------------\n","text: You are a helpful assistant that translates Chinese to English.<|im_start|>user\n","You will be given a Chinese sentence to translate. If it is an incomplete sentence, or if you are unsure about the meaning, simply copy the input text as your output. Do not output any additional sentence such as explanation or reasoning.\n","\n","Chinese: 后来她不挣扎了,对我说,混蛋,你要把我怎么办。\n","English:<|im_end|>\n","<|im_start|>assistant\n","After a while, she no longer struggled and said, You bastard! What are you going to do with me?<|im_end|>\n","--------------------------------------------------\n","prompt: You are a helpful assistant that translates Chinese to English.<|im_start|>user\n","You will be given a Chinese sentence to translate. If it is an incomplete sentence, or if you are unsure about the meaning, simply copy the input text as your output. Do not output any additional sentence such as explanation or reasoning.\n","\n","Chinese: 后来她不挣扎了,对我说,混蛋,你要把我怎么办。\n","English:<|im_end|>\n","<|im_start|>assistant\n","\n"]}],"source":["print_row_details(eval_dataset_v2.to_pandas(), range(len(eval_dataset_v2)))"]}],"metadata":{"accelerator":"GPU","application/vnd.databricks.v1+notebook":{"dashboards":[],"environmentMetadata":null,"language":"python","notebookMetadata":{"mostRecentlyExecutedCommandWithImplicitDF":{"commandId":-1,"dataframes":["_sqldf"]},"pythonIndentUnit":4},"notebookName":"10_eval-lf-medium-py3.11","widgets":{}},"colab":{"gpuType":"L4","provenance":[]},"kernelspec":{"display_name":"Python 3","name":"python3"},"language_info":{"codemirror_mode":{"name":"ipython","version":3},"file_extension":".py","mimetype":"text/x-python","name":"python","nbconvert_exporter":"python","pygments_lexer":"ipython3","version":"3.11.9"}},"nbformat":4,"nbformat_minor":0}
results/mac-results_few_shots_metrics.csv ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ model,shots,meteor,bleu_1,rouge_l,ews_score,repetition_score,total_repetitions,rap,num_max_output_tokens
2
+ 01-ai/Yi-1.5-9B-Chat,00,0.2624042529095214,0.052402107437040435,0.22695449752648078,0.0088261253309797,1.593115622241836,1.6019417475728155,0.24649759532229093,18
results/mac-results_metrics.csv CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:b0aa0a2d4b057e393ee709acc728187c2b1823e593ff134eb1d9de181595a13a
3
- size 15845
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:416f85facc5ab01dda9e52624c0a2b9db9fadf32a8ee2b1ab217eaa10a651c31
3
+ size 17401
scripts/eval-4gpu.sh CHANGED
@@ -15,10 +15,11 @@ grep MemTotal /proc/meminfo
15
 
16
  #pip install -r requirements.txt
17
 
18
- #./scripts/eval-model.sh Qwen/Qwen2-72B-Instruct
19
-
20
  export BATCH_SIZE=1
21
- export START_REPETITION_PENALTY=1.06
 
 
 
22
  ./scripts/eval-model.sh shenzhi-wang/Llama3.1-70B-Chinese-Chat
23
 
24
  # ./scripts/eval-model.sh 01-ai/Yi-1.5-34B-Chat
 
15
 
16
  #pip install -r requirements.txt
17
 
 
 
18
  export BATCH_SIZE=1
19
+ # export START_REPETITION_PENALTY=1.06
20
+
21
+ ./scripts/eval-model.sh Qwen/Qwen2-72B-Instruct
22
+
23
  ./scripts/eval-model.sh shenzhi-wang/Llama3.1-70B-Chinese-Chat
24
 
25
  # ./scripts/eval-model.sh 01-ai/Yi-1.5-34B-Chat