Spaces:
Build error
Build error
complete results for gpt-4o and gpt-4o-mini
Browse files- llm_toolkit/eval.py +6 -0
- llm_toolkit/eval_openai.py +75 -0
- llm_toolkit/llm_utils.py +14 -0
- llm_toolkit/translation_utils.py +43 -23
- logs/openai-gpt-4o-mini.txt +0 -0
- logs/openai-gpt-4o.txt +74 -0
- notebooks/00b_Data Analysis_Few_Shots.ipynb +2 -2
- notebooks/01b_Few-shot_Prompting_RTX4080.ipynb +1 -0
- notebooks/01c_Few-shot_Prompting_OpenAI.ipynb +1 -0
- results/mac-results_few_shots_metrics.csv +22 -8
- results/mac-results_few_shots_openai.csv +0 -0
- scripts/eval-mac.sh +6 -4
llm_toolkit/eval.py
CHANGED
@@ -28,6 +28,7 @@ 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 |
|
32 |
print(
|
33 |
model_name,
|
@@ -83,6 +84,7 @@ def evaluate_model_with_num_shots(
|
|
83 |
tokenizer,
|
84 |
model_name,
|
85 |
data_path,
|
|
|
86 |
range_num_shots=[0, 1, 3, 5, 10, 50],
|
87 |
batch_size=1,
|
88 |
max_new_tokens=2048,
|
@@ -91,6 +93,9 @@ def evaluate_model_with_num_shots(
|
|
91 |
print(f"Evaluating model: {model_name} on {device}")
|
92 |
|
93 |
for num_shots in range_num_shots:
|
|
|
|
|
|
|
94 |
print(f"*** Evaluating with num_shots: {num_shots}")
|
95 |
|
96 |
datasets = load_translation_dataset(data_path, tokenizer, num_shots=num_shots)
|
@@ -125,6 +130,7 @@ evaluate_model_with_num_shots(
|
|
125 |
batch_size=batch_size,
|
126 |
max_new_tokens=max_new_tokens,
|
127 |
device=device,
|
|
|
128 |
)
|
129 |
|
130 |
if is_cuda:
|
|
|
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_num_shots = int(os.getenv("START_NUM_SHOTS", 0))
|
32 |
|
33 |
print(
|
34 |
model_name,
|
|
|
84 |
tokenizer,
|
85 |
model_name,
|
86 |
data_path,
|
87 |
+
start_num_shots=0,
|
88 |
range_num_shots=[0, 1, 3, 5, 10, 50],
|
89 |
batch_size=1,
|
90 |
max_new_tokens=2048,
|
|
|
93 |
print(f"Evaluating model: {model_name} on {device}")
|
94 |
|
95 |
for num_shots in range_num_shots:
|
96 |
+
if num_shots < start_num_shots:
|
97 |
+
continue
|
98 |
+
|
99 |
print(f"*** Evaluating with num_shots: {num_shots}")
|
100 |
|
101 |
datasets = load_translation_dataset(data_path, tokenizer, num_shots=num_shots)
|
|
|
130 |
batch_size=batch_size,
|
131 |
max_new_tokens=max_new_tokens,
|
132 |
device=device,
|
133 |
+
start_num_shots=start_num_shots,
|
134 |
)
|
135 |
|
136 |
if is_cuda:
|
llm_toolkit/eval_openai.py
ADDED
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import sys
|
3 |
+
from dotenv import find_dotenv, load_dotenv
|
4 |
+
|
5 |
+
found_dotenv = find_dotenv(".env")
|
6 |
+
|
7 |
+
if len(found_dotenv) == 0:
|
8 |
+
found_dotenv = find_dotenv(".env.example")
|
9 |
+
print(f"loading env vars from: {found_dotenv}")
|
10 |
+
load_dotenv(found_dotenv, override=False)
|
11 |
+
|
12 |
+
path = os.path.dirname(found_dotenv)
|
13 |
+
print(f"Adding {path} to sys.path")
|
14 |
+
sys.path.append(path)
|
15 |
+
|
16 |
+
from llm_toolkit.llm_utils import *
|
17 |
+
from llm_toolkit.translation_utils import *
|
18 |
+
|
19 |
+
model_name = os.getenv("MODEL_NAME")
|
20 |
+
data_path = os.getenv("DATA_PATH")
|
21 |
+
results_path = os.getenv("RESULTS_PATH")
|
22 |
+
max_new_tokens = int(os.getenv("MAX_NEW_TOKENS", 2048))
|
23 |
+
|
24 |
+
print(
|
25 |
+
model_name,
|
26 |
+
data_path,
|
27 |
+
results_path,
|
28 |
+
max_new_tokens,
|
29 |
+
)
|
30 |
+
|
31 |
+
|
32 |
+
def on_num_shots_step_completed(model_name, dataset, predictions):
|
33 |
+
save_results(
|
34 |
+
model_name,
|
35 |
+
results_path,
|
36 |
+
dataset,
|
37 |
+
predictions,
|
38 |
+
)
|
39 |
+
|
40 |
+
metrics = calc_metrics(dataset["english"], predictions, debug=True)
|
41 |
+
print(f"{model_name} metrics: {metrics}")
|
42 |
+
|
43 |
+
|
44 |
+
def evaluate_model_with_num_shots(
|
45 |
+
model_name,
|
46 |
+
data_path,
|
47 |
+
range_num_shots=[0, 1, 3, 5, 10, 50],
|
48 |
+
max_new_tokens=2048,
|
49 |
+
):
|
50 |
+
print(f"Evaluating model: {model_name}")
|
51 |
+
|
52 |
+
datasets = load_translation_dataset(data_path)
|
53 |
+
print_row_details(datasets["test"].to_pandas())
|
54 |
+
|
55 |
+
for num_shots in range_num_shots:
|
56 |
+
print(f"*** Evaluating with num_shots: {num_shots}")
|
57 |
+
|
58 |
+
predictions = eval_openai(num_shots, datasets, max_new_tokens=max_new_tokens)
|
59 |
+
model_name_with_shorts = f"{model_name}/shots-{num_shots:02d}"
|
60 |
+
|
61 |
+
try:
|
62 |
+
on_num_shots_step_completed(
|
63 |
+
model_name_with_shorts,
|
64 |
+
datasets["test"],
|
65 |
+
predictions,
|
66 |
+
)
|
67 |
+
except Exception as e:
|
68 |
+
print(e)
|
69 |
+
|
70 |
+
|
71 |
+
evaluate_model_with_num_shots(
|
72 |
+
model_name,
|
73 |
+
data_path,
|
74 |
+
max_new_tokens=max_new_tokens,
|
75 |
+
)
|
llm_toolkit/llm_utils.py
CHANGED
@@ -2,6 +2,7 @@ import os
|
|
2 |
import re
|
3 |
import numpy as np
|
4 |
import torch
|
|
|
5 |
from transformers import (
|
6 |
AutoModelForCausalLM,
|
7 |
AutoTokenizer,
|
@@ -22,7 +23,20 @@ def get_template(model_name):
|
|
22 |
return "chatml"
|
23 |
|
24 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
25 |
def load_tokenizer(model_name):
|
|
|
|
|
|
|
26 |
return AutoTokenizer.from_pretrained(
|
27 |
model_name, trust_remote_code=True, padding_side="left"
|
28 |
)
|
|
|
2 |
import re
|
3 |
import numpy as np
|
4 |
import torch
|
5 |
+
import tiktoken
|
6 |
from transformers import (
|
7 |
AutoModelForCausalLM,
|
8 |
AutoTokenizer,
|
|
|
23 |
return "chatml"
|
24 |
|
25 |
|
26 |
+
class OpenAITokenizer:
|
27 |
+
|
28 |
+
def __init__(self, model_name):
|
29 |
+
self.model_name = model_name
|
30 |
+
self.encoding = tiktoken.get_encoding(model_name)
|
31 |
+
|
32 |
+
def __call__(self, text, return_tensors="pt"):
|
33 |
+
return {"input_ids": self.encoding.encode(text)}
|
34 |
+
|
35 |
+
|
36 |
def load_tokenizer(model_name):
|
37 |
+
if "gpt" in model_name:
|
38 |
+
return OpenAITokenizer("cl100k_base")
|
39 |
+
|
40 |
return AutoTokenizer.from_pretrained(
|
41 |
model_name, trust_remote_code=True, padding_side="left"
|
42 |
)
|
llm_toolkit/translation_utils.py
CHANGED
@@ -79,7 +79,7 @@ def save_results(model_name, results_path, dataset, predictions, debug=False):
|
|
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 |
|
@@ -91,6 +91,19 @@ def save_results(model_name, results_path, dataset, predictions, debug=False):
|
|
91 |
df.to_csv(results_path, index=False)
|
92 |
|
93 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
94 |
def load_translation_dataset(data_path, tokenizer=None, num_shots=5):
|
95 |
train_data_file = data_path.replace(".tsv", "-train.tsv")
|
96 |
test_data_file = data_path.replace(".tsv", "-test.tsv")
|
@@ -122,15 +135,7 @@ def load_translation_dataset(data_path, tokenizer=None, num_shots=5):
|
|
122 |
)
|
123 |
|
124 |
if tokenizer:
|
125 |
-
translation_prompt = "
|
126 |
-
if num_shots > 0:
|
127 |
-
example_translations = "Example Translations:\n"
|
128 |
-
for i in range(num_shots):
|
129 |
-
example_translations += f"Chinese: {datasets['train'][i]['chinese']}\n"
|
130 |
-
example_translations += f"English: {datasets['train'][i]['english']}\n"
|
131 |
-
translation_prompt = translation_prompt + example_translations + "\n"
|
132 |
-
|
133 |
-
translation_prompt = translation_prompt + "Chinese: {}\nEnglish:"
|
134 |
|
135 |
def formatting_prompts_func(examples):
|
136 |
inputs = examples["chinese"]
|
@@ -152,7 +157,7 @@ def load_translation_dataset(data_path, tokenizer=None, num_shots=5):
|
|
152 |
texts = []
|
153 |
prompts = []
|
154 |
for input, output in zip(inputs, outputs):
|
155 |
-
prompt = translation_prompt.format(input)
|
156 |
messages[-1] = {"role": "user", "content": prompt}
|
157 |
|
158 |
prompt = tokenizer.apply_chat_template(
|
@@ -426,12 +431,13 @@ def plot_times(perf_df, ylim=0.421):
|
|
426 |
plt.show()
|
427 |
|
428 |
|
429 |
-
def
|
430 |
-
|
|
|
431 |
llm = ChatOpenAI(
|
432 |
-
model=
|
433 |
temperature=0,
|
434 |
-
max_tokens=
|
435 |
timeout=None,
|
436 |
max_retries=2,
|
437 |
base_url=base_url,
|
@@ -439,9 +445,13 @@ def translate_via_llm(text):
|
|
439 |
|
440 |
prompt = ChatPromptTemplate.from_messages(
|
441 |
[
|
|
|
|
|
|
|
|
|
442 |
(
|
443 |
"human",
|
444 |
-
|
445 |
),
|
446 |
]
|
447 |
)
|
@@ -452,13 +462,23 @@ def translate_via_llm(text):
|
|
452 |
"input": text,
|
453 |
}
|
454 |
)
|
|
|
455 |
return response.content
|
456 |
|
457 |
|
458 |
-
def
|
459 |
-
|
460 |
-
|
461 |
-
|
462 |
-
|
463 |
-
|
464 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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, errors="ignore")
|
83 |
else:
|
84 |
df = pd.read_csv(results_path, on_bad_lines="warn")
|
85 |
|
|
|
91 |
df.to_csv(results_path, index=False)
|
92 |
|
93 |
|
94 |
+
def get_few_shot_prompt(dataset, num_shots=5):
|
95 |
+
translation_prompt = "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"
|
96 |
+
if num_shots > 0:
|
97 |
+
example_translations = "Example Translations:\n"
|
98 |
+
for i in range(num_shots):
|
99 |
+
example_translations += f"Chinese: {dataset[i]['chinese']}\n"
|
100 |
+
example_translations += f"English: {dataset[i]['english']}\n"
|
101 |
+
translation_prompt = translation_prompt + example_translations + "\n"
|
102 |
+
|
103 |
+
translation_prompt = translation_prompt + "Chinese: {input}\nEnglish:"
|
104 |
+
return translation_prompt
|
105 |
+
|
106 |
+
|
107 |
def load_translation_dataset(data_path, tokenizer=None, num_shots=5):
|
108 |
train_data_file = data_path.replace(".tsv", "-train.tsv")
|
109 |
test_data_file = data_path.replace(".tsv", "-test.tsv")
|
|
|
135 |
)
|
136 |
|
137 |
if tokenizer:
|
138 |
+
translation_prompt = get_few_shot_prompt(datasets["train"], num_shots)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
139 |
|
140 |
def formatting_prompts_func(examples):
|
141 |
inputs = examples["chinese"]
|
|
|
157 |
texts = []
|
158 |
prompts = []
|
159 |
for input, output in zip(inputs, outputs):
|
160 |
+
prompt = translation_prompt.format(input=input)
|
161 |
messages[-1] = {"role": "user", "content": prompt}
|
162 |
|
163 |
prompt = tokenizer.apply_chat_template(
|
|
|
431 |
plt.show()
|
432 |
|
433 |
|
434 |
+
def translate_via_openai(
|
435 |
+
text, translation_prompt, max_tokens=None, model="gpt-4o-mini", base_url=None
|
436 |
+
):
|
437 |
llm = ChatOpenAI(
|
438 |
+
model=model,
|
439 |
temperature=0,
|
440 |
+
max_tokens=max_tokens,
|
441 |
timeout=None,
|
442 |
max_retries=2,
|
443 |
base_url=base_url,
|
|
|
445 |
|
446 |
prompt = ChatPromptTemplate.from_messages(
|
447 |
[
|
448 |
+
(
|
449 |
+
"system",
|
450 |
+
"You are a helpful assistant that translates Chinese to English.",
|
451 |
+
),
|
452 |
(
|
453 |
"human",
|
454 |
+
translation_prompt,
|
455 |
),
|
456 |
]
|
457 |
)
|
|
|
462 |
"input": text,
|
463 |
}
|
464 |
)
|
465 |
+
|
466 |
return response.content
|
467 |
|
468 |
|
469 |
+
def eval_openai(num_shots, datasets, model="gpt-4o-mini", max_new_tokens=300):
|
470 |
+
translation_prompt = get_few_shot_prompt(datasets["train"], num_shots=num_shots)
|
471 |
+
eval_dataset = datasets["test"]
|
472 |
+
total = len(eval_dataset)
|
473 |
+
predictions = []
|
474 |
+
|
475 |
+
for i in tqdm(range(total)):
|
476 |
+
output = translate_via_openai(
|
477 |
+
eval_dataset["chinese"][i],
|
478 |
+
translation_prompt,
|
479 |
+
model=model,
|
480 |
+
max_tokens=max_new_tokens,
|
481 |
+
)
|
482 |
+
predictions.append(output)
|
483 |
+
|
484 |
+
return predictions
|
logs/openai-gpt-4o-mini.txt
ADDED
The diff for this file is too large to render.
See raw diff
|
|
logs/openai-gpt-4o.txt
ADDED
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
loading env vars from: D:\code\projects\rapget-translation\.env
|
2 |
+
Adding D:\code\projects\rapget-translation to sys.path
|
3 |
+
C:\Users\dongh\.conda\envs\rapget\Lib\site-packages\threadpoolctl.py:1214: RuntimeWarning:
|
4 |
+
Found Intel OpenMP ('libiomp') and LLVM OpenMP ('libomp') loaded at
|
5 |
+
the same time. Both libraries are known to be incompatible and this
|
6 |
+
can cause random crashes or deadlocks on Linux when loaded in the
|
7 |
+
same Python program.
|
8 |
+
Using threadpoolctl may cause crashes or deadlocks. For more
|
9 |
+
information and possible workarounds, please see
|
10 |
+
https://github.com/joblib/threadpoolctl/blob/master/multiple_openmp.md
|
11 |
+
|
12 |
+
warnings.warn(msg, RuntimeWarning)
|
13 |
+
[nltk_data] Downloading package wordnet to
|
14 |
+
[nltk_data] C:\Users\dongh\AppData\Roaming\nltk_data...
|
15 |
+
[nltk_data] Package wordnet is already up-to-date!
|
16 |
+
[nltk_data] Downloading package punkt to
|
17 |
+
[nltk_data] C:\Users\dongh\AppData\Roaming\nltk_data...
|
18 |
+
[nltk_data] Package punkt is already up-to-date!
|
19 |
+
[nltk_data] Downloading package omw-1.4 to
|
20 |
+
[nltk_data] C:\Users\dongh\AppData\Roaming\nltk_data...
|
21 |
+
[nltk_data] Package omw-1.4 is already up-to-date!
|
22 |
+
loading: D:\code\projects\rapget-translation\eval_modules\calc_repetitions.py
|
23 |
+
loading D:\code\projects\rapget-translation\llm_toolkit\translation_utils.py
|
24 |
+
[nltk_data] Downloading package wordnet to
|
25 |
+
[nltk_data] C:\Users\dongh\AppData\Roaming\nltk_data...
|
26 |
+
[nltk_data] Package wordnet is already up-to-date!
|
27 |
+
[nltk_data] Downloading package punkt to
|
28 |
+
[nltk_data] C:\Users\dongh\AppData\Roaming\nltk_data...
|
29 |
+
[nltk_data] Package punkt is already up-to-date!
|
30 |
+
[nltk_data] Downloading package omw-1.4 to
|
31 |
+
[nltk_data] C:\Users\dongh\AppData\Roaming\nltk_data...
|
32 |
+
[nltk_data] Package omw-1.4 is already up-to-date!
|
33 |
+
gpt-4o datasets/mac/mac.tsv results/mac-results_few_shots_openai.csv 300
|
34 |
+
Evaluating model: gpt-4o
|
35 |
+
loading train/test data files
|
36 |
+
DatasetDict({
|
37 |
+
train: Dataset({
|
38 |
+
features: ['chinese', 'english'],
|
39 |
+
num_rows: 4528
|
40 |
+
})
|
41 |
+
test: Dataset({
|
42 |
+
test: Dataset({
|
43 |
+
features: ['chinese', 'english'],
|
44 |
+
num_rows: 1133
|
45 |
+
})
|
46 |
+
})
|
47 |
+
--------------------------------------------------
|
48 |
+
chinese: 老耿端起枪,眯缝起一只三角眼,一搂扳机响了枪,冰雹般的金麻雀劈哩啪啦往下落,铁砂子在柳枝间飞迸着,嚓嚓有声。
|
49 |
+
chinese: 老耿端起枪,眯缝起一只三角眼,一搂扳机响了枪,冰雹般的金麻雀劈哩啪啦往下落,铁砂子在柳枝间飞迸着,嚓嚓有声。
|
50 |
+
--------------------------------------------------
|
51 |
+
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.
|
52 |
+
*** Evaluating with num_shots: 0
|
53 |
+
*** Evaluating with num_shots: 0
|
54 |
+
100%|█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 1133/1133 [28:52<00:00, 1.53s/it]
|
55 |
+
gpt-4o/shots-00 metrics: {'meteor': 0.3797419877414444, 'bleu_scores': {'bleu': 0.12054600115274576, 'precisions': [0.4395170970950372, 0.1657507850413931, 0.08008175399479747, 0.041705426356589144], 'brevity_penalty': 0.965191371371961, 'length_ratio': 0.965783371977476, 'translation_length': 29157, 'reference_length': 30190}, 'rouge_scores': {'rouge1': 0.42488525198918325, 'rouge2': 0.17659595999851255, 'rougeL': 0.37036814222422193, 'rougeLsum': 0.37043557409027883}, 'accuracy': 0.00088261253309797, 'correct_ids': [77]}
|
56 |
+
*** Evaluating with num_shots: 1
|
57 |
+
100%|█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 1133/1133 [22:44<00:00, 1.20s/it]
|
58 |
+
gpt-4o/shots-01 metrics: {'meteor': 0.37588586538591867, 'bleu_scores': {'bleu': 0.12049862468096047, 'precisions': [0.4438186524872315, 0.16850617418861327, 0.08162258566387129, 0.043228692450813504], 'brevity_penalty': 0.9454338245859127, 'length_ratio': 0.9468698244451805, 'translation_length': 28586, 'reference_length': 30190}, 'rouge_scores': {'rouge1': 0.4200247346821462, 'rouge2': 0.17611482166851536, 'rougeL': 0.36555347015620193, 'rougeLsum': 0.36597227925335113}, 'accuracy': 0.00088261253309797, 'correct_ids': [77]}
|
59 |
+
*** Evaluating with num_shots: 3
|
60 |
+
100%|���████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 1133/1133 [38:45<00:00, 2.05s/it]
|
61 |
+
gpt-4o/shots-03 metrics: {'meteor': 0.3768512103553621, 'bleu_scores': {'bleu': 0.12408746322526747, 'precisions': [0.4504073680481757, 0.17455806915894748, 0.08641500730375952, 0.04606687515034881], 'brevity_penalty': 0.9329257300005195, 'length_ratio': 0.9350778403444849, 'translation_length': 28230, 'reference_length': 30190}, 'rouge_scores': {'rouge1': 0.42185440095437376, 'rouge2': 0.18099296897772787, 'rougeL': 0.36683121325656565572, 'rougeLsum': 0.36692420445626067}, 'accuracy': 0.00088261253309797, 'correct_ids': [77]}
|
62 |
+
*** Evaluating with num_shots: 5
|
63 |
+
100%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 1133/1133 [31:48<00:00, 1.68s/it]
|
64 |
+
gpt-4o/shots-05 metrics: {'meteor': 0.35772544915145654, 'bleu_scores': {'bleu': 0.12169683347842021, 'precisions': [0.45675271230826786, 0.1799429620658671, 0.0908092273892347, 0.04932145886344359], 'brevity_penalty': 0.8785850406914042, 'length_ratio': 0.8853925140775091, 'translation_length': 26730, 'reference_length': 30190}, 'rouge_scores': {'rouge1': 0.3989536343087876, 'rouge2': 0.17450105082463535, 'rougeL': 0.348320055666115, 'rougeLsum': 0.3483328999510906}, 'accuracy': 0.00088261253309797, 'correct_ids': [77]}
|
65 |
+
*** Evaluating with num_shots: 10
|
66 |
+
'rougeLsum': 0.3483328999510906}, 'accuracy': 0.00088261253309797, 'correct_ids': [77]}
|
67 |
+
*** Evaluating with num_shots: 10
|
68 |
+
'rougeLsum': 0.3483328999510906}, 'accuracy': 0.00088261253309797, 'correct_ids': [77]}
|
69 |
+
*** Evaluating with num_shots: 10
|
70 |
+
100%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 1133/1133 [33:48<00:00, 1.79s/it]
|
71 |
+
gpt-4o/shots-10 metrics: {'meteor': 0.3746444651189953, 'bleu_scores': {'bleu': 0.12498238983123719, 'precisions': [0.45538813929351135, 0.17677558937630558, 0.08810041971086585, 0.04747233145498034], 'brevity_penalty': 0.9226631755170949, 'length_ratio': 0.9255051341503809, 'translation_length': 27941, 'reference_length': 30190}, 'rouge_scores': {'rouge1': 0.42057276805902843, 'rouge2': 0.182701868068981, 'rougeL': 0.3668754130715727, 'rougeLsum': 0.3673183260659394}, 'accuracy': 0.00176522506619594, 'correct_ids': [77, 364]}
|
72 |
+
*** Evaluating with num_shots: 50
|
73 |
+
100%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 1133/1133 [38:15<00:00, 2.03s/it]
|
74 |
+
gpt-4o/shots-50 metrics: {'meteor': 0.40413933252744955, 'bleu_scores': {'bleu': 0.13782450337569063, 'precisions': [0.4695234708392603, 0.19261125727201986, 0.09873251410464487, 0.05424823410696267], 'brevity_penalty': 0.9290310787259491, 'length_ratio': 0.9314342497515734, 'translation_length': 28120, 'reference_length': 30190}, 'rouge_scores': {'rouge1': 0.44343703034704307, 'rouge2': 0.20310004059554654, 'rougeL': 0.3908878454222482, 'rougeLsum': 0.39082492657743595}, 'accuracy': 0.00353045013239188, 'correct_ids': [77, 364, 567, 1000]}
|
notebooks/00b_Data Analysis_Few_Shots.ipynb
CHANGED
@@ -1,3 +1,3 @@
|
|
1 |
version https://git-lfs.github.com/spec/v1
|
2 |
-
oid sha256:
|
3 |
-
size
|
|
|
1 |
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:4062aa5271a5e14210e73d9ce344cb49dcbb126429fa370c68f8e38725840121
|
3 |
+
size 593498
|
notebooks/01b_Few-shot_Prompting_RTX4080.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: d:\\code\\projects\\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: d:\\code\\projects\\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 True datasets/mac/mac.tsv results/mac-results_few_shots_4bit.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+cu124\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: C:\\Users\\dongh\\.conda\\envs\\rapget\\Lib\\site-packages\n","Requires: filelock, fsspec, jinja2, networkx, sympy, typing-extensions\n","Required-by: accelerate, bitsandbytes, 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: C:\\Users\\dongh\\.conda\\envs\\rapget\\Lib\\site-packages\n","Requires: filelock, huggingface-hub, numpy, packaging, pyyaml, regex, requests, safetensors, tokenizers, tqdm\n","Required-by: peft\n","CPU times: total: 0 ns\n","Wall time: 6.94 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":["c:\\Users\\dongh\\.conda\\envs\\rapget\\Lib\\site-packages\\threadpoolctl.py:1214: RuntimeWarning: \n","Found Intel OpenMP ('libiomp') and LLVM OpenMP ('libomp') loaded at\n","the same time. Both libraries are known to be incompatible and this\n","can cause random crashes or deadlocks on Linux when loaded in the\n","same Python program.\n","Using threadpoolctl may cause crashes or deadlocks. For more\n","information and possible workarounds, please see\n"," https://github.com/joblib/threadpoolctl/blob/master/multiple_openmp.md\n","\n"," warnings.warn(msg, RuntimeWarning)\n","[nltk_data] Downloading package wordnet to\n","[nltk_data] C:\\Users\\dongh\\AppData\\Roaming\\nltk_data...\n","[nltk_data] Package wordnet is already up-to-date!\n","[nltk_data] Downloading package punkt to\n","[nltk_data] C:\\Users\\dongh\\AppData\\Roaming\\nltk_data...\n","[nltk_data] Package punkt is already up-to-date!\n","[nltk_data] Downloading package omw-1.4 to\n","[nltk_data] C:\\Users\\dongh\\AppData\\Roaming\\nltk_data...\n","[nltk_data] Package omw-1.4 is already up-to-date!\n"]},{"name":"stdout","output_type":"stream","text":["loading: d:\\code\\projects\\rapget-translation\\eval_modules\\calc_repetitions.py\n","loading d:\\code\\projects\\rapget-translation\\llm_toolkit\\translation_utils.py\n"]},{"name":"stderr","output_type":"stream","text":["[nltk_data] Downloading package wordnet to\n","[nltk_data] C:\\Users\\dongh\\AppData\\Roaming\\nltk_data...\n","[nltk_data] Package wordnet is already up-to-date!\n","[nltk_data] Downloading package punkt to\n","[nltk_data] C:\\Users\\dongh\\AppData\\Roaming\\nltk_data...\n","[nltk_data] Package punkt is already up-to-date!\n","[nltk_data] Downloading package omw-1.4 to\n","[nltk_data] C:\\Users\\dongh\\AppData\\Roaming\\nltk_data...\n","[nltk_data] Package omw-1.4 is already up-to-date!\n"]},{"name":"stdout","output_type":"stream","text":["CUDA is available, we have found 1 GPU(s)\n","NVIDIA GeForce RTX 4080 Laptop GPU\n","CUDA version: 12.4\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":"16faabb1083d4662b639c035b54844de","version_major":2,"version_minor":0},"text/plain":["tokenizer_config.json: 0%| | 0.00/1.67k [00:00<?, ?B/s]"]},"metadata":{},"output_type":"display_data"},{"name":"stderr","output_type":"stream","text":["c:\\Users\\dongh\\.conda\\envs\\rapget\\Lib\\site-packages\\huggingface_hub\\file_download.py:159: UserWarning: `huggingface_hub` cache-system uses symlinks by default to efficiently store duplicated files but your machine does not support them in C:\\Users\\dongh\\.cache\\huggingface\\hub\\models--01-ai--Yi-1.5-9B-Chat. Caching files will still work but in a degraded version that might require more space on your disk. This warning can be disabled by setting the `HF_HUB_DISABLE_SYMLINKS_WARNING` environment variable. For more details, see https://huggingface.co/docs/huggingface_hub/how-to-cache#limitations.\n","To support symlinks on Windows, you either need to activate Developer Mode or to run Python as an administrator. In order to see activate developer mode, see this article: https://docs.microsoft.com/en-us/windows/apps/get-started/enable-your-device-for-development\n"," warnings.warn(message)\n"]},{"data":{"application/vnd.jupyter.widget-view+json":{"model_id":"3316d03bf00d49c59537caf4fa45d683","version_major":2,"version_minor":0},"text/plain":["tokenizer.model: 0%| | 0.00/1.03M [00:00<?, ?B/s]"]},"metadata":{},"output_type":"display_data"},{"data":{"application/vnd.jupyter.widget-view+json":{"model_id":"8ad82b2bf7224459a56668b0b34660f6","version_major":2,"version_minor":0},"text/plain":["tokenizer.json: 0%| | 0.00/3.60M [00:00<?, ?B/s]"]},"metadata":{},"output_type":"display_data"},{"data":{"application/vnd.jupyter.widget-view+json":{"model_id":"654d3c4a90fe4011bee581af81770e36","version_major":2,"version_minor":0},"text/plain":["special_tokens_map.json: 0%| | 0.00/567 [00:00<?, ?B/s]"]},"metadata":{},"output_type":"display_data"},{"data":{"application/vnd.jupyter.widget-view+json":{"model_id":"bdb46ebad4fe48e3b17e44b372f4c33b","version_major":2,"version_minor":0},"text/plain":["config.json: 0%| | 0.00/661 [00:00<?, ?B/s]"]},"metadata":{},"output_type":"display_data"},{"data":{"application/vnd.jupyter.widget-view+json":{"model_id":"f5bf514086a34a99a3e83d8e3f6bf99e","version_major":2,"version_minor":0},"text/plain":["model.safetensors.index.json: 0%| | 0.00/35.8k [00:00<?, ?B/s]"]},"metadata":{},"output_type":"display_data"},{"data":{"application/vnd.jupyter.widget-view+json":{"model_id":"2c63583627a14301949f4696a0777dbd","version_major":2,"version_minor":0},"text/plain":["Downloading shards: 0%| | 0/4 [00:00<?, ?it/s]"]},"metadata":{},"output_type":"display_data"},{"data":{"application/vnd.jupyter.widget-view+json":{"model_id":"8c56c07a67ac477194351791eddc8069","version_major":2,"version_minor":0},"text/plain":["model-00001-of-00004.safetensors: 0%| | 0.00/4.93G [00:00<?, ?B/s]"]},"metadata":{},"output_type":"display_data"},{"data":{"application/vnd.jupyter.widget-view+json":{"model_id":"cccfaf200fe340628649245e87205e5a","version_major":2,"version_minor":0},"text/plain":["model-00002-of-00004.safetensors: 0%| | 0.00/4.98G [00:00<?, ?B/s]"]},"metadata":{},"output_type":"display_data"},{"data":{"application/vnd.jupyter.widget-view+json":{"model_id":"780839610e2245a99a2044f7108dce4a","version_major":2,"version_minor":0},"text/plain":["model-00003-of-00004.safetensors: 0%| | 0.00/4.97G [00:00<?, ?B/s]"]},"metadata":{},"output_type":"display_data"},{"data":{"application/vnd.jupyter.widget-view+json":{"model_id":"12df1cda8a4c445cb7c96ccbe8c34921","version_major":2,"version_minor":0},"text/plain":["model-00004-of-00004.safetensors: 0%| | 0.00/2.78G [00:00<?, ?B/s]"]},"metadata":{},"output_type":"display_data"},{"data":{"application/vnd.jupyter.widget-view+json":{"model_id":"a37aa5117f044c49806ae9cac830d440","version_major":2,"version_minor":0},"text/plain":["Loading checkpoint shards: 0%| | 0/4 [00:00<?, ?it/s]"]},"metadata":{},"output_type":"display_data"},{"data":{"application/vnd.jupyter.widget-view+json":{"model_id":"61ea7704789942ce9ef72ec3f6f1d9be","version_major":2,"version_minor":0},"text/plain":["generation_config.json: 0%| | 0.00/132 [00:00<?, ?B/s]"]},"metadata":{},"output_type":"display_data"},{"name":"stderr","output_type":"stream","text":["Some parameters are on the meta device device because they were offloaded to the cpu.\n"]}],"source":["model, tokenizer = load_model(model_name)"]},{"cell_type":"code","execution_count":10,"metadata":{},"outputs":[{"name":"stdout","output_type":"stream","text":["loading d:\\code\\projects\\rapget-translation\\llm_toolkit\\translation_utils.py\n"]},{"name":"stderr","output_type":"stream","text":["[nltk_data] Downloading package wordnet to\n","[nltk_data] C:\\Users\\dongh\\AppData\\Roaming\\nltk_data...\n","[nltk_data] Package wordnet is already up-to-date!\n","[nltk_data] Downloading package punkt to\n","[nltk_data] C:\\Users\\dongh\\AppData\\Roaming\\nltk_data...\n","[nltk_data] Package punkt is already up-to-date!\n","[nltk_data] Downloading package omw-1.4 to\n","[nltk_data] C:\\Users\\dongh\\AppData\\Roaming\\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"]},{"data":{"application/vnd.jupyter.widget-view+json":{"model_id":"f37f3ccde5c541f5a5c9eeb2df64613c","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":"d0cd7340999e45179a7ead59e426b7f7","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":11,"metadata":{},"outputs":[{"data":{"text/plain":["('那刘姥姥先听见告艰苦,只当是没想头了, 又听见给他二十两银子,喜的眉开眼笑道:“我们也知道艰难的,但只俗语说的:‘瘦死的骆驼比马还大’呢。',\n"," '后来她不挣扎了,对我说,混蛋,你要把我怎么办。')"]},"execution_count":11,"metadata":{},"output_type":"execute_result"}],"source":["dataset[\"test\"][\"chinese\"][260], dataset[\"test\"][\"chinese\"][908]"]},{"cell_type":"code","execution_count":12,"metadata":{},"outputs":[],"source":["eval_dataset = dataset[\"test\"].select([260, 908])"]},{"cell_type":"code","execution_count":13,"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":14,"metadata":{},"outputs":[{"name":"stderr","output_type":"stream","text":[" 0%| | 0/2 [00:00<?, ?it/s]c:\\Users\\dongh\\.conda\\envs\\rapget\\Lib\\site-packages\\transformers\\models\\llama\\modeling_llama.py:603: UserWarning: 1Torch was not compiled with flash attention. (Triggered internally at C:\\actions-runner\\_work\\pytorch\\pytorch\\builder\\windows\\pytorch\\aten\\src\\ATen\\native\\transformers\\cuda\\sdp_utils.cpp:555.)\n"," attn_output = torch.nn.functional.scaled_dot_product_attention(\n"," 50%|█████ | 1/2 [12:18<12:18, 738.30s/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 translation should be the same as the input text without any additional explanation or reasoning.\\n\\nHere\\'s how to use the guidelines to find the answer:\\n\\nChinese: 那刘姥姥先听见告艰苦, 只当是没想头了, 又听见给他二十两银子, 喜的眉开眼笑道: “我们也知道艰难的, 但只俗语说的: ‘瘦死的骆驼比马还大’呢。\\n\\n1. Read the Chinese sentence carefully.\\n2. Identify any incomplete or unclear parts of the sentence.\\n3. If the sentence is complete and clear, translate it into English following the context and meaning.\\n4. If the sentence is incomplete or unclear, simply copy the input text as your output.\\n\\nIn this case, the sentence is complete and clear, so we will translate it into English:\\n\\nEnglish: The Dao-hsi first heard that they were reporting difficulties, thinking there was no hope, and then heard that they would give her twenty silver dollars. She was overjoyed, smiling broadly and saying, \"We know the difficulties, but as the saying goes, \\'A camel that\\'s lost its fat is still bigger than a horse.\\'\"']\n"]},{"name":"stderr","output_type":"stream","text":["100%|██████████| 2/2 [24:19<00:00, 729.62s/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":15,"metadata":{},"outputs":[{"name":"stdout","output_type":"stream","text":["loading d:\\code\\projects\\rapget-translation\\llm_toolkit\\translation_utils.py\n"]},{"name":"stderr","output_type":"stream","text":["[nltk_data] Downloading package wordnet to\n","[nltk_data] C:\\Users\\dongh\\AppData\\Roaming\\nltk_data...\n","[nltk_data] Package wordnet is already up-to-date!\n","[nltk_data] Downloading package punkt to\n","[nltk_data] C:\\Users\\dongh\\AppData\\Roaming\\nltk_data...\n","[nltk_data] Package punkt is already up-to-date!\n","[nltk_data] Downloading package omw-1.4 to\n","[nltk_data] C:\\Users\\dongh\\AppData\\Roaming\\nltk_data...\n","[nltk_data] Package omw-1.4 is already up-to-date!\n"]},{"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 translation should be the same as the input text without any additional explanation or reasoning.\\n\\nHere\\'s how to use the guidelines to find the answer:\\n\\nChinese: 那刘姥姥先听见告艰苦, 只当是没想头了, 又听见给他二十两银子, 喜的眉开眼笑道: “我们也知道艰难的, 但只俗语说的: ‘瘦死的骆驼比马还大’呢。\\n\\n1. Read the Chinese sentence carefully.\\n2. Identify any incomplete or unclear parts of the sentence.\\n3. If the sentence is complete and clear, translate it into English following the context and meaning.\\n4. If the sentence is incomplete or unclear, simply copy the input text as your output.\\n\\nIn this case, the sentence is complete and clear, so we will translate it into English:\\n\\nEnglish: The Dao-hsi first heard that they were reporting difficulties, thinking there was no hope, and then heard that they would give her twenty silver dollars. She was overjoyed, smiling broadly and saying, \"We know the difficulties, but as the saying goes, \\'A camel that\\'s lost its fat is still bigger than a horse.\\'\"', 'Later, she stopped struggling and asked me, \"Asshole, what are you going to do with me?\"']\n"]}],"source":["print(predictions)"]},{"cell_type":"code","execution_count":16,"metadata":{},"outputs":[{"name":"stdout","output_type":"stream","text":["loading d:\\code\\projects\\rapget-translation\\llm_toolkit\\translation_utils_v1.py\n"]},{"name":"stderr","output_type":"stream","text":["[nltk_data] Downloading package wordnet to\n","[nltk_data] C:\\Users\\dongh\\AppData\\Roaming\\nltk_data...\n","[nltk_data] Package wordnet is already up-to-date!\n","[nltk_data] Downloading package punkt to\n","[nltk_data] C:\\Users\\dongh\\AppData\\Roaming\\nltk_data...\n","[nltk_data] Package punkt is already up-to-date!\n","[nltk_data] Downloading package omw-1.4 to\n","[nltk_data] C:\\Users\\dongh\\AppData\\Roaming\\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"]},{"data":{"application/vnd.jupyter.widget-view+json":{"model_id":"9b93dc2e072345bab26e7dc4b1170e13","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":"a9adb136bd474eba99a718a6bef0b953","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":["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":17,"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":25,"metadata":{},"outputs":[{"data":{"text/plain":["{'meteor': 0.5158944459316517,\n"," 'bleu_scores': {'bleu': 0.08754836694338668,\n"," 'precisions': [0.23318385650224216,\n"," 0.09502262443438914,\n"," 0.0639269406392694,\n"," 0.041474654377880185],\n"," 'brevity_penalty': 1.0,\n"," 'length_ratio': 2.207920792079208,\n"," 'translation_length': 223,\n"," 'reference_length': 101},\n"," 'rouge_scores': {'rouge1': 0.4382566585956416,\n"," 'rouge2': 0.2634032634032634,\n"," 'rougeL': 0.387409200968523,\n"," 'rougeLsum': 0.4170702179176755},\n"," 'accuracy': 0.0}"]},"execution_count":25,"metadata":{},"output_type":"execute_result"}],"source":["calc_metrics(eval_dataset[\"english\"], predictions)"]},{"cell_type":"code","execution_count":18,"metadata":{},"outputs":[{"name":"stderr","output_type":"stream","text":[" 50%|█████ | 1/2 [11:04<11:04, 664.47s/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 Huarou) - a character\\'s name in a classic Chinese novel, \"Dream of the Red Chamber\"\\n2. 先听见告艰苦 (first heard of the hardship)\\n3. 只当是没想头了 (just thought it was nonsense)\\n4. 又听见给他二十两银子 (then heard that he received twenty silver pieces)\\n5. 喜的眉开眼笑 (very happy, smiling broadly)\\n6. “我们也知道艰难的 (we also know the difficulties)\\n7. 但只俗语说的 (but as the saying goes)\\n8. ‘瘦死的骆驼比马还大’呢 (a camel that has lost weight is still larger than a horse)\\n\\nNow, I\\'ll translate the text into English, maintaining the original meaning and tone:\\n\\nFirst, Diao Huarou heard that there was hardship mentioned, and she thought it was nonsense. Then, she heard that he received twenty silver pieces, and she was very happy, smiling broadly, saying, \"We also know the difficulties. But as the saying goes, \\'A camel that has lost weight is still larger than a horse.\\'\"']\n"]},{"name":"stderr","output_type":"stream","text":["100%|██████████| 2/2 [22:04<00:00, 662.38s/it]\n"]},{"data":{"text/plain":["['First, I\\'ll identify the key phrases and words in the Chinese text:\\n\\n1. 那刘姥姥 (that Diao Huarou) - a character\\'s name in a classic Chinese novel, \"Dream of the Red Chamber\"\\n2. 先听见告艰苦 (first heard of the hardship)\\n3. 只当是没想头了 (just thought it was nonsense)\\n4. 又听见给他二十两银子 (then heard that he received twenty silver pieces)\\n5. 喜的眉开眼笑 (very happy, smiling broadly)\\n6. “我们也知道艰难的 (we also know the difficulties)\\n7. 但只俗语说的 (but as the saying goes)\\n8. ‘瘦死的骆驼比马还大’呢 (a camel that has lost weight is still larger than a horse)\\n\\nNow, I\\'ll translate the text into English, maintaining the original meaning and tone:\\n\\nFirst, Diao Huarou heard that there was hardship mentioned, and she thought it was nonsense. Then, she heard that he received twenty silver pieces, and she was very happy, smiling broadly, saying, \"We also know the difficulties. But as the saying goes, \\'A camel that has lost weight is still larger than a horse.\\'\"',\n"," 'Later, she stopped struggling and said to me, \"Son of a bitch, what are you going to do with me?\"']"]},"execution_count":18,"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":19,"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 Huarou) - a character\\'s name in a classic Chinese novel, \"Dream of the Red Chamber\"\\n2. 先听见告艰苦 (first heard of the hardship)\\n3. 只当是没想头了 (just thought it was nonsense)\\n4. 又听见给他二十两银子 (then heard that he received twenty silver pieces)\\n5. 喜的眉开眼笑 (very happy, smiling broadly)\\n6. “我们也知道艰难的 (we also know the difficulties)\\n7. 但只俗语说的 (but as the saying goes)\\n8. ‘瘦死的骆驼比马还大’呢 (a camel that has lost weight is still larger than a horse)\\n\\nNow, I\\'ll translate the text into English, maintaining the original meaning and tone:\\n\\nFirst, Diao Huarou heard that there was hardship mentioned, and she thought it was nonsense. Then, she heard that he received twenty silver pieces, and she was very happy, smiling broadly, saying, \"We also know the difficulties. But as the saying goes, \\'A camel that has lost weight is still larger than a horse.\\'\"', '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":20,"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":26,"metadata":{},"outputs":[{"data":{"text/plain":["{'meteor': 0.5153317672515252,\n"," 'bleu_scores': {'bleu': 0.08097031799100003,\n"," 'precisions': [0.21397379912663755,\n"," 0.09691629955947137,\n"," 0.057777777777777775,\n"," 0.03587443946188341],\n"," 'brevity_penalty': 1.0,\n"," 'length_ratio': 2.267326732673267,\n"," 'translation_length': 229,\n"," 'reference_length': 101},\n"," 'rouge_scores': {'rouge1': 0.4401123990165086,\n"," 'rouge2': 0.26690746045584757,\n"," 'rougeL': 0.38707411310151035,\n"," 'rougeLsum': 0.40533895328415875},\n"," 'accuracy': 0.0}"]},"execution_count":26,"metadata":{},"output_type":"execute_result"}],"source":["calc_metrics(eval_dataset_v1[\"english\"], predictions_v1)"]},{"cell_type":"code","execution_count":21,"metadata":{},"outputs":[{"name":"stdout","output_type":"stream","text":["loading train/test data files\n"]},{"data":{"application/vnd.jupyter.widget-view+json":{"model_id":"22e0eed1c971459497f30cf1141317f2","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":"3925ff53b4c34183a8427d900f2f51f3","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":22,"metadata":{},"outputs":[{"name":"stderr","output_type":"stream","text":[" 50%|█████ | 1/2 [11:33<11:33, 693.07s/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 [22:34<00:00, 677.33s/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 Chinese sentence and there is no need for additional explanation or reasoning, the output is the same as the input:\\n\\nEnglish: 后来她不挣扎了, 对我说, 混蛋, 你要把我怎么办。']"]},"execution_count":22,"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":23,"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 Chinese 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":24,"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)))"]},{"cell_type":"code","execution_count":27,"metadata":{},"outputs":[{"data":{"text/plain":["{'meteor': 0.21319948962320656,\n"," 'bleu_scores': {'bleu': 0.10039676162391267,\n"," 'precisions': [0.32075471698113206,\n"," 0.11538461538461539,\n"," 0.06862745098039216,\n"," 0.04],\n"," 'brevity_penalty': 1.0,\n"," 'length_ratio': 1.0495049504950495,\n"," 'translation_length': 106,\n"," 'reference_length': 101},\n"," 'rouge_scores': {'rouge1': 0.27369956246961596,\n"," 'rouge2': 0.07563025210084033,\n"," 'rougeL': 0.20450494247285692,\n"," 'rougeLsum': 0.20450494247285692},\n"," 'accuracy': 0.0}"]},"execution_count":27,"metadata":{},"output_type":"execute_result"}],"source":["calc_metrics(eval_dataset_v2[\"english\"], predictions_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}
|
notebooks/01c_Few-shot_Prompting_OpenAI.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: d:\\code\\projects\\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: d:\\code\\projects\\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 True datasets/mac/mac.tsv results/mac-results_few_shots_4bit.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+cu124\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: C:\\Users\\dongh\\.conda\\envs\\rapget\\Lib\\site-packages\n","Requires: filelock, fsspec, jinja2, networkx, sympy, typing-extensions\n","Required-by: accelerate, bitsandbytes, 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: C:\\Users\\dongh\\.conda\\envs\\rapget\\Lib\\site-packages\n","Requires: filelock, huggingface-hub, numpy, packaging, pyyaml, regex, requests, safetensors, tokenizers, tqdm\n","Required-by: peft\n","CPU times: total: 0 ns\n","Wall time: 8.35 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":["c:\\Users\\dongh\\.conda\\envs\\rapget\\Lib\\site-packages\\threadpoolctl.py:1214: RuntimeWarning: \n","Found Intel OpenMP ('libiomp') and LLVM OpenMP ('libomp') loaded at\n","the same time. Both libraries are known to be incompatible and this\n","can cause random crashes or deadlocks on Linux when loaded in the\n","same Python program.\n","Using threadpoolctl may cause crashes or deadlocks. For more\n","information and possible workarounds, please see\n"," https://github.com/joblib/threadpoolctl/blob/master/multiple_openmp.md\n","\n"," warnings.warn(msg, RuntimeWarning)\n","[nltk_data] Downloading package wordnet to\n","[nltk_data] C:\\Users\\dongh\\AppData\\Roaming\\nltk_data...\n","[nltk_data] Package wordnet is already up-to-date!\n","[nltk_data] Downloading package punkt to\n","[nltk_data] C:\\Users\\dongh\\AppData\\Roaming\\nltk_data...\n","[nltk_data] Package punkt is already up-to-date!\n","[nltk_data] Downloading package omw-1.4 to\n","[nltk_data] C:\\Users\\dongh\\AppData\\Roaming\\nltk_data...\n","[nltk_data] Package omw-1.4 is already up-to-date!\n"]},{"name":"stdout","output_type":"stream","text":["loading: d:\\code\\projects\\rapget-translation\\eval_modules\\calc_repetitions.py\n","loading d:\\code\\projects\\rapget-translation\\llm_toolkit\\translation_utils.py\n"]},{"name":"stderr","output_type":"stream","text":["[nltk_data] Downloading package wordnet to\n","[nltk_data] C:\\Users\\dongh\\AppData\\Roaming\\nltk_data...\n","[nltk_data] Package wordnet is already up-to-date!\n","[nltk_data] Downloading package punkt to\n","[nltk_data] C:\\Users\\dongh\\AppData\\Roaming\\nltk_data...\n","[nltk_data] Package punkt is already up-to-date!\n","[nltk_data] Downloading package omw-1.4 to\n","[nltk_data] C:\\Users\\dongh\\AppData\\Roaming\\nltk_data...\n","[nltk_data] Package omw-1.4 is already up-to-date!\n"]},{"name":"stdout","output_type":"stream","text":["CUDA is available, we have found 1 GPU(s)\n","NVIDIA GeForce RTX 4080 Laptop GPU\n","CUDA version: 12.4\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 train/test data files\n","DatasetDict({\n"," train: Dataset({\n"," features: ['chinese', 'english'],\n"," num_rows: 4528\n"," })\n"," test: Dataset({\n"," features: ['chinese', 'english'],\n"," num_rows: 1133\n"," })\n","})\n"]}],"source":["datasets = load_translation_dataset(data_path)"]},{"cell_type":"code","execution_count":8,"metadata":{},"outputs":[],"source":["os.getenv(\"OPENAI_MODEL\")\n","base_url = os.getenv(\"OPENAI_BASE_URL\") or None"]},{"cell_type":"code","execution_count":9,"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","chinese: 后来她不挣扎了,对我说,混蛋,你要把我怎么办。\n","--------------------------------------------------\n","english: After a while, she no longer struggled and said, You bastard! What are you going to do with me?\n"]}],"source":["eval_dataset = datasets[\"test\"].select([260, 908])\n","print_row_details(eval_dataset.to_pandas(), range(len(eval_dataset)))"]},{"cell_type":"code","execution_count":10,"metadata":{},"outputs":[{"name":"stdout","output_type":"stream","text":["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: {input}\n","English:\n"]}],"source":["translation_prompt = get_few_shot_prompt(datasets[\"train\"], num_shots=5)\n","print(translation_prompt)"]},{"cell_type":"code","execution_count":11,"metadata":{},"outputs":[{"name":"stdout","output_type":"stream","text":["\u001b[32;1m\u001b[1;3m[chain/start]\u001b[0m \u001b[1m[chain:RunnableSequence] Entering Chain run with input:\n","\u001b[0m{\n"," \"input\": \"那刘姥姥先听见告艰苦,只当是没想头了, 又听见给他二十两银子,喜的眉开眼笑道:“我们也知道艰难的,但只俗语说的:‘瘦死的骆驼比马还大’呢。\"\n","}\n","\u001b[32;1m\u001b[1;3m[chain/start]\u001b[0m \u001b[1m[chain:RunnableSequence > prompt:ChatPromptTemplate] Entering Prompt run with input:\n","\u001b[0m{\n"," \"input\": \"那刘姥姥先听见告艰苦,只当是没想头了, 又听见给他二十两银子,喜的眉开眼笑道:“我们也知道艰难的,但只俗语说的:‘瘦死的骆驼比马还大’呢。\"\n","}\n","\u001b[36;1m\u001b[1;3m[chain/end]\u001b[0m \u001b[1m[chain:RunnableSequence > prompt:ChatPromptTemplate] [1ms] Exiting Prompt run with output:\n","\u001b[0m[outputs]\n","\u001b[32;1m\u001b[1;3m[llm/start]\u001b[0m \u001b[1m[chain:RunnableSequence > llm:ChatOpenAI] Entering LLM run with input:\n","\u001b[0m{\n"," \"prompts\": [\n"," \"System: You are a helpful assistant that translates Chinese to English.\\nHuman: 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\\nExample Translations:\\nChinese: 全仗着狐仙搭救。\\nEnglish: Because I was protected by a fox fairy.\\nChinese: 过后,表哥告诉她俩,这人是导演,在外国留过学的,还会编剧,今天拍的这戏,就是他自编自导的。\\nEnglish: 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.\\nChinese: 这凤姐忽然想起一件事来,便向窗外叫:“蓉儿回来!”\\nEnglish: Xi-feng suddenly seemed to remember something, and called to him through the window, 'Rong, come back!'\\nChinese: 三个老红卫兵走到叶文洁面前,面对着她站成了一排——当年,她们也是这样面对叶哲泰的——试图再现那早已忘却的尊严,但她们当年那魔鬼般的精神力量显然已荡然无存。\\nEnglish: 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.\\nChinese: 程先生照单全收,都是一个“谢”字,然后问王琦瑶有什么话说。\\nEnglish: 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\\nChinese: 那刘姥姥先听见告艰苦,只当是没想头了, 又听见给他二十两银子,喜的眉开眼笑道:“我们也知道艰难的,但只俗语说的:‘瘦死的骆驼比马还大’呢。\\nEnglish:\"\n"," ]\n","}\n","\u001b[36;1m\u001b[1;3m[llm/end]\u001b[0m \u001b[1m[chain:RunnableSequence > llm:ChatOpenAI] [1.45s] Exiting LLM run with output:\n","\u001b[0m{\n"," \"generations\": [\n"," [\n"," {\n"," \"text\": \"That Liu Laolao first heard about the hardships and thought it was hopeless, then heard about the twenty taels of silver and smiled with joy, saying, \\\"We also know about difficulties, but as the saying goes: 'A dead camel is still bigger than a horse.'\\\"\",\n"," \"generation_info\": {\n"," \"finish_reason\": \"stop\",\n"," \"logprobs\": null\n"," },\n"," \"type\": \"ChatGeneration\",\n"," \"message\": {\n"," \"lc\": 1,\n"," \"type\": \"constructor\",\n"," \"id\": [\n"," \"langchain\",\n"," \"schema\",\n"," \"messages\",\n"," \"AIMessage\"\n"," ],\n"," \"kwargs\": {\n"," \"content\": \"That Liu Laolao first heard about the hardships and thought it was hopeless, then heard about the twenty taels of silver and smiled with joy, saying, \\\"We also know about difficulties, but as the saying goes: 'A dead camel is still bigger than a horse.'\\\"\",\n"," \"response_metadata\": {\n"," \"token_usage\": {\n"," \"completion_tokens\": 56,\n"," \"prompt_tokens\": 484,\n"," \"total_tokens\": 540\n"," },\n"," \"model_name\": \"gpt-4o-mini-2024-07-18\",\n"," \"system_fingerprint\": \"fp_0f03d4f0ee\",\n"," \"finish_reason\": \"stop\",\n"," \"logprobs\": null\n"," },\n"," \"type\": \"ai\",\n"," \"id\": \"run-1c7d8c24-e2d6-4ba3-b87a-16101fb1ce80-0\",\n"," \"usage_metadata\": {\n"," \"input_tokens\": 484,\n"," \"output_tokens\": 56,\n"," \"total_tokens\": 540\n"," },\n"," \"tool_calls\": [],\n"," \"invalid_tool_calls\": []\n"," }\n"," }\n"," }\n"," ]\n"," ],\n"," \"llm_output\": {\n"," \"token_usage\": {\n"," \"completion_tokens\": 56,\n"," \"prompt_tokens\": 484,\n"," \"total_tokens\": 540\n"," },\n"," \"model_name\": \"gpt-4o-mini-2024-07-18\",\n"," \"system_fingerprint\": \"fp_0f03d4f0ee\"\n"," },\n"," \"run\": null\n","}\n","\u001b[36;1m\u001b[1;3m[chain/end]\u001b[0m \u001b[1m[chain:RunnableSequence] [1.46s] Exiting Chain run with output:\n","\u001b[0m[outputs]\n"]},{"data":{"text/plain":["'That Liu Laolao first heard about the hardships and thought it was hopeless, then heard about the twenty taels of silver and smiled with joy, saying, \"We also know about difficulties, but as the saying goes: \\'A dead camel is still bigger than a horse.\\'\"'"]},"execution_count":11,"metadata":{},"output_type":"execute_result"}],"source":["from langchain_core.globals import set_debug\n","\n","set_debug(True)\n","\n","translate_via_openai(eval_dataset[\"chinese\"][0], translation_prompt, max_tokens=max_new_tokens)"]},{"cell_type":"code","execution_count":12,"metadata":{},"outputs":[],"source":["datasets[\"test\"] = eval_dataset"]},{"cell_type":"code","execution_count":13,"metadata":{},"outputs":[{"name":"stderr","output_type":"stream","text":[" 0%| | 0/2 [00:00<?, ?it/s]"]},{"name":"stdout","output_type":"stream","text":["\u001b[32;1m\u001b[1;3m[chain/start]\u001b[0m \u001b[1m[chain:RunnableSequence] Entering Chain run with input:\n","\u001b[0m{\n"," \"input\": \"那刘姥姥先听见告艰苦,只当是没想头了, 又听见给他二十两银子,喜的眉开眼笑道:“我们也知道艰难的,但只俗语说的:‘瘦死的骆驼比马还大’呢。\"\n","}\n","\u001b[32;1m\u001b[1;3m[chain/start]\u001b[0m \u001b[1m[chain:RunnableSequence > prompt:ChatPromptTemplate] Entering Prompt run with input:\n","\u001b[0m{\n"," \"input\": \"那刘姥姥先听见告艰苦,只当是没想头了, 又听见给他二十两银子,喜的眉开眼笑道:“我们也知道艰难的,但只俗语说的:‘瘦死的骆驼比马还大’呢。\"\n","}\n","\u001b[36;1m\u001b[1;3m[chain/end]\u001b[0m \u001b[1m[chain:RunnableSequence > prompt:ChatPromptTemplate] [1ms] Exiting Prompt run with output:\n","\u001b[0m[outputs]\n","\u001b[32;1m\u001b[1;3m[llm/start]\u001b[0m \u001b[1m[chain:RunnableSequence > llm:ChatOpenAI] Entering LLM run with input:\n","\u001b[0m{\n"," \"prompts\": [\n"," \"System: You are a helpful assistant that translates Chinese to English.\\nHuman: 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\\nExample Translations:\\nChinese: 全仗着狐仙搭救。\\nEnglish: Because I was protected by a fox fairy.\\nChinese: 过后,表哥告诉她俩,这人是导演,在外国留过学的,还会编剧,今天拍的这戏,就是他自编自导的。\\nEnglish: 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.\\nChinese: 这凤姐忽然想起一件事来,便向窗外叫:“蓉儿回来!”\\nEnglish: Xi-feng suddenly seemed to remember something, and called to him through the window, 'Rong, come back!'\\nChinese: 三个老红卫兵走到叶文洁面前,面对着她站成了一排——当年,她们也是这样面对叶哲泰的——试图再现那早已忘却的尊严,但她们当年那魔鬼般的精神力量显然已荡然无存。\\nEnglish: 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.\\nChinese: 程先生照单全收,都是一个“谢”字,然后问王琦瑶有什么话说。\\nEnglish: 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\\nChinese: 那刘姥姥先听见告艰苦,只当是没想头了, 又听见给他二十两银子,喜的眉开眼笑道:“我们也知道艰难的,但只俗语说的:‘瘦死的骆驼比马还大’呢。\\nEnglish:\"\n"," ]\n","}\n"]},{"name":"stderr","output_type":"stream","text":[" 50%|█████ | 1/2 [00:02<00:02, 2.31s/it]"]},{"name":"stdout","output_type":"stream","text":["\u001b[36;1m\u001b[1;3m[llm/end]\u001b[0m \u001b[1m[chain:RunnableSequence > llm:ChatOpenAI] [1.27s] Exiting LLM run with output:\n","\u001b[0m{\n"," \"generations\": [\n"," [\n"," {\n"," \"text\": \"That Liu Laolao first heard about the hardships and thought it was hopeless, then heard about the twenty taels of silver and smiled with joy, saying, \\\"We also know it's difficult, but as the saying goes: 'A dead camel is still bigger than a horse.'\\\"\",\n"," \"generation_info\": {\n"," \"finish_reason\": \"stop\",\n"," \"logprobs\": null\n"," },\n"," \"type\": \"ChatGeneration\",\n"," \"message\": {\n"," \"lc\": 1,\n"," \"type\": \"constructor\",\n"," \"id\": [\n"," \"langchain\",\n"," \"schema\",\n"," \"messages\",\n"," \"AIMessage\"\n"," ],\n"," \"kwargs\": {\n"," \"content\": \"That Liu Laolao first heard about the hardships and thought it was hopeless, then heard about the twenty taels of silver and smiled with joy, saying, \\\"We also know it's difficult, but as the saying goes: 'A dead camel is still bigger than a horse.'\\\"\",\n"," \"response_metadata\": {\n"," \"token_usage\": {\n"," \"completion_tokens\": 56,\n"," \"prompt_tokens\": 484,\n"," \"total_tokens\": 540\n"," },\n"," \"model_name\": \"gpt-4o-mini-2024-07-18\",\n"," \"system_fingerprint\": \"fp_9b0abffe81\",\n"," \"finish_reason\": \"stop\",\n"," \"logprobs\": null\n"," },\n"," \"type\": \"ai\",\n"," \"id\": \"run-68581936-c5f8-4d63-a40a-9ae04e88d234-0\",\n"," \"usage_metadata\": {\n"," \"input_tokens\": 484,\n"," \"output_tokens\": 56,\n"," \"total_tokens\": 540\n"," },\n"," \"tool_calls\": [],\n"," \"invalid_tool_calls\": []\n"," }\n"," }\n"," }\n"," ]\n"," ],\n"," \"llm_output\": {\n"," \"token_usage\": {\n"," \"completion_tokens\": 56,\n"," \"prompt_tokens\": 484,\n"," \"total_tokens\": 540\n"," },\n"," \"model_name\": \"gpt-4o-mini-2024-07-18\",\n"," \"system_fingerprint\": \"fp_9b0abffe81\"\n"," },\n"," \"run\": null\n","}\n","\u001b[36;1m\u001b[1;3m[chain/end]\u001b[0m \u001b[1m[chain:RunnableSequence] [1.28s] Exiting Chain run with output:\n","\u001b[0m[outputs]\n","\u001b[32;1m\u001b[1;3m[chain/start]\u001b[0m \u001b[1m[chain:RunnableSequence] Entering Chain run with input:\n","\u001b[0m{\n"," \"input\": \"后来她不挣扎了,对我说,混蛋,你要把我怎么办。\"\n","}\n","\u001b[32;1m\u001b[1;3m[chain/start]\u001b[0m \u001b[1m[chain:RunnableSequence > prompt:ChatPromptTemplate] Entering Prompt run with input:\n","\u001b[0m{\n"," \"input\": \"后来她不挣扎了,对我说,混蛋,你要把我怎么办。\"\n","}\n","\u001b[36;1m\u001b[1;3m[chain/end]\u001b[0m \u001b[1m[chain:RunnableSequence > prompt:ChatPromptTemplate] [1ms] Exiting Prompt run with output:\n","\u001b[0m[outputs]\n","\u001b[32;1m\u001b[1;3m[llm/start]\u001b[0m \u001b[1m[chain:RunnableSequence > llm:ChatOpenAI] Entering LLM run with input:\n","\u001b[0m{\n"," \"prompts\": [\n"," \"System: You are a helpful assistant that translates Chinese to English.\\nHuman: 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\\nExample Translations:\\nChinese: 全仗着狐仙搭救。\\nEnglish: Because I was protected by a fox fairy.\\nChinese: 过后,表哥告诉她俩,这人是导演,在外国留过学的,还会编剧,今天拍的这戏,就是他自编自导的。\\nEnglish: 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.\\nChinese: 这凤姐忽然想起一件事来,便向窗外叫:“蓉儿回来!”\\nEnglish: Xi-feng suddenly seemed to remember something, and called to him through the window, 'Rong, come back!'\\nChinese: 三个老红卫兵走到叶文洁面前,面对着她站成了一排——当年,她们也是这样面对叶哲泰的——试图再现那早已忘却的尊严,但她们当年那魔鬼般的精神力量显然已荡然无存。\\nEnglish: 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.\\nChinese: 程先生照单全收,都是一个“谢”字,然后问王琦瑶有什么话说。\\nEnglish: 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\\nChinese: 后来她不挣扎了,对我说,混蛋,你要把我怎么办。\\nEnglish:\"\n"," ]\n","}\n"]},{"name":"stderr","output_type":"stream","text":["100%|██████████| 2/2 [00:04<00:00, 2.12s/it]"]},{"name":"stdout","output_type":"stream","text":["\u001b[36;1m\u001b[1;3m[llm/end]\u001b[0m \u001b[1m[chain:RunnableSequence > llm:ChatOpenAI] [908ms] Exiting LLM run with output:\n","\u001b[0m{\n"," \"generations\": [\n"," [\n"," {\n"," \"text\": \"Later, she stopped struggling and said to me, \\\"Bastard, what are you going to do with me?\\\"\",\n"," \"generation_info\": {\n"," \"finish_reason\": \"stop\",\n"," \"logprobs\": null\n"," },\n"," \"type\": \"ChatGeneration\",\n"," \"message\": {\n"," \"lc\": 1,\n"," \"type\": \"constructor\",\n"," \"id\": [\n"," \"langchain\",\n"," \"schema\",\n"," \"messages\",\n"," \"AIMessage\"\n"," ],\n"," \"kwargs\": {\n"," \"content\": \"Later, she stopped struggling and said to me, \\\"Bastard, what are you going to do with me?\\\"\",\n"," \"response_metadata\": {\n"," \"token_usage\": {\n"," \"completion_tokens\": 24,\n"," \"prompt_tokens\": 433,\n"," \"total_tokens\": 457\n"," },\n"," \"model_name\": \"gpt-4o-mini-2024-07-18\",\n"," \"system_fingerprint\": \"fp_611b667b19\",\n"," \"finish_reason\": \"stop\",\n"," \"logprobs\": null\n"," },\n"," \"type\": \"ai\",\n"," \"id\": \"run-e4bb10fb-f7c4-4440-82ba-c13a1a82bc00-0\",\n"," \"usage_metadata\": {\n"," \"input_tokens\": 433,\n"," \"output_tokens\": 24,\n"," \"total_tokens\": 457\n"," },\n"," \"tool_calls\": [],\n"," \"invalid_tool_calls\": []\n"," }\n"," }\n"," }\n"," ]\n"," ],\n"," \"llm_output\": {\n"," \"token_usage\": {\n"," \"completion_tokens\": 24,\n"," \"prompt_tokens\": 433,\n"," \"total_tokens\": 457\n"," },\n"," \"model_name\": \"gpt-4o-mini-2024-07-18\",\n"," \"system_fingerprint\": \"fp_611b667b19\"\n"," },\n"," \"run\": null\n","}\n","\u001b[36;1m\u001b[1;3m[chain/end]\u001b[0m \u001b[1m[chain:RunnableSequence] [918ms] Exiting Chain run with output:\n","\u001b[0m[outputs]\n"]},{"name":"stderr","output_type":"stream","text":["\n"]}],"source":["predictions = eval_openai(5, datasets)"]},{"cell_type":"code","execution_count":14,"metadata":{},"outputs":[{"name":"stdout","output_type":"stream","text":["['That Liu Laolao first heard about the hardships and thought it was hopeless, then heard about the twenty taels of silver and smiled with joy, saying, \"We also know it\\'s difficult, but as the saying goes: \\'A dead camel is still bigger than a horse.\\'\"', 'Later, she stopped struggling and said to me, \"Bastard, what are you going to do with me?\"']\n"]}],"source":["print(predictions)"]},{"cell_type":"code","execution_count":15,"metadata":{},"outputs":[{"data":{"text/plain":["{'meteor': 0.5376810911615811,\n"," 'bleu_scores': {'bleu': 0.16133991724232039,\n"," 'precisions': [0.5454545454545454,\n"," 0.26666666666666666,\n"," 0.1643835616438356,\n"," 0.09859154929577464],\n"," 'brevity_penalty': 0.7322097138745853,\n"," 'length_ratio': 0.7623762376237624,\n"," 'translation_length': 77,\n"," 'reference_length': 101},\n"," 'rouge_scores': {'rouge1': 0.5594202898550725,\n"," 'rouge2': 0.362051015096304,\n"," 'rougeL': 0.5246376811594203,\n"," 'rougeLsum': 0.5246376811594203},\n"," 'accuracy': 0.0}"]},"execution_count":15,"metadata":{},"output_type":"execute_result"}],"source":["calc_metrics(eval_dataset[\"english\"], predictions)"]}],"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
CHANGED
@@ -1,9 +1,23 @@
|
|
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,0,0.2624042529095214,0.052402107437040435,0.
|
3 |
-
01-ai/Yi-1.5-9B-Chat,1,0.34870107586750904,0.08089424511255362,0.
|
4 |
-
01-ai/Yi-1.5-9B-Chat,3,0.32640977691198636,0.055279846527263934,0.
|
5 |
-
01-ai/Yi-1.5-9B-Chat,5,0.34766805202103457,0.08282971728232061,0.
|
6 |
-
|
7 |
-
Qwen/Qwen2-72B-Instruct,
|
8 |
-
Qwen/Qwen2-72B-Instruct,
|
9 |
-
Qwen/Qwen2-72B-Instruct,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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,0,0.2624042529095214,0.052402107437040435,0.22702109917009206,0.0088261253309797,1.593115622241836,1.6019417475728155,0.24649759532229093,18
|
3 |
+
01-ai/Yi-1.5-9B-Chat,1,0.34870107586750904,0.08089424511255362,0.32734221074629044,0.0,0.41394527802294795,0.41394527802294795,0.3426649332614599,17
|
4 |
+
01-ai/Yi-1.5-9B-Chat,3,0.32640977691198636,0.055279846527263934,0.2928978370489262,0.0,0.8570167696381289,0.8570167696381289,0.3151554166830832,41
|
5 |
+
01-ai/Yi-1.5-9B-Chat,5,0.34766805202103457,0.08282971728232061,0.3267409773412665,0.0,0.1703442188879082,0.1703442188879082,0.3451362525721807,12
|
6 |
+
01-ai/Yi-1.5-9B-Chat,10,0.3404245874451134,0.0874799371333584,0.3186285587310857,0.0,0.33451015004413065,0.33451015004413065,0.335628491165567,9
|
7 |
+
Qwen/Qwen2-72B-Instruct,0,0.4003638205699929,0.12223832517678616,0.3843308919636922,0.0,0.19593998234774934,0.19593998234774934,0.3970180421898014,1
|
8 |
+
Qwen/Qwen2-72B-Instruct,1,0.4068727655718769,0.13151008586303575,0.39419477888585397,0.0,0.15798764342453664,0.15798764342453664,0.4041216347207881,1
|
9 |
+
Qwen/Qwen2-72B-Instruct,3,0.4086244766794449,0.13771788946915253,0.3975872454980886,0.0,0.12709620476610767,0.12709620476610767,0.4063954239173824,0
|
10 |
+
Qwen/Qwen2-72B-Instruct,5,0.4132330811975005,0.1439773872150899,0.40319922813685904,0.0,0.11915269196822595,0.11915269196822595,0.41111822769434864,0
|
11 |
+
Qwen/Qwen2-72B-Instruct,10,0.41598174489789025,0.14493475334416772,0.4061550950232767,0.0,0.09620476610767872,0.09620476610767872,0.4142591929807702,0
|
12 |
+
gpt-4o-mini,0,0.3797696357415517,0.1208238389018596,0.3703414668036082,0.0,0.09532215357458076,0.09532215357458076,0.37821133607113916,0
|
13 |
+
gpt-4o-mini,1,0.37721414424357197,0.12013402254992751,0.3672849018610451,0.0,0.09179170344218888,0.09179170344218888,0.37572317024740703,0
|
14 |
+
gpt-4o-mini,3,0.3772985230936086,0.12400311006855895,0.3678727405759652,0.0,0.09179170344218888,0.09179170344218888,0.3758072155821894,0
|
15 |
+
gpt-4o-mini,5,0.35541821046691263,0.1202464326274801,0.3467666649149247,0.0,0.05030891438658429,0.05030891438658429,0.3546452926906339,0
|
16 |
+
gpt-4o-mini,10,0.37335968903521094,0.1257600824824953,0.3655393297085069,0.0,0.0706090026478376,0.0706090026478376,0.37222227656264567,0
|
17 |
+
gpt-4o-mini,50,0.4044690970661121,0.13972883920222515,0.39119808964775155,0.0,0.08473080317740513,0.08473080317740513,0.4029924080114739,0
|
18 |
+
gpt-4o,0,0.3797419877414444,0.12054600115274576,0.3701547457064372,0.0,0.09532215357458076,0.09532215357458076,0.37818380151840997,0
|
19 |
+
gpt-4o,1,0.37588586538591867,0.12049862468096047,0.3655088353382996,0.0,0.09179170344218888,0.09179170344218888,0.3744001415355042,0
|
20 |
+
gpt-4o,3,0.3768512103553621,0.12408746322526747,0.36675999670221837,0.0,0.09355692850838482,0.09355692850838482,0.3753332737090981,0
|
21 |
+
gpt-4o,5,0.35772544915145654,0.12169683347842021,0.348000637544411,0.0,0.0353045013239188,0.0353045013239188,0.3571787674657609,0
|
22 |
+
gpt-4o,10,0.3746444651189953,0.12498238983123719,0.36675868342577317,0.0,0.0706090026478376,0.0706090026478376,0.37350313867182305,0
|
23 |
+
gpt-4o,50,0.40413933252744955,0.13782450337569063,0.39068912530823663,0.0,0.07590467784642542,0.07590467784642542,0.402816463024093,0
|
results/mac-results_few_shots_openai.csv
ADDED
The diff for this file is too large to render.
See raw diff
|
|
scripts/eval-mac.sh
CHANGED
@@ -14,13 +14,15 @@ grep MemTotal /proc/meminfo
|
|
14 |
# pip install torch torchvision torchaudio
|
15 |
# pip install -r requirements.txt
|
16 |
|
|
|
|
|
17 |
./scripts/eval-model.sh 01-ai/Yi-1.5-9B-Chat
|
18 |
|
19 |
-
./scripts/eval-model.sh internlm/internlm2_5-7b-chat
|
20 |
|
21 |
-
./scripts/eval-model.sh Qwen/Qwen2-7B-Instruct
|
22 |
|
23 |
-
./scripts/eval-model.sh shenzhi-wang/Mistral-7B-v0.3-Chinese-Chat
|
24 |
|
25 |
-
./scripts/eval-model.sh shenzhi-wang/Llama3.1-8B-Chinese-Chat
|
26 |
|
|
|
14 |
# pip install torch torchvision torchaudio
|
15 |
# pip install -r requirements.txt
|
16 |
|
17 |
+
export START_NUM_SHOTS=50
|
18 |
+
|
19 |
./scripts/eval-model.sh 01-ai/Yi-1.5-9B-Chat
|
20 |
|
21 |
+
# ./scripts/eval-model.sh internlm/internlm2_5-7b-chat
|
22 |
|
23 |
+
# ./scripts/eval-model.sh Qwen/Qwen2-7B-Instruct
|
24 |
|
25 |
+
# ./scripts/eval-model.sh shenzhi-wang/Mistral-7B-v0.3-Chinese-Chat
|
26 |
|
27 |
+
# ./scripts/eval-model.sh shenzhi-wang/Llama3.1-8B-Chinese-Chat
|
28 |
|