Gemma 2 2b Jpn It Translate
基于Google发布的gemma-2-2b-jpn-it进行翻译任务调优的模型,专注于日英互译任务
下载量 60
发布时间 : 10/7/2024
模型简介
该模型是针对日语和英语双向翻译优化的语言模型,具有高效处理能力和长文本翻译潜力
模型特点
高效翻译
20亿参数规模下实现接近70亿参数模型的翻译质量
长文本处理
具备处理无限长文本翻译的潜力,建议分句预处理
快速运行
约5GB的较小文件尺寸实现快速运行
自动提示模板
采用apply_chat_template技术避免手动提示模板编写
模型能力
日语到英语翻译
英语到日语翻译
长文本处理
商务文本翻译
使用案例
商务翻译
商务邮件翻译
将商务邮件内容在日语和英语之间互译
示例输出显示良好的商务术语处理能力
企业公告翻译
翻译企业财务报告、发展计划等正式文档
能准确处理数字、日期等关键信息
技术文档翻译
技术文档翻译
将技术文档在日英之间互译
🚀 gemma-2-2b-jpn-it-translate 翻译模型
gemma-2-2b-jpn-it-translate 是基于 Google 发布的 google/gemma-2-2b-jpn-it 模型,针对翻译任务进行微调的模型。虽然它只有 20 亿(2B)个参数,但在某些领域,其翻译质量可接近一年前 70 亿(7B)参数的模型。而且,该模型文件大小相对较小,约为 5GB,因此能够实现快速执行。
🚀 快速开始
gemma-2-2b-jpn-it-translate 模型在翻译任务中表现出色,能够为用户提供高质量的翻译服务。以下是使用该模型进行翻译的基本步骤:
- 安装必要的库:使用
pip install -U transformers
命令安装所需的库。 - 加载模型和分词器:使用
AutoModelForCausalLM
和AutoTokenizer
加载模型和分词器。 - 设置系统提示和指令:根据翻译任务的需求,设置系统提示和指令。
- 进行翻译:将待翻译的文本输入到模型中,获取翻译结果。
✨ 主要特性
- 高质量翻译:尽管参数数量为 20 亿(2B),但在某些领域能提供接近一年前 70 亿(7B)模型的翻译质量。
- 快速执行:文件大小约 5GB,相对较小,可实现高速运行。
- 支持无限长文本翻译:旨在实现对无限长文本的高速翻译。
- 简化操作:使用
apply_chat_template
避免手动编写易出错的提示模板。
📚 详细文档
模型说明
此模型是对 Google 发布的日语专用模型「gemma-2-2b-jpn-it」进行微调后的产物。其目标是实现高速且能处理无限长文本的翻译。具体而言,先输入相当于系统提示的文本(日语/英语)后,模型会对用户后续输入的文本进行翻译并输出(日语/英语)。此外,由于使用了 apply_chat_template
,无需手动编写容易出错的提示模板。
需要注意的是,该模型是按句子进行翻译训练的,因此一次性输入包含换行的长文本会导致翻译质量下降。翻译长文本时,请先将其按句子进行预处理,再输入模型。
一括翻译用样本 Colab 脚本
拥有 Google 账号的用户,点击以下链接中的「Open In Colab」按钮,即可免费进行测试: gemma_2_2b_jpn_it_tranlate_batch_translation_sample.ipynb
💻 使用示例
日英翻译用示例代码
如果您拥有配备 GPU 的计算机,可以参考以下脚本进行操作;若没有,可尝试使用 gguf 版模型。请注意,以下示例脚本中对句子进行分割的部分并非完整实现,请根据实际需求进行修改。
import re
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
def get_torch_dtype():
if torch.cuda.is_available():
device = torch.device("cuda")
prop = torch.cuda.get_device_properties(device)
# Ampere (Compute Capability 8.0 above), for example L4 support bfloat16, but T4 not support.
if prop.major >= 8:
return torch.bfloat16
return torch.float16
model_name = "webbigdata/gemma-2-2b-jpn-it-translate"
model = AutoModelForCausalLM.from_pretrained(
model_name,
torch_dtype=get_torch_dtype(),
device_map="auto",
)
tokenizer = AutoTokenizer.from_pretrained(model_name)
tokenizer.pad_token = tokenizer.unk_token
system_prompt = "You are a highly skilled professional Japanese-English and English-Japanese translator. Translate the given text accurately, taking into account the context and specific instructions provided. Steps may include hints enclosed in square brackets [] with the key and value separated by a colon:. Only when the subject is specified in the Japanese sentence, the subject will be added when translating into English. If no additional instructions or context are provided, use your expertise to consider what the most appropriate context is and provide a natural translation that aligns with that context. When translating, strive to faithfully reflect the meaning and tone of the original text, pay attention to cultural nuances and differences in language usage, and ensure that the translation is grammatically correct and easy to read. After completing the translation, review it once more to check for errors or unnatural expressions. For technical terms and proper nouns, either leave them in the original language or use appropriate translations as necessary. Take a deep breath, calm down, and start translating.\n\n"
instruct = """Translate Japanese to English.\nWhen translating, please use the following hints:\n[writing_style: casual]"""
# 文章を区切る関数
def split_sentences(text):
sentences = []
last = 0
# 句点で文を分割
for match in re.finditer(r'[。!?…]', text):
end = match.end()
# 句点の直後に続く改行を含める
while end < len(text) and text[end] == '\n':
end += 1
sentence = text[last:end]
sentences.append(sentence)
last = end
# 残りのテキストを追加
if last < len(text):
remaining = text[last:]
sentences.append(remaining)
# 各文内の改行を適切に分割
final_sentences = []
for s in sentences:
if '\n' in s:
parts = s.split('\n')
for i, part in enumerate(parts):
if part:
# 最後の部分でなければ改行を追加
if i < len(parts) - 1:
final_sentences.append(part + '\n')
else:
final_sentences.append(part)
# 改行自体を保持
if i < len(parts) - 1:
final_sentences.append('\n')
else:
final_sentences.append(s)
return final_sentences
# 翻訳処理を行う関数
def translate_sentence(sentence, previous_context):
# 過去のコンテキストと新しい文を配列に格納
if sentence.strip() == '':
return sentence
messages = previous_context + [
{"role": "user", "content": sentence}
]
# apply_chat_templateを使用してプロンプトを生成
inputs = tokenizer.apply_chat_template(
messages,
tokenize=True,
add_generation_prompt=True,
return_tensors="pt",
).to("cuda")
translation = ""
with torch.no_grad():
generated_ids = model.generate(
input_ids=inputs,
num_beams=3, max_new_tokens=1200, do_sample=True, temperature=0.5, top_p=0.3
)
full_output = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0].strip()
translation = full_output.split('\nmodel\n')[-1].strip()
return translation
from collections import deque
# メイン処理
def main(text):
sentences = split_sentences(text)
translated_sentences = []
# Initialize context with system prompt
context = deque([
{"role": "user", "content": system_prompt + instruct},
{"role": "assistant", "content": "OK"}
], maxlen=6) # Maximum 10 elements (5 user, 5 assistant)
for i, sentence in enumerate(sentences):
# For the first sentence, use the full context including system prompt
if i == 0:
translation_context = list(context)
else:
# For subsequent sentences, exclude the system prompt
translation_context = list(context)[2:]
translated_sentence = translate_sentence(sentence, translation_context)
translated_sentences.append(translated_sentence)
# Add new interactions to the context
if sentence.strip() != '':
context.append({"role": "user", "content": sentence})
else:
context.append({"role": "user", "content": sentence})
if translated_sentence.strip() != '':
context.append({"role": "assistant", "content": translated_sentence})
else:
context.append({"role": "assistant", "content": translated_sentence})
return translated_sentences
text = """こんにちは。私は田中です。今日はとても良い天気ですね。朝ごはんはパンとコーヒーを食べました。そのあとに散歩に行きました。公園にはたくさんの人がいました。子供たちは遊んでいました。
犬を連れている人もいました。私はベンチに座って本を読みました。風がとても気持ちよかったです。その後、友達とカフェに行きました。
カフェではコーヒーを飲みながらおしゃべりをしました。友達は最近引っ越したばかりだと言いました。新しい家の写真を見せてくれました。
とてもきれいな家でした。時間が経つのがあっという間でした。夕方になり、私は家に帰りました。夕食にはカレーを作りました。カレーはとても美味しかったです。今日一日、とても楽しかったです。"""
translated = main(text)
print(translated)
英日翻译用示例代码
import re
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
def get_torch_dtype():
if torch.cuda.is_available():
device = torch.device("cuda")
prop = torch.cuda.get_device_properties(device)
# Ampere (Compute Capability 8.0 above), for example L4 support bfloat16, but T4 not support.
if prop.major >= 8:
return torch.bfloat16
return torch.float16
model_name = "gemma-2-2b-jpn-it-translate"
model = AutoModelForCausalLM.from_pretrained(
model_name,
torch_dtype=get_torch_dtype(),
device_map="auto",
)
tokenizer = AutoTokenizer.from_pretrained(model_name)
tokenizer.pad_token = tokenizer.unk_token
system_prompt = "You are a highly skilled professional Japanese-English and English-Japanese translator. Translate the given text accurately, taking into account the context and specific instructions provided. Steps may include hints enclosed in square brackets [] with the key and value separated by a colon:. Only when the subject is specified in the Japanese sentence, the subject will be added when translating into English. If no additional instructions or context are provided, use your expertise to consider what the most appropriate context is and provide a natural translation that aligns with that context. When translating, strive to faithfully reflect the meaning and tone of the original text, pay attention to cultural nuances and differences in language usage, and ensure that the translation is grammatically correct and easy to read. After completing the translation, review it once more to check for errors or unnatural expressions. For technical terms and proper nouns, either leave them in the original language or use appropriate translations as necessary. Take a deep breath, calm down, and start translating.\n\n"
instruct = """Translate English to Japanese.\nWhen translating, please use the following hints:\n[writing_style: business]"""
# Function to split English sentences
def split_sentences(text):
sentences = []
# Split by newlines, periods, exclamation marks, question marks, or two or more consecutive spaces
pattern = r'(?:\r?\n|\.|\!|\?|(?:\s{2,}))'
splits = re.split(pattern, text)
for split in splits:
split = split.strip()
if split:
sentences.append(split)
return sentences
# Function to translate a sentence
def translate_sentence(sentence, previous_context):
if sentence.strip() == '':
return sentence
messages = previous_context + [
{"role": "user", "content": sentence}
]
inputs = tokenizer.apply_chat_template(
messages,
tokenize=True,
add_generation_prompt=True,
return_tensors="pt",
).to("cuda")
translation = ""
with torch.no_grad():
generated_ids = model.generate(
input_ids=inputs,
num_beams=3, max_new_tokens=1200, do_sample=True, temperature=0.5, top_p=0.3
)
full_output = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0].strip()
translation = full_output.split('\nmodel\n')[-1].strip()
return translation
from collections import deque
# Main processing function
def main(text):
sentences = split_sentences(text)
translated_sentences = []
context = deque([
{"role": "user", "content": system_prompt + instruct},
{"role": "assistant", "content": "OK"}
], maxlen=6)
for i, sentence in enumerate(sentences):
if i == 0:
translation_context = list(context)
else:
translation_context = list(context)[2:]
translated_sentence = translate_sentence(sentence, translation_context)
translated_sentences.append(translated_sentence)
if sentence.strip() != '':
context.append({"role": "user", "content": sentence})
else:
context.append({"role": "user", "content": sentence})
if translated_sentence.strip() != '':
context.append({"role": "assistant", "content": translated_sentence})
else:
context.append({"role": "assistant", "content": translated_sentence})
return translated_sentences
# Sample English text for translation (business context)
text = """Dear valued clients and partners,
I hope this email finds you well. I am writing to provide you with an important update regarding our company's recent developments and future plans.
Firstly, I am pleased to announce that our Q3 financial results have exceeded expectations, with a 15% increase in revenue compared to the same period last year. This success is largely attributed to the launch of our new product line and the expansion of our services into emerging markets.
In light of this growth, we are planning to implement several strategic initiatives in the coming months:
1. Expansion of our R&D department: We will be investing significantly in research and development to maintain our competitive edge in the market.
2. Sustainability efforts: We are committed to reducing our carbon footprint by 30% over the next five years. This includes transitioning to renewable energy sources and implementing eco-friendly practices across all our operations.
3. Digital transformation: We will be upgrading our IT infrastructure to enhance efficiency and provide better service to our clients.
Additionally, we are excited to announce our upcoming annual conference, which will be held virtually this year due to ongoing global health concerns. The conference will take place on November 15-16, 2024, and will feature keynote speeches from industry leaders, interactive workshops, and networking opportunities.
We value your continued support and partnership. If you have any questions or would like further information about any of these initiatives, please don't hesitate to reach out to your account manager or contact our customer support team.
Thank you for your trust in our company. We look forward to achieving new milestones together.
Best regards,
John Smith
CEO, XYZ Corporation"""
翻译结果
['貴社にご愛顧いただき、誠にありがとうございます。', 'このメールがご健在であることを心よりお祈り申し上げます。',
'弊社の最近の進展と今後の計画について、重要なお知らせをご提供いたします。',
'まず、第3四半期の収益が予想を上回ったことをお知らせいたします。昨年の同時期と比較して、売上高が15%増加しました。',
'この成功は、新製品ラインの発売と、新興市場へのサービスの拡大が大きく貢献しています。',
'この成長を踏まえ、今後の数ヶ月にわたって、いくつかの戦略的イニシアティブを実施する予定です。',
'1', 'R&D部門の拡大:市場での競争力を維持するために、大幅に研究開発に投資する予定です。',
'2', 'サステナビリティの取り組み:次の5年間で、炭素排出量を30%削減することを目指しています。',
'これは、再生可能エネルギー源への移行と、すべての事業活動における環境にやさしい実践の導入を含むものです。',
'3', 'デジタルトランスフォーメーション: 私たちのITインフラを強化し、効率を向上させ、より良いサービスを提供する',
'さらに、今年は新型コロナウイルス感染症の懸念が続くため、オンラインで開催されますが、毎年恒例の年次カンファレンスをお知らせいたします。',
'カンファレンスは2024年11月15日~16日に開催され、業界のリーダーによるキーノートスピーチ、インタラクティブワークショップ、ネットワークングの機会が盛りだくさんです。',
'引き続きご支援とご協力を賜りますようお願い申し上げます。',
'これらのイニシアチブについてご質問がある場合や、さらに詳しい情報をご希望の場合は、ご担当マネジャーにご連絡するか、弊社のカスタマーサポートチームにご連絡ください。',
'弊社の信頼を賜り、誠にありがとうございます。',
'共に新たな目標を達成できることを楽しみにしています。',
'ご清栄のこととお慶び申し上げます。',
'ジョン・スミス', 'XYZ株式会社のCEO']
🔧 技术细节
基准测试结果
文件名 | 翻译方向 | spBLEU | chrF2++ | comet | xlcomet |
---|---|---|---|---|---|
flores200v1 | 英日 | 28.56 | 37.5 | 0.896 | 0.8512 |
flores200v1 | 日英 | 26.38 | 56.6 | 0.8735 | 0.9324 |
wmt20 | 英日 | 15.62 | 29.1 | 0.8796 | 0.7913 |
wmt20 | 日英 | 18.04 | 46.3 | 0.8013 | 0.7815 |
wmt22 | 英日 | 17.47 | 30.9 | 0.8799 | 0.8581 |
wmt22 | 日英 | 19.93 | 46.4 | 0.8107 | 0.8821 |
wmt23 | 英日 | 15.95 | 28.4 | 0.8585 | 0.8213 |
wmt23 | 日英 | 15.54 | 45.2 | 0.8029 | 0.8669 |
Business | 英日 | 21.08 | 38.1 | 0.9041 | 0.9178 |
Business | 日英 | 24.27 | 47.5 | 0.8317 | 0.8716 |
NTREX128 | 英日 | 18.18 | 30.1 | 0.8757 | 0.7709 |
📄 许可证
致谢
- 开发者:[dahara1@webbigdata]
- 支持语言 (NLP):[英语、日语]
- 基础模型 [可选]:gemma-2-2b-jpn-it
BibTeX 引用
@misc{dahara2024imatrix,
author = {dahara1@webbigdata},
title = {gemma-2-2b-jpn-it-translate: A translation task-specific model based on gemma-2-2b-jpn-it},
year = {2024},
howpublished = {\url{https://huggingface.co/webbigdata/gemma-2-2b-jpn-it-translate/}},
note = {Accessed: 2024-10-10},
abstract = {This model was developed to verify how much Japanese-English and English-Japanese translation performance can be improved with the 2B model.},
}
M2m100 418M
MIT
M2M100是一个多语言编码器-解码器模型,支持100种语言的9900个翻译方向
机器翻译 支持多种语言
M
facebook
1.6M
299
Opus Mt Fr En
Apache-2.0
基于Transformer的法语到英语神经机器翻译模型,由Helsinki-NLP团队开发,采用OPUS多语数据集训练。
机器翻译 支持多种语言
O
Helsinki-NLP
1.2M
44
Opus Mt Ar En
Apache-2.0
基于OPUS数据训练的阿拉伯语到英语的机器翻译模型,采用transformer-align架构
机器翻译 支持多种语言
O
Helsinki-NLP
579.41k
42
M2m100 1.2B
MIT
M2M100是一个支持100种语言的多语言机器翻译模型,可直接在9900个翻译方向之间进行翻译。
机器翻译 支持多种语言
M
facebook
501.82k
167
Indictrans2 Indic En 1B
MIT
支持25种印度语言与英语互译的1.1B参数规模机器翻译模型,由AI4Bharat项目开发
机器翻译
Transformers 支持多种语言

I
ai4bharat
473.63k
14
Opus Mt En Zh
Apache-2.0
基于Transformer架构的英汉多方言翻译模型,支持英语到13种汉语变体的翻译任务
机器翻译 支持多种语言
O
Helsinki-NLP
442.08k
367
Opus Mt Zh En
由赫尔辛基大学开发的基于OPUS语料库的中文到英语机器翻译模型
机器翻译 支持多种语言
O
Helsinki-NLP
441.24k
505
Mbart Large 50 Many To Many Mmt
基于mBART-large-50微调的多语言机器翻译模型,支持50种语言间的互译
机器翻译 支持多种语言
M
facebook
404.66k
357
Opus Mt De En
Apache-2.0
opus-mt-de-en 是一个基于 transformer-align 架构的德语到英语的机器翻译模型,由 Helsinki-NLP 团队开发。
机器翻译 支持多种语言
O
Helsinki-NLP
404.33k
44
Opus Mt Es En
Apache-2.0
这是一个基于Transformer架构的西班牙语到英语的机器翻译模型,由Helsinki-NLP团队开发。
机器翻译
Transformers 支持多种语言

O
Helsinki-NLP
385.40k
71
精选推荐AI模型
Llama 3 Typhoon V1.5x 8b Instruct
专为泰语设计的80亿参数指令模型,性能媲美GPT-3.5-turbo,优化了应用场景、检索增强生成、受限生成和推理任务
大型语言模型
Transformers 支持多种语言

L
scb10x
3,269
16
Cadet Tiny
Openrail
Cadet-Tiny是一个基于SODA数据集训练的超小型对话模型,专为边缘设备推理设计,体积仅为Cosmo-3B模型的2%左右。
对话系统
Transformers 英语

C
ToddGoldfarb
2,691
6
Roberta Base Chinese Extractive Qa
基于RoBERTa架构的中文抽取式问答模型,适用于从给定文本中提取答案的任务。
问答系统 中文
R
uer
2,694
98