kaitos255 commited on
Commit
c920b1b
·
0 Parent(s):

Initial release of PLaMo 3 Translate 0.8B W4AFP8

Browse files
.gitattributes ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ figures/benchmark.png filter=lfs diff=lfs merge=lfs -text
37
+ figures/benchmark_ja.png filter=lfs diff=lfs merge=lfs -text
38
+ figures/benchmark_en.png filter=lfs diff=lfs merge=lfs -text
LICENSE/en ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ PLaMo Community License Agreement
2
+
3
+ The PLaMo Community License Agreement outlines the terms and conditions for utilizing the large-scale language foundation model PLaMo and its derivatives provided by Preferred Networks, Inc., as well as any obligations the USER must observe. The USER’s access to the PLaMo model and its derivatives is subject to this AGREEMENT. By agreeing to or utilizing this MODEL, the USER shall be bound by the terms of this AGREEMENT.
4
+
5
+
6
+ Article 1 (Definitions)
7
+
8
+ (1) "AGREEMENT" refers to the PLaMo Community License Agreement.
9
+
10
+ (2) "PFN" refers to Preferred Networks, Inc.
11
+
12
+ (3) "MODEL" denotes the model weights, model code, tokenizer, training scripts, and other supplementary materials provided by PFN under the name "PLaMo" as separately specified.
13
+
14
+ (4) "USER" means an individual or legal entity utilizing the MODEL.
15
+
16
+ (5) "DERIVED MODEL" refers to models created through modification or use of the MODEL, including their model weights, code, and other associated materials.
17
+
18
+ (6) "OUTPUT" means the results produced by the MODEL or DERIVED MODEL.
19
+
20
+ (7) " MODEL MATERIALS" collectively refers to the MODEL, DERIVED MODEL, and OUTPUT.
21
+
22
+ (8) "LICENSE" means PFN's authorization to grant the USER permission to use the MODEL MATERIALS under this AGREEMENT.
23
+
24
+ (9) "COMMERCIAL PURPOSE" means any use beyond personal or academic use, including business applications or commercial purposes. Notably, COMMERCIAL PURPOSE also includes usage for developing, modifying, or providing products, services, or business operations (including through hosting services or APIs), and usage within the USER's organizational frameworks.
25
+
26
+
27
+ Article 2 (User Requirements)
28
+
29
+ The USER must be 18 years of age or older, or have reached the age of legal capacity in the USER’s country of residence, unless the USER's legal guardian or legal representative has consented to this AGREEMENT on the USER’s behalf.
30
+
31
+
32
+ Article 3 (This License)
33
+
34
+ (1) PFN grants the USER permission to use the MODEL MATERIALS under the terms and conditions and scope specified in this AGREEMENT, provided that the USER agrees to and comply with this AGREEMENT.
35
+
36
+ (2) This LICENSE is non-exclusive, worldwide, non-transferable, and royalty-free.
37
+
38
+ (3) The USER may utilize the MODEL MATERIALS for COMMERCIAL PURPOSE only if the USER satisfies all of the following conditions. If the USER fails to meet any of these conditions, the USER may no longer use the MODEL MATERIALS for COMMERCIAL PURPOSE and must obtain a new commercial license from PFN if the USER wishes to use the MODEL MATERIALS for COMMERCIAL PURPOSE.
39
+
40
+ (i) Prior registration on PFN's official registration page (https://forms.gle/mTL8tBLrMYXKNZD56).
41
+
42
+ (ii) The USER's or the USER’s affiliated company's annual revenue or sales must not exceed 1 billion yen (converted to the local currency of the USER's jurisdiction).
43
+
44
+
45
+ Article 4 (Redistribution and Attribution Requirements)
46
+
47
+ (1) When providing the MODEL MATERIALS to third parties, the USER must meet the following requirements:
48
+
49
+ (i) Provide a copy of this AGREEMENT and ensure the recipients comply with its terms.
50
+
51
+ (ii) Explicitly indicate "Built with PLaMo" in related websites, user interfaces, blog posts, product information pages, or product documentation.
52
+
53
+ (iii) Include "PLaMo" in the names of AI models created using the MODEL MATERIALS.
54
+
55
+
56
+ Article 5 (Usage of Outputs)
57
+
58
+ (1) The USER may publicly distribute the OUTPUT provided that the USER clearly indicates that it is the output of the MODEL or DERIVED MODEL.
59
+
60
+ (2) If models are trained using the OUTPUT, those models shall be treated as DERIVED MODEL subject to this AGREEMENT's terms, and may only be used, distributed, and commercialized under the same license conditions.
61
+
62
+
63
+ Article 6 (Additional Usage Terms)
64
+
65
+ The USER must not engage in any of the following activities regarding the use of the MODEL MATERIALS:
66
+
67
+ (1) Actions violating laws or public order and morals
68
+
69
+ (2) Criminal activities or any actions that threaten, participate in, or facilitate such activities
70
+
71
+ (3) Actions infringing upon the rights or interests of PFN or third parties
72
+
73
+ (4) Actions that damage the reputation or credibility of PFN or third parties
74
+
75
+ (5) Dissemination of information that could create the false impression that the OUTPUT represents PFN's official views, etc.
76
+
77
+ (6) Dissemination of false information
78
+
79
+ (7) Any other actions that PFN reasonably determines to be inappropriate
80
+
81
+
82
+ Article 7 (Warranty Disclaimer)
83
+
84
+ (1) The MODEL and the OUTPUT are provided "as is" without any warranties from PFN regarding accuracy, truthfulness, merchantability, quality, performance, fitness for specific purposes, non-infringement, or any other matter.
85
+
86
+ (2) The USER must not use the OUTPUT as the sole evidence, evaluation, or opinion regarding legal matters, medical diagnoses, financial decisions, or important personal assessments.
87
+
88
+ (3) The USER assumes all responsibility for the use of the MODEL MATERIALS and any consequences arising therefrom.
89
+
90
+
91
+ Article 8 (Limitation of Liability)
92
+
93
+ (1) Regardless of whether liability arises from contract, tort, product liability, or other legal grounds, PFN's maximum liability to the USER regarding this AGREEMENT and the MODEL MATERIALS is limited to direct and ordinary damages only (including loss of profits, special damages, indirect damages, and other damages, regardless of foreseeability). The maximum liability amount shall be 500 yen. This limitation does not apply if PFN is found to have acted with intent or gross negligence.
94
+
95
+ (2) Notwithstanding the preceding paragraph, if the USER utilizes the MODEL MATERIALS for business purposes, PFN shall assume no liability whatsoever, including any damages or other obligations, regarding this AGREEMENT and the MODEL MATERIALS.
96
+
97
+
98
+ Article 9 (User Responsibility)
99
+
100
+ (1) The USER shall comply with all applicable laws and regulations (including those related to import/export and trade) and this AGREEMENT regarding the acquisition and use of the MODEL MATERIALS.
101
+
102
+ (2) If the USER causes PFN any damages due to breach of this AGREEMENT or use of the MODEL MATERIALS, the USER must compensate PFN for those damages.
103
+
104
+ (3) If PFN receives any claims for damages or other demands from third parties due to USER's use of the MODEL MATERIALS, the USER shall indemnify PFN against such claims and ensure PFN is not harmed.
105
+
106
+
107
+ Article 10 (Ownership Rights)
108
+
109
+ (1) All rights to the MODEL belong to PFN or any third party licensed by PFN to license the MODEL.
110
+
111
+ (2) For DERIVED MODEL, rights pertaining to the portions modified by the USER belong to the USER, while all other rights belong to PFN.
112
+
113
+ (3) All rights to the OUTPUT belong to the USER.
114
+
115
+
116
+ Article 11 (Contract Term and Termination)
117
+
118
+ (1) This AGREEMENT shall be effective from the time the USER agrees to this AGREEMENT or access the MODEL MATERIALS and continue until termination.
119
+
120
+ (2) If the USER violates any terms of this AGREEMENT, PFN may immediately terminate this AGREEMENT, and the USER must delete all copies of the MODEL MATERIALS and cease usage immediately.
121
+
122
+
123
+ Article 12 (Contract Modification)
124
+
125
+ PFN may modify this AGREEMENT (including rules and regulations related to the MODEL MATERIALS; the same applies hereinafter). When modifying this AGREEMENT, PFN shall notify the USER of the modification details and the effective date of the change through the method specified by PFN by the effective date.
126
+
127
+
128
+ Article 13 (Governing Law and Jurisdiction)
129
+
130
+ (1) The laws of Japan shall govern this AGREEMENT.
131
+
132
+ (2) Any disputes arising from the MODEL MATERIALS or AGREEMENT shall be subject to the exclusive jurisdiction of the Tokyo District Court.
LICENSE/ja ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ PLaMoコミュニティライセンス契約
2
+
3
+ PLaMoコミュニティライセンス契約には、株式会社Preferred Networksが提供する別途定める大規模言語基盤モデルPLaMo及びその派生物を利用するためのライセンスの内容及びユーザーが遵守する事項等が定められている。ユーザーのPLaMo及びその派生物の利用には本契約が適用され、本契約に同意又は本モデル等を利用することにより、ユーザーは本契約に拘束される。
4
+
5
+
6
+ 第1条(定義)
7
+
8
+ (1) 「本契約」とは、PLaMoコミュニティライセンス契約を意味する。
9
+
10
+ (2) 「PFN」とは、株式会社Preferred Networksを意味する。
11
+
12
+ (3) 「本モデル」とは、別途定める「PLaMo」という名称のモデルの重み、モデルコード、トークナイザー、学習スクリプト及びこれらに付随してPFNが提供するものを意味する。
13
+
14
+ (4) 「ユーザー」とは、本モデルを利用する個人又は法人を意味する。
15
+
16
+ (5) 「派生モデル」とは、本モデルを改変又は利用し作成されるモデルの重み、モデルコード及びその他作成されたモデルの付随物を意味する。
17
+
18
+ (6) 「生成物」とは、本モデル又は派生モデルの出力結果を意味する。
19
+
20
+ (7) 「本モデル等」とは、本モデル、派生モデル及び生成物の総称を意味する。
21
+
22
+ (8) 「本ライセンス」とは、PFNがユーザーに対して本契約に基づき本モデル等を利用することを許諾することを意味する。
23
+
24
+ (9) 「商業目的」とは、 私的使用又は学術用途の範囲を超える、事業での利用又は営利を目的とする利用を意味する。なお、商業目的にはユーザーの製品、サービス又は事業の開発、変更又は提供(ホスティングサービスやAPI経由での提供を含む。)を目的とした使用及びユーザーの組織内部における利用も含まれる。
25
+
26
+
27
+ 第2条(ユーザー)
28
+
29
+ ユーザーは、18歳以上又はその居住国で単独で契約を締結できる年齢に達していなければならない。但し、ユーザーの親権者又は法定代理人が本契約をユーザーが締結することに同意している場合はこの限りではない。
30
+
31
+
32
+ 第3条(本ライセンス)
33
+
34
+ (1) PFNは、ユーザーが本契約に同意しかつ本契約を遵守することを条件に、ユーザーに対して、本モデル等を本契約に定める条件及び範囲内で利用することを許諾する。
35
+
36
+ (2) 本ライセンスは非独占、世界的、譲渡不可及びロイヤリティ無料とする。
37
+
38
+ (3) ユーザーは、以下の条件をいずれも満たす場合に限り、商業目的を含む形で本モデル等を利用することができる。なお、ユーザーがこれらの条件のいずれかを満たさなくなった場合は、ユーザーはその時点で本モデル等を商業目的で利用することはできず、商業目的で本モデル等を利用したい場合は、新たにPFNから商業用のライセンスを取得しなければならない。
39
+
40
+ (i) PFNの公式登録ページ(https://forms.gle/mTL8tBLrMYXKNZD56)に事前に登録すること。
41
+
42
+ (ii) ユーザー又はその関係会社の直近事業年度の収入又は売上が10億円(ユーザーの現地通貨換算額)を超えないこと。
43
+
44
+
45
+ 第4条(再配布及び表示義務)
46
+
47
+ (1) ユーザーが本モデル等(派生モデルやその生成物を含む)を第三者に提供する場合、以下の条件を満たさなければならない。
48
+
49
+ (i) 本契約のコピーを提供し、本契約の条件を遵守させること。
50
+
51
+ (ii) 「Built with PLaMo」と明示し、関連ウェブサイト、ユーザーインターフェース、ブログ記事、製品情報ページ又は製品ドキュメントに記載すること。
52
+
53
+ (iii) 本モデル等を利用して作成した AI モデルの名称に「PLaMo」を含めること。
54
+
55
+
56
+ 第5条(生成物の利用)
57
+
58
+ (1) ユーザーは、生成物を本モデル又は派生モデルの生成物であることを明示することを条件に、公表することができる。
59
+
60
+ (2) 生成物を利用してモデルを学習した場合、そのモデルは派生モデルとして本契約の条件が適用され、本契約のライセンス条件の下でのみ利用、配布及び商業化することができる。
61
+
62
+
63
+ 第6条(その他利用条件)
64
+
65
+ ユーザーは、本モデル等の利用に関して、以下に定める行為をしてはならない。
66
+
67
+ (1) 法令又は公序良俗に違反する行為
68
+
69
+ (2) 犯罪行為又はこれを予告、関与、助長その他これらに関連する行為
70
+
71
+ (3) PFN又は第三者の権利又は利益を侵害する行為
72
+
73
+ (4) PFN又は第三者の名誉若しくは信用を毀損する行為
74
+
75
+ (5) 生成物がPFNの公式見解��であるものという錯誤を生む情報を流布する行為
76
+
77
+ (6) 虚偽の情報を発信する行為
78
+
79
+ (7) 上記の他、PFNが不適切と合理的に判断する行為
80
+
81
+
82
+ 第7条(保証の否認)
83
+
84
+ (1) 本モデル及び生成物は、「現状有姿」で提供され、PFNは、これらに対して、正確性、真実性、商品性、品質、性能、特定目的への適合性、権利の非侵害など一切の保証をしない。
85
+
86
+ (2) ユーザーは、法律、医療、金融又は人物評価その他重要な事項の決定に関して、生成物を唯一の証拠、評価又は意見として使用してはならない。
87
+
88
+ (3) ユーザーは、本モデル等の使用及びその結果に関して全ての責任を負う。
89
+
90
+
91
+ 第8条(責任の制限)
92
+
93
+ (1) 契約責任、不法行為又は製造物責任その他の法的責任のいずれかであるかを問わず、PFNが本契約及び本モデル等に関してユーザーに対して負う損害賠償の責任は、通常かつ直接の損害に限り(逸失利益、特別損害、間接損害その他の損害については、その予見可能性の有無に関わらず、責任を負わない。)、損害賠償額の上限は、500円とする。但し、PFNに故意又は重過失が認められる場合はこの限りではない。
94
+
95
+ (2) 前項に関わらず、ユーザーが本モデル等を事業のために利用する場合は、PFNは本契約及び本モデル等に関してユーザーに対して一切の損害賠償責任及びその他の責任を負わない。
96
+
97
+
98
+ 第9条(ユーザーの責任)
99
+
100
+ (1) ユーザーは、本モデル等の取得及び利用に関して、適用される法令(輸出入及び貿易に関連する法令を含む。)及び本契約を遵守する。
101
+
102
+ (2) ユーザーは、本契約違反又は本モデル等の使用によって、PFNに損害を与えた場合は、その損害を賠償する。
103
+
104
+ (3) ユーザーの本モデル等の使用に起因して、PFNが第三者から損害賠償請求その他請求を受けた場合、ユーザーは、当該請求からPFNを免責し、PFNに損害を与えないようにする。
105
+
106
+
107
+ 第10条(権利の帰属)
108
+
109
+ (1) 本モデルの一切の権利は、PFN又はPFNに本モデルのライセンスをしている第三者に帰属する。
110
+
111
+ (2) 派生モデルのうち、ユーザーが本モデルを改変した部分の権利はユーザーに帰属し、その他の部分の権利はPFNに帰属する。
112
+
113
+ (3) 生成物の一切の権利はユーザーに帰属する。
114
+
115
+
116
+ 第11条(契約期間及び終了)
117
+
118
+ (1) 本契約は、ユーザーが本契約に同意したとき又は本モデルにアクセスしたときから、本契約が解約されたときまでとする。
119
+
120
+ (2) ユーザーが本契約のいずれかの条項に違反した場合、PFNは直ちに本契約を解除することができ、ユーザーは本モデル等のすべてのコピーを削除し、利用を即時に停止しなければならない。
121
+
122
+
123
+ 第12条(契約の変更)
124
+
125
+ PFNは、本契約(本モデル等に関するルールや諸規定等を含む。以下本条において同じ。)を変更できるものとする。PFNは、本契約を変更する場合には、変更の内容及び変更の効力発生時期を、当該効力発生時期までにPFN所定の方法で告知するものとする。
126
+
127
+
128
+ 第13条(準拠法及び管轄裁判所)
129
+
130
+ (1) 本契約の準拠法は日本法とする。
131
+
132
+ (2) 本モデル等及び本契約に起因する紛争については、東京地方裁判所が専属的合意管轄裁判所とする。
README.md ADDED
@@ -0,0 +1,833 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: "other"
3
+ license_name: "plamo-community-license"
4
+ license_link: "https://plamo.preferredai.jp/info/plamo-community-license-en"
5
+ base_model: pfnet/plamo-3-translate-0.8b
6
+ base_model_relation: quantized
7
+ model_name: "PLaMo 3 Translate 0.8B W4AFP8"
8
+ library_name: transformers
9
+ language:
10
+ - ar
11
+ - az
12
+ - be
13
+ - bg
14
+ - bn
15
+ - ca
16
+ - ceb
17
+ - de
18
+ - en
19
+ - es
20
+ - et
21
+ - eu
22
+ - fa
23
+ - fr
24
+ - gu
25
+ - he
26
+ - hi
27
+ - hr
28
+ - hu
29
+ - hy
30
+ - id
31
+ - it
32
+ - ja
33
+ - jv
34
+ - ka
35
+ - kk
36
+ - km
37
+ - ko
38
+ - lt
39
+ - lv
40
+ - ml
41
+ - mr
42
+ - ms
43
+ - my
44
+ - ne
45
+ - nl
46
+ - pa
47
+ - pl
48
+ - ru
49
+ - si
50
+ - sk
51
+ - sl
52
+ - sr
53
+ - sw
54
+ - ta
55
+ - te
56
+ - th
57
+ - tl
58
+ - ur
59
+ - uz
60
+ - vi
61
+ - zh
62
+ pipeline_tag: translation
63
+ tags:
64
+ - translation
65
+ - multilingual
66
+ - custom_code
67
+ - plamo
68
+ - w4afp8
69
+ - int4
70
+ - fp8
71
+ - compressed-tensors
72
+ - vllm
73
+
74
+ ---
75
+
76
+ # PLaMo 3 Translate 0.8B W4AFP8
77
+
78
+ [日本語版のREADME / Japanese README](README_ja.md)
79
+
80
+ PLaMo 3 Translate 0.8B W4AFP8 is a version of [PLaMo 3 Translate 0.8B](https://huggingface.co/pfnet/plamo-3-translate-0.8b) with the weights quantized to INT4 and the activations to FP8. See [Choosing a Distribution Format](#choosing-a-distribution-format) to compare it with the other distribution formats. The vLLM launch command is the same as for the BF16 version.
81
+
82
+ PLaMo 3 Translate 0.8B is a translation-specialized LLM developed by Preferred Networks (PFN) that delivers world-class translation quality.
83
+ It is built on PLaMo 3 NICT, a pretrained model developed through joint research by PFN and the National Institute of Information and Communications Technology (NICT).
84
+ We further trained this base model on tens of billions of tokens of translation-focused data.
85
+ For development details, see the [tech blog](https://www.preferred.jp/en/blog/tech/plamo-3-translate-weight-release).
86
+
87
+ PLaMo 3 Translate 0.8B supports translation among 53 languages (see [Supported Languages](#supported-languages)).
88
+ It can also take surrounding context and a glossary into account, and lets you choose between plain and polite style for Japanese output.
89
+ The maximum length during training was 32,768 tokens for the input and output combined. The model can translate long passages in one go, but split anything longer so that the input and output together stay within this limit.
90
+
91
+ PLaMo 3 Translate 0.8B is available under the [PLaMo Community License](https://plamo.preferredai.jp/info/plamo-community-license-en). Personal use, such as learning or hobby projects, and other non-commercial use, including academic use, are free of charge with no prior registration. See [License](#license) for the terms of commercial use.
92
+
93
+ ## Benchmarks
94
+
95
+ PLaMo 3 Translate delivers world-class quality in both Japanese–English and multilingual translation. Even the 2B model outperforms the translation-specialized LLMs we compared against on every metric in the figure below.
96
+
97
+ ![Translation quality of PLaMo 3 Translate, TranslateGemma and HY-MT2](figures/benchmark_en.png)
98
+
99
+ The top row shows Japanese–English translation quality as the average of PFTB, SaaS and WMT24++ COMET-22. The middle row shows translation between Japanese and 14 other languages, and the bottom row between English and 14 other languages, each as the average of FLORES+ chrF++ in both directions. Higher is better for all scores.
100
+
101
+ For the FLORES+ multilingual evaluation, we selected the following 15 of the 53 supported languages. Translation was evaluated in both directions between Japanese or English and each of the remaining 14 languages.
102
+
103
+ - Japanese, English, Arabic, Indonesian, Italian, Dutch, Korean, Spanish, Thai, Chinese (Simplified and Traditional), German, French, Vietnamese, Russian
104
+
105
+ For details, see the [tech blog](https://www.preferred.jp/en/blog/tech/plamo-3-translate-weight-release).
106
+
107
+ ## Choosing a Model
108
+
109
+ ### Model List
110
+ PLaMo 3 Translate comes in four sizes: 0.8B, 2B, 8B and 31B.
111
+ For each size, quantized and converted variants are provided in separate repositories.
112
+
113
+ | Size | BF16 | FP8 | W4A16 | W4AFP8 | NVFP4 | GGUF | MLX |
114
+ | --- | --- | --- | --- | --- | --- | --- | --- |
115
+ | 0.8B | [BF16](https://huggingface.co/pfnet/plamo-3-translate-0.8b) | [FP8](https://huggingface.co/pfnet/plamo-3-translate-0.8b-FP8) | [W4A16](https://huggingface.co/pfnet/plamo-3-translate-0.8b-W4A16) | [W4AFP8](https://huggingface.co/pfnet/plamo-3-translate-0.8b-W4AFP8) | [NVFP4](https://huggingface.co/pfnet/plamo-3-translate-0.8b-NVFP4) | [GGUF](https://huggingface.co/pfnet/plamo-3-translate-0.8b-GGUF) | [MLX-4bit](https://huggingface.co/pfnet/plamo-3-translate-0.8b-MLX-4bit) |
116
+ | 2B | [BF16](https://huggingface.co/pfnet/plamo-3-translate-2b) | [FP8](https://huggingface.co/pfnet/plamo-3-translate-2b-FP8) | [W4A16](https://huggingface.co/pfnet/plamo-3-translate-2b-W4A16) | [W4AFP8](https://huggingface.co/pfnet/plamo-3-translate-2b-W4AFP8) | [NVFP4](https://huggingface.co/pfnet/plamo-3-translate-2b-NVFP4) | [GGUF](https://huggingface.co/pfnet/plamo-3-translate-2b-GGUF) | [MLX-4bit](https://huggingface.co/pfnet/plamo-3-translate-2b-MLX-4bit) |
117
+ | 8B | [BF16](https://huggingface.co/pfnet/plamo-3-translate-8b) | [FP8](https://huggingface.co/pfnet/plamo-3-translate-8b-FP8) | [W4A16](https://huggingface.co/pfnet/plamo-3-translate-8b-W4A16) | [W4AFP8](https://huggingface.co/pfnet/plamo-3-translate-8b-W4AFP8) | [NVFP4](https://huggingface.co/pfnet/plamo-3-translate-8b-NVFP4) | [GGUF](https://huggingface.co/pfnet/plamo-3-translate-8b-GGUF) | [MLX-4bit](https://huggingface.co/pfnet/plamo-3-translate-8b-MLX-4bit) |
118
+ | 31B | [BF16](https://huggingface.co/pfnet/plamo-3-translate-31b) | [FP8](https://huggingface.co/pfnet/plamo-3-translate-31b-FP8) | [W4A16](https://huggingface.co/pfnet/plamo-3-translate-31b-W4A16) | [W4AFP8](https://huggingface.co/pfnet/plamo-3-translate-31b-W4AFP8) | [NVFP4](https://huggingface.co/pfnet/plamo-3-translate-31b-NVFP4) | [GGUF](https://huggingface.co/pfnet/plamo-3-translate-31b-GGUF) | [MLX-4bit](https://huggingface.co/pfnet/plamo-3-translate-31b-MLX-4bit) |
119
+
120
+ <details>
121
+ <summary>Accuracy changes from quantization</summary>
122
+
123
+ For each model size, the tables compare the translation accuracy of BF16 with that of each distribution format. The value in parentheses under each score is the difference from BF16 of the same size (a negative value means lower accuracy). Higher is better for all scores.
124
+
125
+ For details on the evaluation metrics, see the [tech blog](https://www.preferred.jp/en/blog/tech/plamo-3-translate-weight-release).
126
+
127
+ Overall, `GGUF Q2_K` shows lower translation accuracy on some metrics, while the other formats stay close to BF16.
128
+
129
+ Size is the total size of the weight files.
130
+
131
+ #### 31B
132
+
133
+ | Format | Size (GB) | PFTB (En↔Ja) | SaaS (En→Ja) | WMT24++ COMET-22 (En→Ja) | FLORES+ chrF++ (Ja↔Multilingual) | FLORES+ chrF++ (En↔Multilingual) |
134
+ | --- | ---: | ---: | ---: | ---: | ---: | ---: |
135
+ | **BF16** | 63.51 | 0.6244 | 0.5786 | 0.8799 | 37.81 | 56.61 |
136
+ | FP8 | 32.31 | 0.6240<br>(-0.0004) | 0.5803<br>(+0.0017) | 0.8799<br>(0.0000) | 37.79<br>(-0.02) | 56.60<br>(-0.01) |
137
+ | W4A16 | 17.19 | 0.6258<br>(+0.0014) | 0.5777<br>(-0.0009) | 0.8805<br>(+0.0006) | 37.74<br>(-0.07) | 56.49<br>(-0.12) |
138
+ | W4AFP8 | 17.19 | 0.6223<br>(-0.0021) | 0.5716<br>(-0.0070) | 0.8813<br>(+0.0014) | 37.71<br>(-0.10) | 56.53<br>(-0.08) |
139
+ | NVFP4 | 18.66 | 0.6258<br>(+0.0014) | 0.5748<br>(-0.0038) | 0.8809<br>(+0.0010) | 37.70<br>(-0.11) | 56.49<br>(-0.12) |
140
+ | GGUF BF16 | 63.52 | 0.6241<br>(-0.0003) | 0.5793<br>(+0.0007) | 0.8799<br>(0.0000) | 37.82<br>(+0.01) | 56.59<br>(-0.02) |
141
+ | GGUF Q4_K_M | 19.53 | 0.6237<br>(-0.0007) | 0.5770<br>(-0.0016) | 0.8810<br>(+0.0011) | 37.84<br>(+0.03) | 56.55<br>(-0.06) |
142
+ | GGUF Q3_K_M | 15.86 | 0.6223<br>(-0.0021) | 0.5780<br>(-0.0006) | 0.8813<br>(+0.0014) | 37.78<br>(-0.03) | 56.54<br>(-0.07) |
143
+ | GGUF Q2_K | 12.61 | 0.6126<br>(-0.0118) | 0.5745<br>(-0.0041) | 0.8801<br>(+0.0002) | 37.36<br>(-0.45) | 56.16<br>(-0.45) |
144
+ | MLX 4bit | 18.66 | 0.6222<br>(-0.0022) | 0.5779<br>(-0.0007) | 0.8800<br>(+0.0001) | 37.82<br>(+0.01) | 56.58<br>(-0.03) |
145
+
146
+ #### 8B
147
+
148
+ | Format | Size (GB) | PFTB (En↔Ja) | SaaS (En→Ja) | WMT24++ COMET-22 (En→Ja) | FLORES+ chrF++ (Ja↔Multilingual) | FLORES+ chrF++ (En↔Multilingual) |
149
+ | --- | ---: | ---: | ---: | ---: | ---: | ---: |
150
+ | **BF16** | 17.06 | 0.6119 | 0.5750 | 0.8805 | 37.45 | 56.22 |
151
+ | FP8 | 9.41 | 0.6123<br>(+0.0004) | 0.5764<br>(+0.0014) | 0.8805<br>(0.0000) | 37.40<br>(-0.05) | 56.17<br>(-0.05) |
152
+ | W4A16 | 5.71 | 0.6114<br>(-0.0005) | 0.5749<br>(-0.0001) | 0.8789<br>(-0.0016) | 37.36<br>(-0.09) | 56.19<br>(-0.03) |
153
+ | W4AFP8 | 5.71 | 0.6174<br>(+0.0055) | 0.5759<br>(+0.0009) | 0.8794<br>(-0.0011) | 37.34<br>(-0.11) | 56.12<br>(-0.10) |
154
+ | NVFP4 | 6.07 | 0.6040<br>(-0.0079) | 0.5783<br>(+0.0033) | 0.8792<br>(-0.0013) | 37.26<br>(-0.19) | 56.10<br>(-0.12) |
155
+ | GGUF BF16 | 17.07 | 0.6110<br>(-0.0009) | 0.5755<br>(+0.0005) | 0.8802<br>(-0.0003) | 37.46<br>(+0.01) | 56.22<br>(0.00) |
156
+ | GGUF Q4_K_M | 5.28 | 0.6100<br>(-0.0019) | 0.5765<br>(+0.0015) | 0.8802<br>(-0.0003) | 37.39<br>(-0.06) | 56.18<br>(-0.04) |
157
+ | GGUF Q3_K_M | 4.31 | 0.6019<br>(-0.0100) | 0.5707<br>(-0.0043) | 0.8826<br>(+0.0021) | 37.20<br>(-0.25) | 55.93<br>(-0.29) |
158
+ | GGUF Q2_K | 3.45 | 0.5989<br>(-0.0130) | 0.5676<br>(-0.0074) | 0.8791<br>(-0.0014) | 36.54<br>(-0.91) | 55.31<br>(-0.91) |
159
+ | MLX 4bit | 6.07 | 0.6102<br>(-0.0017) | 0.5751<br>(+0.0001) | 0.8796<br>(-0.0009) | 37.41<br>(-0.04) | 56.19<br>(-0.03) |
160
+
161
+ #### 2B
162
+
163
+ | Format | Size (GB) | PFTB (En↔Ja) | SaaS (En→Ja) | WMT24++ COMET-22 (En→Ja) | FLORES+ chrF++ (Ja↔Multilingual) | FLORES+ chrF++ (En↔Multilingual) |
164
+ | --- | ---: | ---: | ---: | ---: | ---: | ---: |
165
+ | **BF16** | 5.76 | 0.6061 | 0.5612 | 0.8780 | 37.02 | 55.74 |
166
+ | FP8 | 3.43 | 0.6067<br>(+0.0006) | 0.5613<br>(+0.0001) | 0.8776<br>(-0.0004) | 36.98<br>(-0.04) | 55.76<br>(+0.02) |
167
+ | W4A16 | 2.30 | 0.6032<br>(-0.0029) | 0.5594<br>(-0.0018) | 0.8783<br>(+0.0003) | 36.96<br>(-0.06) | 55.69<br>(-0.05) |
168
+ | W4AFP8 | 2.30 | 0.6022<br>(-0.0039) | 0.5612<br>(0.0000) | 0.8772<br>(-0.0008) | 36.95<br>(-0.07) | 55.71<br>(-0.03) |
169
+ | NVFP4 | 2.41 | 0.6032<br>(-0.0029) | 0.5626<br>(+0.0014) | 0.8783<br>(+0.0003) | 36.82<br>(-0.20) | 55.64<br>(-0.10) |
170
+ | GGUF BF16 | 5.76 | 0.6062<br>(+0.0001) | 0.5619<br>(+0.0007) | 0.8782<br>(+0.0002) | 37.02<br>(0.00) | 55.75<br>(+0.01) |
171
+ | GGUF Q4_K_M | 1.81 | 0.6062<br>(+0.0001) | 0.5602<br>(-0.0010) | 0.8774<br>(-0.0006) | 37.00<br>(-0.02) | 55.76<br>(+0.02) |
172
+ | GGUF Q4_0 | 1.70 | 0.6069<br>(+0.0008) | 0.5604<br>(-0.0008) | 0.8791<br>(+0.0011) | 36.12<br>(-0.90) | 55.62<br>(-0.12) |
173
+ | GGUF Q3_K_M | 1.50 | 0.6053<br>(-0.0008) | 0.5644<br>(+0.0032) | 0.8789<br>(+0.0009) | 36.81<br>(-0.21) | 55.59<br>(-0.15) |
174
+ | GGUF Q2_K | 1.23 | 0.5977<br>(-0.0084) | 0.5610<br>(-0.0002) | 0.8777<br>(-0.0003) | 36.45<br>(-0.57) | 55.02<br>(-0.72) |
175
+ | MLX 4bit | 2.41 | 0.6040<br>(-0.0021) | 0.5624<br>(+0.0012) | 0.8777<br>(-0.0003) | 36.99<br>(-0.03) | 55.64<br>(-0.10) |
176
+
177
+ #### 0.8B
178
+
179
+ | Format | Size (GB) | PFTB (En↔Ja) | SaaS (En→Ja) | WMT24++ COMET-22 (En→Ja) | FLORES+ chrF++ (Ja↔Multilingual) | FLORES+ chrF++ (En↔Multilingual) |
180
+ | --- | ---: | ---: | ---: | ---: | ---: | ---: |
181
+ | **BF16** | 1.78 | 0.5862 | 0.5530 | 0.8724 | 36.08 | 54.44 |
182
+ | FP8 | 1.22 | 0.5846<br>(-0.0016) | 0.5491<br>(-0.0039) | 0.8726<br>(+0.0002) | 36.00<br>(-0.08) | 54.60<br>(+0.16) |
183
+ | W4A16 | 0.95 | 0.5847<br>(-0.0015) | 0.5439<br>(-0.0091) | 0.8711<br>(-0.0013) | 35.78<br>(-0.30) | 53.95<br>(-0.49) |
184
+ | W4AFP8 | 0.95 | 0.5783<br>(-0.0079) | 0.5456<br>(-0.0074) | 0.8718<br>(-0.0006) | 35.75<br>(-0.33) | 54.38<br>(-0.06) |
185
+ | NVFP4 | 0.98 | 0.5787<br>(-0.0075) | 0.5436<br>(-0.0094) | 0.8702<br>(-0.0022) | 35.54<br>(-0.54) | 54.20<br>(-0.24) |
186
+ | GGUF BF16 | 1.78 | 0.5873<br>(+0.0011) | 0.5533<br>(+0.0003) | 0.8727<br>(+0.0003) | 36.10<br>(+0.02) | 54.45<br>(+0.01) |
187
+ | GGUF Q4_K_M | 0.57 | 0.5832<br>(-0.0030) | 0.5451<br>(-0.0079) | 0.8716<br>(-0.0008) | 35.90<br>(-0.18) | 54.47<br>(+0.03) |
188
+ | GGUF Q4_0 | 0.55 | 0.5853<br>(-0.0009) | 0.5500<br>(-0.0030) | 0.8723<br>(-0.0001) | 34.97<br>(-1.11) | 54.11<br>(-0.33) |
189
+ | GGUF Q3_K_M | 0.49 | 0.5798<br>(-0.0064) | 0.5520<br>(-0.0010) | 0.8710<br>(-0.0014) | 35.32<br>(-0.76) | 54.15<br>(-0.29) |
190
+ | GGUF Q2_K | 0.41 | 0.5620<br>(-0.0242) | 0.5397<br>(-0.0133) | 0.8659<br>(-0.0065) | 33.56<br>(-2.52) | 51.15<br>(-3.29) |
191
+ | MLX 4bit | 0.98 | 0.5773<br>(-0.0089) | 0.5476<br>(-0.0054) | 0.8724<br>(0.0000) | 35.82<br>(-0.26) | 54.41<br>(-0.03) |
192
+
193
+ </details>
194
+
195
+ ### Choosing a Distribution Format
196
+
197
+ Each size of PLaMo 3 Translate is available in the following distribution formats, depending on your use case and hardware.
198
+
199
+ | Format | Target hardware | Inference engine | Typical use |
200
+ | --- | --- | --- | --- |
201
+ | BF16 | GPUs with BF16 support | Transformers / vLLM | Prioritizes accuracy with no quantization, when memory allows |
202
+ | FP8 | NVIDIA Ada Lovelace / Hopper / Blackwell | vLLM | Balances accuracy with memory savings and speed |
203
+ | W4A16 | NVIDIA Ampere or later | vLLM | 4-bit weights to run with less GPU memory |
204
+ | **W4AFP8** | NVIDIA Hopper | vLLM | 4-bit weights with FP8 compute, aiming at both low memory and high throughput |
205
+ | NVFP4 | NVIDIA Blackwell | vLLM | FP4 compute, aiming at low memory and high speed |
206
+ | GGUF | CPU / various GPUs | llama.cpp | Runs on a local PC, optionally combining CPU and GPU |
207
+ | MLX-4bit | Apple silicon | mlx-lm | Memory-efficient inference on a Mac |
208
+
209
+ ## Usage
210
+
211
+ To run with less memory, see the [vLLM instructions](#vllm).
212
+
213
+ ### Transformers
214
+
215
+ In Transformers, the quantized weights are expanded to BF16 for inference, so quantization does not reduce memory usage.
216
+
217
+ Download the model files and move into that directory. Run the following examples in this directory.
218
+
219
+ ```bash
220
+ pip install -U huggingface_hub
221
+ hf download pfnet/plamo-3-translate-0.8b-W4AFP8 --local-dir plamo-3-translate-0.8b-W4AFP8
222
+ cd plamo-3-translate-0.8b-W4AFP8
223
+ ```
224
+
225
+ Install the required packages.
226
+
227
+ ```bash
228
+ pip install -U torch transformers accelerate numba compressed-tensors
229
+ ```
230
+
231
+ #### Translating a single text
232
+
233
+ A chat template is provided so you can try translation easily. Given the source text and the target language, it builds a prompt in the PFML3 format.
234
+
235
+ For production use, such as integrating the model into an application, we recommend building the prompt directly in the [PFML3 format](#pfml3-prompt-format) and passing it to the [vLLM Completions API](#translating-with-the-completions-api).
236
+
237
+ The following example translates Japanese into English.
238
+
239
+ ```python
240
+ from transformers import AutoModelForCausalLM, AutoTokenizer
241
+
242
+ tokenizer = AutoTokenizer.from_pretrained(".", trust_remote_code=True)
243
+ model = AutoModelForCausalLM.from_pretrained(
244
+ ".", trust_remote_code=True, dtype="bfloat16", device_map="auto",
245
+ )
246
+
247
+ inputs = tokenizer.apply_chat_template(
248
+ [{"role": "user", "content": "会議は来週の月曜日に変更されました。"}],
249
+ target_lang="en",
250
+ add_generation_prompt=True,
251
+ return_dict=True, return_tensors="pt",
252
+ ).to(model.device)
253
+
254
+ output = model.generate(**inputs, do_sample=False, max_new_tokens=512)
255
+ text = tokenizer.decode(output[0, inputs["input_ids"].shape[1]:], skip_special_tokens=True)
256
+ print(text)
257
+ ```
258
+
259
+ `max_new_tokens` is the generation limit for the translation. This example sets it to 512 tokens. When translating long text, adjust the limit so that the whole input (source text, history, context, glossary and so on) plus the output fits within the limit of your runtime.
260
+
261
+ Example output:
262
+
263
+ > The meeting has been rescheduled for next Monday.
264
+
265
+ The example above does not specify the source language. When `source_lang` is omitted, the model detects the language from the source text. To specify it explicitly, pass `source_lang="ja"`, for example.
266
+
267
+ #### Translating multiple texts at once
268
+
269
+ Multiple texts can be translated in a batch by passing them to the chat template together. The following example uses the `model` and `tokenizer` loaded above to translate two texts into English.
270
+
271
+ ```python
272
+ tokenizer.padding_side = "left"
273
+ texts = [
274
+ "会議は来週の月曜日に変更されました。",
275
+ "プロジェクトの管理画面を開いてください。",
276
+ ]
277
+ messages = [[{"role": "user", "content": text}] for text in texts]
278
+
279
+ inputs = tokenizer.apply_chat_template(
280
+ messages,
281
+ target_lang="en",
282
+ add_generation_prompt=True,
283
+ padding=True,
284
+ return_dict=True, return_tensors="pt",
285
+ ).to(model.device)
286
+
287
+ outputs = model.generate(**inputs, do_sample=False, max_new_tokens=512)
288
+ translations = tokenizer.batch_decode(
289
+ outputs[:, inputs["input_ids"].shape[1]:], skip_special_tokens=True,
290
+ )
291
+ for source, translation in zip(texts, translations):
292
+ print(f"{source} → {translation}")
293
+ ```
294
+
295
+ The inputs are padded on the left to equalize their lengths, and only the generated translations are extracted. Translation options such as `target_lang` apply to every text in the batch in this example.
296
+
297
+ ### Continuing a translation with previous translations
298
+
299
+ When translating a document paragraph by paragraph, you can pass the previous source–translation pairs as history. This lets the model follow the earlier word choices and style when translating the next passage.
300
+
301
+ With the chat template, alternate the source text as `user` and its translation as `assistant`, and put the current source text in the final `user` message. History is not stored automatically, so include the pairs you need in each request.
302
+
303
+ The translation direction is shared by the whole request: `source_lang` applies to every source text and `target_lang` to every translation.
304
+
305
+ History also counts toward the input tokens. Keep the whole input plus the generated translation within 32,768 tokens and within the limit of your runtime. As the history grows, we recommend dropping the oldest source–translation pairs first and keeping the most recent ones.
306
+
307
+ This example uses the `model` and `tokenizer` loaded above.
308
+
309
+ ```python
310
+ messages = [
311
+ {"role": "user", "content": "プロジェクトの管理画面を開きます。"},
312
+ {"role": "assistant", "content": "Open the project dashboard."},
313
+ {"role": "user", "content": "進行中のタスクがすべて表示されます。"},
314
+ {"role": "assistant", "content": "It lists all active tasks."},
315
+ {"role": "user", "content": "オーナーでフィルタリングすることもできます。"},
316
+ ]
317
+
318
+ inputs = tokenizer.apply_chat_template(
319
+ messages, source_lang="ja", target_lang="en",
320
+ add_generation_prompt=True,
321
+ return_dict=True, return_tensors="pt",
322
+ ).to(model.device)
323
+ output = model.generate(**inputs, do_sample=False, max_new_tokens=512)
324
+ text = tokenizer.decode(output[0, inputs["input_ids"].shape[1]:], skip_special_tokens=True)
325
+ print(text)
326
+ ```
327
+
328
+ ### PFML3 Prompt Format
329
+
330
+ PFML3 is PLaMo's prompt format, in which the text to translate, the target language and other elements are delimited by special tokens. In the Transformers examples above, the chat template converts the source text and target language into PFML3. This section explains how to read the converted prompt and how to write prompts by hand.
331
+
332
+ For production use, we recommend building the prompt directly in PFML3 and passing it to the [vLLM Completions API](#translating-with-the-completions-api).
333
+
334
+ Converting the Transformers example above into PFML3 gives the following. The beginning-of-sequence token is omitted here, and the Python string is split across lines for readability. The actual prompt contains no line breaks.
335
+
336
+ ```python
337
+ prompt = (
338
+ "<|plamo:tag|>dataset<|plamo:msg|>translation"
339
+ "<|plamo:tag|>input"
340
+ "<|plamo:msg|>会議は来週の月曜日に変更されました。"
341
+ "<|plamo:tag|>output<|plamo:key|>lang<|plamo:val|>en<|plamo:msg|>"
342
+ )
343
+ ```
344
+
345
+ - `translation` in `dataset` denotes the translation task. Because this model is dedicated to translation, always set `dataset` to `translation`.
346
+ - The part following `<|plamo:msg|>` in `input` is the source text to translate.
347
+ - `<|plamo:key|>lang<|plamo:val|>en` in `output` sets the target language to English. The translation is generated right after the final `<|plamo:msg|>`.
348
+
349
+ `<|plamo:tag|>` marks the start of each element, and `<|plamo:msg|>` marks the start of its body. To specify attributes such as the language or style, write the attribute name after `<|plamo:key|>` and its value after `<|plamo:val|>`, following the element name. For example, adding `<|plamo:key|>form<|plamo:val|>plain` to `output` requests plain style.
350
+
351
+ Context and a glossary are optional. To use them, add `context` and then `glossary`, in that order, between `dataset` and `input`. When translation history is also used, put `context` right after `dataset`, list the previous `input`/`output` pairs, and put `glossary` immediately before the current `input`. In the glossary, write a source term after `<|plamo:index|>` and its translation after `<|plamo:item|>`, repeating this pair for each term. See [Translation Options](#translation-options) for concrete examples.
352
+
353
+ #### Using a handwritten prompt
354
+
355
+ When writing PFML3 by hand, start by setting `dataset` to `translation` and end the `output` element with `<|plamo:msg|>`. After generating the translation, the model emits `<|plamo:tag|>` or `<|plamo:bos|>` and stops.
356
+
357
+ The handwritten examples above omit `<|plamo:bos|>`, which marks the beginning of the sequence. The Transformers tokenizer, llama.cpp and mlx-lm add the beginning-of-sequence token automatically. With the vLLM Completions API, specify `add_special_tokens=true`.
358
+
359
+ A string produced by the chat template already contains the beginning-of-sequence token. If you pass a string obtained with `tokenize=False` to the Transformers tokenizer, specify `add_special_tokens=False` to avoid adding it twice.
360
+
361
+ For example, to pass a handwritten prompt to Transformers, use the `model` and `tokenizer` from the Transformers example above.
362
+
363
+ ```python
364
+ inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
365
+ output = model.generate(**inputs, do_sample=False, max_new_tokens=512)
366
+ text = tokenizer.decode(output[0, inputs["input_ids"].shape[1]:], skip_special_tokens=True)
367
+ print(text)
368
+ ```
369
+
370
+ #### Specifying translation history in PFML3
371
+
372
+ Translation history can also be written in PFML3 by hand. List the already translated `input` and `output` elements in document order, then add the current source text followed by an `output` element with an empty body. In the following example, only the last sentence, "オーナーでフィルタリングすることもできます。", is translated, with reference to the two previous pairs.
373
+
374
+ ```python
375
+ prompt = (
376
+ "<|plamo:tag|>dataset<|plamo:msg|>translation"
377
+ "<|plamo:tag|>input<|plamo:key|>lang<|plamo:val|>ja<|plamo:msg|>プロジェクトの管理画面を開きます。"
378
+ "<|plamo:tag|>output<|plamo:key|>lang<|plamo:val|>en<|plamo:msg|>Open the project dashboard."
379
+ "<|plamo:tag|>input<|plamo:key|>lang<|plamo:val|>ja<|plamo:msg|>進行中のタスクがすべて表示されます。"
380
+ "<|plamo:tag|>output<|plamo:key|>lang<|plamo:val|>en<|plamo:msg|>It lists all active tasks."
381
+ "<|plamo:tag|>input<|plamo:key|>lang<|plamo:val|>ja<|plamo:msg|>オーナーでフィルタリングすることもできます。"
382
+ "<|plamo:tag|>output<|plamo:key|>lang<|plamo:val|>en<|plamo:msg|>"
383
+ )
384
+ ```
385
+
386
+ Run the example in "Using a handwritten prompt" above with `prompt` replaced by this string.
387
+
388
+ To continue translating, append the current source text and the generated translation to the history as a pair. Then add an `input` element containing the next source text and an `output` element with an empty body.
389
+
390
+ Keep only the body of each translation in the history. The translation returned by the example above can be used as is.
391
+
392
+ If `<|plamo:tag|>` or `<|plamo:bos|>` remains at the end of a translation, remove it so that exactly one `<|plamo:tag|>` separates it from the next `input`.
393
+
394
+ ### Translation Options
395
+
396
+ Specify the target language, style, context, glossary and other options as arguments to `apply_chat_template()`, not in a `system` message or in the source text.
397
+
398
+ Run the Transformers example above with the part that builds `inputs` replaced by the following code.
399
+
400
+ | Argument | Description |
401
+ | --- | --- |
402
+ | `target_lang` | Language code of the target language. Required. |
403
+ | `source_lang` | Language code of the source text. Optional. |
404
+ | `context` | Reference context for interpreting the source text, such as the surrounding text or the situation. |
405
+ | `glossary` | A list of `{"source": "source term", "target": "translation"}` dictionaries, one per term. |
406
+ | `form` | `plain` for plain style or `polite` for polite style (only with `target_lang="ja"`). |
407
+
408
+ When combined with translation history, `context` is passed as reference context for the whole request, while `glossary` and `form` apply to the current translation. Previous translations themselves are not changed.
409
+
410
+ #### Specifying terms with a glossary
411
+
412
+ Pass pairs of source terms and their translations in `glossary` to control how the terms are translated.
413
+
414
+ ```python
415
+ inputs = tokenizer.apply_chat_template(
416
+ [{"role": "user", "content": "プロジェクトの管理画面を開いてください。"}],
417
+ target_lang="en",
418
+ glossary=[
419
+ {"source": "管理画面", "target": "dashboard"},
420
+ {"source": "プロジェクト", "target": "project"},
421
+ ],
422
+ add_generation_prompt=True,
423
+ return_dict=True, return_tensors="pt",
424
+ ).to(model.device)
425
+ ```
426
+
427
+ Example output:
428
+
429
+ > Please open the project dashboard.
430
+
431
+ <details>
432
+ <summary>PFML3 prompt for this example</summary>
433
+
434
+ ```python
435
+ prompt = (
436
+ "<|plamo:tag|>dataset<|plamo:msg|>translation"
437
+ "<|plamo:tag|>glossary"
438
+ "<|plamo:index|>管理画面<|plamo:item|>dashboard"
439
+ "<|plamo:index|>プロジェクト<|plamo:item|>project"
440
+ "<|plamo:tag|>input<|plamo:msg|>プロジェクトの管理画面を開いてください。"
441
+ "<|plamo:tag|>output<|plamo:key|>lang<|plamo:val|>en<|plamo:msg|>"
442
+ )
443
+ ```
444
+
445
+ </details>
446
+
447
+ #### Providing context
448
+
449
+ Use `context` to pass the surrounding text or to describe the situation. In this example, the source text かみを切りました。 is ambiguous because かみ can mean either hair or paper. The context says that the speaker is making origami, so it is translated as paper.
450
+
451
+ ```python
452
+ inputs = tokenizer.apply_chat_template(
453
+ [{"role": "user", "content": "かみを切りました。"}],
454
+ target_lang="en",
455
+ context="工作で折り紙を作っています。",
456
+ add_generation_prompt=True,
457
+ return_dict=True, return_tensors="pt",
458
+ ).to(model.device)
459
+ ```
460
+
461
+ Example output:
462
+
463
+ > I cut the paper.
464
+
465
+ <details>
466
+ <summary>PFML3 prompt for this example</summary>
467
+
468
+ ```python
469
+ prompt = (
470
+ "<|plamo:tag|>dataset<|plamo:msg|>translation"
471
+ "<|plamo:tag|>context"
472
+ "<|plamo:msg|>工作で折り紙を作っています。"
473
+ "<|plamo:tag|>input<|plamo:msg|>かみを切りました。"
474
+ "<|plamo:tag|>output<|plamo:key|>lang<|plamo:val|>en<|plamo:msg|>"
475
+ )
476
+ ```
477
+
478
+ </details>
479
+
480
+ #### Specifying plain or polite style
481
+
482
+ When translating into Japanese, `form="plain"` requests the plain style (da/dearu) and `form="polite"` requests the polite style (desu/masu). Because `form` applies only to Japanese translations, this example translates English into Japanese.
483
+
484
+ ```python
485
+ inputs = tokenizer.apply_chat_template(
486
+ [{"role": "user", "content": "This system is convenient."}],
487
+ target_lang="ja",
488
+ form="plain",
489
+ add_generation_prompt=True,
490
+ return_dict=True, return_tensors="pt",
491
+ ).to(model.device)
492
+ ```
493
+
494
+ Example outputs for the same source text:
495
+
496
+ | Style | Option | Translation |
497
+ | --- | --- | --- |
498
+ | Plain | `form="plain"` | このシステムは便利だ。 |
499
+ | Polite | `form="polite"` | このシステムは便利です。 |
500
+
501
+ <details>
502
+ <summary>PFML3 prompt for this example</summary>
503
+
504
+ Plain:
505
+
506
+ ```python
507
+ prompt = (
508
+ "<|plamo:tag|>dataset<|plamo:msg|>translation"
509
+ "<|plamo:tag|>input<|plamo:msg|>This system is convenient."
510
+ "<|plamo:tag|>output<|plamo:key|>lang<|plamo:val|>ja"
511
+ "<|plamo:key|>form<|plamo:val|>plain<|plamo:msg|>"
512
+ )
513
+ ```
514
+
515
+ Polite:
516
+
517
+ ```python
518
+ prompt = (
519
+ "<|plamo:tag|>dataset<|plamo:msg|>translation"
520
+ "<|plamo:tag|>input<|plamo:msg|>This system is convenient."
521
+ "<|plamo:tag|>output<|plamo:key|>lang<|plamo:val|>ja"
522
+ "<|plamo:key|>form<|plamo:val|>polite<|plamo:msg|>"
523
+ )
524
+ ```
525
+ </details>
526
+
527
+ #### Specifying all options at once
528
+
529
+ Translation history, context, a glossary and the style can be combined in one request. The following example translates the third sentence after two previous pairs, passing the page type as context and fixing the translation of オーナー with the glossary. `context` is passed as reference context for the whole request, and `glossary` applies to the current translation. When translating into Japanese, `form` can be added in the same way.
530
+
531
+ ```python
532
+ inputs = tokenizer.apply_chat_template(
533
+ [
534
+ {"role": "user", "content": "プロジェクトの管理画面を開きます。"},
535
+ {"role": "assistant", "content": "Open the project dashboard."},
536
+ {"role": "user", "content": "進行中のタスクがすべて表示されます。"},
537
+ {"role": "assistant", "content": "It lists all active tasks."},
538
+ {"role": "user", "content": "オーナーでフィルタリングすることもできます。"},
539
+ ],
540
+ source_lang="ja", target_lang="en",
541
+ context="プロジェクト管理ツールのヘルプページです。",
542
+ glossary=[{"source": "オーナー", "target": "assignee"}],
543
+ add_generation_prompt=True,
544
+ return_dict=True, return_tensors="pt",
545
+ ).to(model.device)
546
+ ```
547
+
548
+ Example output:
549
+
550
+ > You can also filter by assignee.
551
+
552
+ <details>
553
+ <summary>PFML3 prompt for this example</summary>
554
+
555
+ ```python
556
+ prompt = (
557
+ "<|plamo:tag|>dataset<|plamo:msg|>translation"
558
+ "<|plamo:tag|>context<|plamo:msg|>プロジェクト管理ツールのヘルプページです。"
559
+ "<|plamo:tag|>input<|plamo:key|>lang<|plamo:val|>ja<|plamo:msg|>プロジェクトの管理画面を開きます。"
560
+ "<|plamo:tag|>output<|plamo:key|>lang<|plamo:val|>en<|plamo:msg|>Open the project dashboard."
561
+ "<|plamo:tag|>input<|plamo:key|>lang<|plamo:val|>ja<|plamo:msg|>進行中のタスクがすべて表示されます。"
562
+ "<|plamo:tag|>output<|plamo:key|>lang<|plamo:val|>en<|plamo:msg|>It lists all active tasks."
563
+ "<|plamo:tag|>glossary<|plamo:index|>オーナー<|plamo:item|>assignee"
564
+ "<|plamo:tag|>input<|plamo:key|>lang<|plamo:val|>ja<|plamo:msg|>オーナーでフィルタリングすることもできます。"
565
+ "<|plamo:tag|>output<|plamo:key|>lang<|plamo:val|>en<|plamo:msg|>"
566
+ )
567
+ ```
568
+
569
+ </details>
570
+
571
+ ### vLLM
572
+
573
+ #### Starting the server
574
+
575
+ Download the model files and move into that directory. Skip this step if you have already downloaded them by following the [Transformers](#transformers) instructions.
576
+
577
+ ```bash
578
+ pip install -U huggingface_hub
579
+ hf download pfnet/plamo-3-translate-0.8b-W4AFP8 --local-dir plamo-3-translate-0.8b-W4AFP8
580
+ cd plamo-3-translate-0.8b-W4AFP8
581
+ ```
582
+
583
+ Install the required packages and start the vLLM server.
584
+
585
+ ```bash
586
+ pip install -U vllm openai numba
587
+
588
+ vllm serve . --trust-remote-code \
589
+ --served-model-name plamo-3-translate \
590
+ --max-model-len 16384 --max-num-seqs 4
591
+ ```
592
+
593
+ This example sets the maximum combined length of the input and output to 16,384 tokens. Adjust it to fit the available GPU memory as needed.
594
+
595
+ #### Translating with the Chat Completions API
596
+
597
+ With the Chat Completions API, put the current source text in the last `user` message and pass the translation options in `chat_template_kwargs`.
598
+
599
+ ```bash
600
+ curl http://localhost:8000/v1/chat/completions \
601
+ -H 'Content-Type: application/json' \
602
+ -d '{
603
+ "model": "plamo-3-translate",
604
+ "messages": [{"role": "user", "content": "こんにちは。"}],
605
+ "chat_template_kwargs": {"source_lang": "ja", "target_lang": "en"},
606
+ "temperature": 0,
607
+ "max_tokens": 512,
608
+ "stop": ["<|plamo:tag|>", "<|plamo:bos|>"]
609
+ }'
610
+ ```
611
+
612
+ `max_tokens` is the generation limit for the translation. This example sets it to 512 tokens. When translating long text, adjust the limit so that the whole input (source text, history, context, glossary and so on) plus the output fits within the limit of your runtime.
613
+
614
+ The translation is returned in `choices[0].message.content`.
615
+
616
+ **Translating multiple texts at once**
617
+
618
+ To translate multiple texts, send one request per text and run the requests in parallel. vLLM batches the requests it receives.
619
+
620
+ ```python
621
+ from concurrent.futures import ThreadPoolExecutor
622
+ from openai import OpenAI
623
+
624
+ client = OpenAI(base_url="http://localhost:8000/v1", api_key="EMPTY")
625
+ texts = [
626
+ "会議は来週の月曜日に変更されました。",
627
+ "プロジェクトの管理画面を開いてください。",
628
+ ]
629
+
630
+ def translate(text):
631
+ response = client.chat.completions.create(
632
+ model="plamo-3-translate",
633
+ messages=[{"role": "user", "content": text}],
634
+ temperature=0,
635
+ max_tokens=512,
636
+ stop=["<|plamo:tag|>", "<|plamo:bos|>"],
637
+ extra_body={"chat_template_kwargs": {"target_lang": "en"}},
638
+ )
639
+ return response.choices[0].message.content
640
+
641
+ with ThreadPoolExecutor(max_workers=4) as executor:
642
+ translations = list(executor.map(translate, texts))
643
+
644
+ for source, translation in zip(texts, translations):
645
+ print(f"{source} → {translation}")
646
+ ```
647
+
648
+ **Translating with history via the Chat Completions API**
649
+
650
+ Pass the already translated source–translation pairs as `user`/`assistant` pairs. Only the last `user` message is translated.
651
+
652
+ ```python
653
+ from openai import OpenAI
654
+
655
+ client = OpenAI(base_url="http://localhost:8000/v1", api_key="EMPTY")
656
+ messages = [
657
+ {"role": "user", "content": "プロジェクトの管理画面を開きます。"},
658
+ {"role": "assistant", "content": "Open the project dashboard."},
659
+ {"role": "user", "content": "進行中のタスクがすべて表示されます。"},
660
+ {"role": "assistant", "content": "It lists all active tasks."},
661
+ {"role": "user", "content": "オーナーでフィルタリングすることもできます。"},
662
+ ]
663
+
664
+ response = client.chat.completions.create(
665
+ model="plamo-3-translate",
666
+ messages=messages,
667
+ temperature=0,
668
+ max_tokens=512,
669
+ stop=["<|plamo:tag|>", "<|plamo:bos|>"],
670
+ extra_body={"chat_template_kwargs": {"source_lang": "ja", "target_lang": "en"}},
671
+ )
672
+ print(response.choices[0].message.content)
673
+ ```
674
+
675
+ #### Translating with the Completions API
676
+
677
+ Pass one of the PFML3 prompts shown in the translation examples as `prompt`.
678
+
679
+ ```python
680
+ from openai import OpenAI
681
+
682
+ client = OpenAI(base_url="http://localhost:8000/v1", api_key="EMPTY")
683
+ prompt = (
684
+ "<|plamo:tag|>dataset<|plamo:msg|>translation"
685
+ "<|plamo:tag|>input"
686
+ "<|plamo:msg|>会議は来週の月曜日に変更されました。"
687
+ "<|plamo:tag|>output<|plamo:key|>lang<|plamo:val|>en<|plamo:msg|>"
688
+ )
689
+
690
+ response = client.completions.create(
691
+ model="plamo-3-translate",
692
+ prompt=prompt,
693
+ temperature=0,
694
+ max_tokens=512,
695
+ stop=["<|plamo:tag|>", "<|plamo:bos|>"],
696
+ extra_body={"add_special_tokens": True},
697
+ )
698
+ print(response.choices[0].text)
699
+ ```
700
+
701
+ The translation is returned in `choices[0].text`.
702
+
703
+ **Translating multiple texts at once**
704
+
705
+ When using PFML3 prompts directly, you can likewise send one request per text in parallel.
706
+
707
+ ```python
708
+ from concurrent.futures import ThreadPoolExecutor
709
+ from openai import OpenAI
710
+
711
+ client = OpenAI(base_url="http://localhost:8000/v1", api_key="EMPTY")
712
+ texts = [
713
+ "会議は来週の月曜日に変更されました。",
714
+ "プロジェクトの管理画面を開いてください。",
715
+ ]
716
+
717
+ def translate(text):
718
+ prompt = (
719
+ "<|plamo:tag|>dataset<|plamo:msg|>translation"
720
+ "<|plamo:tag|>input<|plamo:msg|>"
721
+ f"{text}"
722
+ "<|plamo:tag|>output<|plamo:key|>lang<|plamo:val|>en<|plamo:msg|>"
723
+ )
724
+ response = client.completions.create(
725
+ model="plamo-3-translate",
726
+ prompt=prompt,
727
+ temperature=0,
728
+ max_tokens=512,
729
+ stop=["<|plamo:tag|>", "<|plamo:bos|>"],
730
+ extra_body={"add_special_tokens": True},
731
+ )
732
+ return response.choices[0].text
733
+
734
+ with ThreadPoolExecutor(max_workers=4) as executor:
735
+ translations = list(executor.map(translate, texts))
736
+
737
+ for source, translation in zip(texts, translations):
738
+ print(f"{source} → {translation}")
739
+ ```
740
+
741
+ **Continuing a translation with history**
742
+
743
+ Translation with [history](#continuing-a-translation-with-previous-translations) also works with the Completions API. Pass a PFML3 prompt that includes the already translated source–translation pairs, and the translation of the last source text is returned.
744
+
745
+ ```python
746
+ from openai import OpenAI
747
+
748
+ client = OpenAI(base_url="http://localhost:8000/v1", api_key="EMPTY")
749
+ prompt = (
750
+ "<|plamo:tag|>dataset<|plamo:msg|>translation"
751
+ "<|plamo:tag|>input<|plamo:key|>lang<|plamo:val|>ja<|plamo:msg|>プロジェクトの管理画面を開きます。"
752
+ "<|plamo:tag|>output<|plamo:key|>lang<|plamo:val|>en<|plamo:msg|>Open the project dashboard."
753
+ "<|plamo:tag|>input<|plamo:key|>lang<|plamo:val|>ja<|plamo:msg|>進行中のタスクがすべて表示されます。"
754
+ "<|plamo:tag|>output<|plamo:key|>lang<|plamo:val|>en<|plamo:msg|>It lists all active tasks."
755
+ "<|plamo:tag|>input<|plamo:key|>lang<|plamo:val|>ja<|plamo:msg|>オーナーでフィルタリングすることもできます。"
756
+ "<|plamo:tag|>output<|plamo:key|>lang<|plamo:val|>en<|plamo:msg|>"
757
+ )
758
+
759
+ response = client.completions.create(
760
+ model="plamo-3-translate",
761
+ prompt=prompt,
762
+ temperature=0,
763
+ max_tokens=512,
764
+ stop=["<|plamo:tag|>", "<|plamo:bos|>"],
765
+ extra_body={"add_special_tokens": True},
766
+ )
767
+ print(response.choices[0].text)
768
+ ```
769
+
770
+ ## Supported Languages
771
+
772
+ 53 languages are supported, including Japanese and English. Simplified and Traditional Chinese are counted as separate languages. Because Hugging Face groups Chinese as a single language in its language display, the model page shows 52 languages.
773
+
774
+ <details>
775
+ <summary>Supported languages and language codes</summary>
776
+
777
+ | Language | Code | Language | Code |
778
+ |---|---|---|---|
779
+ | Japanese | `ja` | English | `en` |
780
+ | Chinese (Simplified) | `zh-hans` | Chinese (Traditional) | `zh-hant` |
781
+ | Korean | `ko` | Arabic | `ar` |
782
+ | Azerbaijani | `az` | Belarusian | `be` |
783
+ | Bulgarian | `bg` | Bengali | `bn` |
784
+ | Catalan | `ca` | Cebuano | `ceb` |
785
+ | German | `de` | Spanish | `es` |
786
+ | Estonian | `et` | Basque | `eu` |
787
+ | Persian | `fa` | French | `fr` |
788
+ | Gujarati | `gu` | Hebrew | `he` |
789
+ | Hindi | `hi` | Croatian | `hr` |
790
+ | Hungarian | `hu` | Armenian | `hy` |
791
+ | Indonesian | `id` | Italian | `it` |
792
+ | Javanese | `jv` | Georgian | `ka` |
793
+ | Kazakh | `kk` | Khmer | `km` |
794
+ | Lithuanian | `lt` | Latvian | `lv` |
795
+ | Malayalam | `ml` | Marathi | `mr` |
796
+ | Malay | `ms` | Burmese | `my` |
797
+ | Nepali | `ne` | Dutch | `nl` |
798
+ | Punjabi | `pa` | Polish | `pl` |
799
+ | Russian | `ru` | Sinhala | `si` |
800
+ | Slovak | `sk` | Slovenian | `sl` |
801
+ | Serbian | `sr` | Swahili | `sw` |
802
+ | Tamil | `ta` | Telugu | `te` |
803
+ | Thai | `th` | Tagalog | `tl` |
804
+ | Urdu | `ur` | Uzbek | `uz` |
805
+ | Vietnamese | `vi` | | |
806
+
807
+ </details>
808
+
809
+ ## License
810
+
811
+ PLaMo 3 Translate 0.8B W4AFP8 is released under the [PLaMo Community License](https://plamo.preferredai.jp/info/plamo-community-license-en).
812
+
813
+ - [English](https://plamo.preferredai.jp/info/plamo-community-license-en)
814
+ - [Japanese](https://plamo.preferredai.jp/info/plamo-community-license-ja)
815
+
816
+ **Personal and non-commercial use**
817
+
818
+ For personal use, such as learning or hobby projects, you can download and use the model free of charge. Non-commercial use, including academic use, is also free, with no restriction based on revenue or sales and no prior registration with PFN.
819
+
820
+ **Commercial use when revenue or sales is 1 billion yen or less**
821
+
822
+ If the revenue or sales of the user or its affiliates in the most recent fiscal year is 1 billion yen or less, register your intended use through the [PLaMo Commercial Use Registration Form](https://forms.gle/mTL8tBLrMYXKNZD56). Commercial use is free of charge from the moment you submit the form.
823
+
824
+ **Commercial use when revenue or sales exceeds 1 billion yen**
825
+
826
+ A separate license agreement is required. Instead of the registration form above, please contact PFN through the [PLaMo Translation Model inquiry page](https://translate.preferredai.jp/llm/contact/).
827
+
828
+ See the full text of the PLaMo Community License for details.
829
+
830
+ ## Preferred Networks Group AI Policy
831
+
832
+ - [日本語](https://www.preferred.jp/ja/company/aipolicy/)
833
+ - [English](https://www.preferred.jp/en/company/aipolicy/)
README_ja.md ADDED
@@ -0,0 +1,834 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: "other"
3
+ license_name: "plamo-community-license"
4
+ license_link: "https://plamo.preferredai.jp/info/plamo-community-license-en"
5
+ base_model: pfnet/plamo-3-translate-0.8b
6
+ base_model_relation: quantized
7
+ model_name: "PLaMo 3 Translate 0.8B W4AFP8"
8
+ library_name: transformers
9
+ language:
10
+ - ar
11
+ - az
12
+ - be
13
+ - bg
14
+ - bn
15
+ - ca
16
+ - ceb
17
+ - de
18
+ - en
19
+ - es
20
+ - et
21
+ - eu
22
+ - fa
23
+ - fr
24
+ - gu
25
+ - he
26
+ - hi
27
+ - hr
28
+ - hu
29
+ - hy
30
+ - id
31
+ - it
32
+ - ja
33
+ - jv
34
+ - ka
35
+ - kk
36
+ - km
37
+ - ko
38
+ - lt
39
+ - lv
40
+ - ml
41
+ - mr
42
+ - ms
43
+ - my
44
+ - ne
45
+ - nl
46
+ - pa
47
+ - pl
48
+ - ru
49
+ - si
50
+ - sk
51
+ - sl
52
+ - sr
53
+ - sw
54
+ - ta
55
+ - te
56
+ - th
57
+ - tl
58
+ - ur
59
+ - uz
60
+ - vi
61
+ - zh
62
+ pipeline_tag: translation
63
+ tags:
64
+ - translation
65
+ - multilingual
66
+ - custom_code
67
+ - plamo
68
+ - w4afp8
69
+ - int4
70
+ - fp8
71
+ - compressed-tensors
72
+ - vllm
73
+
74
+ ---
75
+
76
+ # PLaMo 3 Translate 0.8B W4AFP8
77
+
78
+ [English README](README.md)
79
+
80
+ PLaMo 3 Translate 0.8B W4AFP8は、[PLaMo 3 Translate 0.8B](https://huggingface.co/pfnet/plamo-3-translate-0.8b/blob/main/README_ja.md)の重みをINT4、活性化をFP8に量子化したモデルです。他の配布形式との比較は[配布形式の選び方](#配布形式の選び方)を参照してください。vLLMの起動コマンドはBF16版と同じです。
81
+
82
+ PLaMo 3 Translate 0.8Bは、Preferred Networks(PFN)が開発した、世界最高クラスの翻訳特化LLMです。
83
+ PFNと国立研究開発法人情報通信研究機構(NICT)の共同研究で得られた事前学習モデル「PLaMo 3 NICT」を基盤としています。
84
+ この基盤モデルに対し、数十Bトークン規模の翻訳特化の学習を行いました。
85
+ 開発詳細については[テックブログ](https://www.preferred.jp/ja/blog/tech/plamo-3-translate-weight-release)をご参照ください。
86
+
87
+ PLaMo 3 Translate 0.8Bは53言語の多言語翻訳に対応しています ([対応言語](#対応言語)のセクションを参照)。
88
+ 翻訳の周辺文脈、用語集、日本語における常体・敬体のスタイル指定にも対応しています。
89
+ 学習時の最大長は、入力と出力を合わせて32,768トークンです。長い文章もまとめて翻訳できますが、さらに長い文章は、入力と出力の合計がこの範囲に収まるように分割してください。
90
+
91
+ PLaMo 3 Translate 0.8Bのライセンスは[PLaMo Community License](https://plamo.preferredai.jp/info/plamo-community-license-ja)です。個人での学習や趣味などの私的な用途や、学術用途を含む非商用利用では、事前の登録なしに無償で自由にご利用いただけます。商用利用の条件は[ライセンス](#ライセンス)を参照してください。
92
+
93
+ ## ベンチマーク結果
94
+
95
+ PLaMo 3 Translateは、日英翻訳と多言語翻訳の双方で世界最高クラスの性能を示します。2Bモデルの時点で、下図のすべての指標において、比較した翻訳特化LLMを上回っています。
96
+
97
+ ![PLaMo 3 Translate、TranslateGemma、HY-MT2の翻訳性能比較](figures/benchmark_ja.png)
98
+
99
+ 上段は日英翻訳の品質で、PFTB、SaaS、WMT24++ COMET-22の平均です。中段は日本語と他の14言語、下段は英語と他の14言語との間の翻訳品質で、FLORES+ chrF++を双方向で平均したものです。いずれも高いほど良いスコアです。
100
+
101
+ FLORES+による多言語評価では、対応する53言語のうち、次の15言語を対象にしました。日本語または英語を中心に、それぞれ残りの14言語との翻訳を双方向で評価しています。
102
+
103
+ - 日本語、英語、アラビア語、インドネシア語、イタリア語、オランダ語、韓国語、スペイン語、タイ語、中国語(簡体字・繁体字)、ドイツ語、フランス語、ベトナム語、ロシア語
104
+
105
+ 詳細については[テックブログ](https://www.preferred.jp/ja/blog/tech/plamo-3-translate-weight-release)をご参照ください。
106
+
107
+ ## モデルの選び方
108
+
109
+ ### モデル一覧
110
+ PLaMo 3 Translateには、0.8B、2B、8B、31Bの4つのサイズがあります。
111
+ それぞれのサイズについて、量子化やフォーマット変換を行ったモデルを別のリポジトリに用意しています。
112
+
113
+ | サイズ | BF16 | FP8 | W4A16 | W4AFP8 | NVFP4 | GGUF | MLX |
114
+ | --- | --- | --- | --- | --- | --- | --- | --- |
115
+ | 0.8B | [BF16](https://huggingface.co/pfnet/plamo-3-translate-0.8b/blob/main/README_ja.md) | [FP8](https://huggingface.co/pfnet/plamo-3-translate-0.8b-FP8/blob/main/README_ja.md) | [W4A16](https://huggingface.co/pfnet/plamo-3-translate-0.8b-W4A16/blob/main/README_ja.md) | [W4AFP8](https://huggingface.co/pfnet/plamo-3-translate-0.8b-W4AFP8/blob/main/README_ja.md) | [NVFP4](https://huggingface.co/pfnet/plamo-3-translate-0.8b-NVFP4/blob/main/README_ja.md) | [GGUF](https://huggingface.co/pfnet/plamo-3-translate-0.8b-GGUF/blob/main/README_ja.md) | [MLX-4bit](https://huggingface.co/pfnet/plamo-3-translate-0.8b-MLX-4bit/blob/main/README_ja.md) |
116
+ | 2B | [BF16](https://huggingface.co/pfnet/plamo-3-translate-2b/blob/main/README_ja.md) | [FP8](https://huggingface.co/pfnet/plamo-3-translate-2b-FP8/blob/main/README_ja.md) | [W4A16](https://huggingface.co/pfnet/plamo-3-translate-2b-W4A16/blob/main/README_ja.md) | [W4AFP8](https://huggingface.co/pfnet/plamo-3-translate-2b-W4AFP8/blob/main/README_ja.md) | [NVFP4](https://huggingface.co/pfnet/plamo-3-translate-2b-NVFP4/blob/main/README_ja.md) | [GGUF](https://huggingface.co/pfnet/plamo-3-translate-2b-GGUF/blob/main/README_ja.md) | [MLX-4bit](https://huggingface.co/pfnet/plamo-3-translate-2b-MLX-4bit/blob/main/README_ja.md) |
117
+ | 8B | [BF16](https://huggingface.co/pfnet/plamo-3-translate-8b/blob/main/README_ja.md) | [FP8](https://huggingface.co/pfnet/plamo-3-translate-8b-FP8/blob/main/README_ja.md) | [W4A16](https://huggingface.co/pfnet/plamo-3-translate-8b-W4A16/blob/main/README_ja.md) | [W4AFP8](https://huggingface.co/pfnet/plamo-3-translate-8b-W4AFP8/blob/main/README_ja.md) | [NVFP4](https://huggingface.co/pfnet/plamo-3-translate-8b-NVFP4/blob/main/README_ja.md) | [GGUF](https://huggingface.co/pfnet/plamo-3-translate-8b-GGUF/blob/main/README_ja.md) | [MLX-4bit](https://huggingface.co/pfnet/plamo-3-translate-8b-MLX-4bit/blob/main/README_ja.md) |
118
+ | 31B | [BF16](https://huggingface.co/pfnet/plamo-3-translate-31b/blob/main/README_ja.md) | [FP8](https://huggingface.co/pfnet/plamo-3-translate-31b-FP8/blob/main/README_ja.md) | [W4A16](https://huggingface.co/pfnet/plamo-3-translate-31b-W4A16/blob/main/README_ja.md) | [W4AFP8](https://huggingface.co/pfnet/plamo-3-translate-31b-W4AFP8/blob/main/README_ja.md) | [NVFP4](https://huggingface.co/pfnet/plamo-3-translate-31b-NVFP4/blob/main/README_ja.md) | [GGUF](https://huggingface.co/pfnet/plamo-3-translate-31b-GGUF/blob/main/README_ja.md) | [MLX-4bit](https://huggingface.co/pfnet/plamo-3-translate-31b-MLX-4bit/blob/main/README_ja.md) |
119
+
120
+ <details>
121
+ <summary>量子化による精度変化</summary>
122
+
123
+ モデルサイズごとに、BF16と各配布形式の翻訳精度を比較します。各スコアの下の括弧内は、同じサイズのBF16との差です(マイナスは精度の低下を示します)。いずれも高いほど良いスコアです。
124
+
125
+ 評価指標の詳細については[テックブログ](https://www.preferred.jp/ja/blog/tech/plamo-3-translate-weight-release)をご参照ください。
126
+
127
+ 全体として、`GGUF Q2_K`では一部の指標で翻訳精度の低下が見られますが、他の形式ではBF16に近い精度を維持しています。
128
+
129
+ 容量は重みファイルの合計です。
130
+
131
+ #### 31B
132
+
133
+ | 形式 | 容量(GB) | PFTB(英↔日) | SaaS(英→日) | WMT24++ COMET-22(英→日) | FLORES+ chrF++(日本語↔多言語) | FLORES+ chrF++(英語↔多言語) |
134
+ | --- | ---: | ---: | ---: | ---: | ---: | ---: |
135
+ | **BF16** | 63.51 | 0.6244 | 0.5786 | 0.8799 | 37.81 | 56.61 |
136
+ | FP8 | 32.31 | 0.6240<br>(-0.0004) | 0.5803<br>(+0.0017) | 0.8799<br>(0.0000) | 37.79<br>(-0.02) | 56.60<br>(-0.01) |
137
+ | W4A16 | 17.19 | 0.6258<br>(+0.0014) | 0.5777<br>(-0.0009) | 0.8805<br>(+0.0006) | 37.74<br>(-0.07) | 56.49<br>(-0.12) |
138
+ | W4AFP8 | 17.19 | 0.6223<br>(-0.0021) | 0.5716<br>(-0.0070) | 0.8813<br>(+0.0014) | 37.71<br>(-0.10) | 56.53<br>(-0.08) |
139
+ | NVFP4 | 18.66 | 0.6258<br>(+0.0014) | 0.5748<br>(-0.0038) | 0.8809<br>(+0.0010) | 37.70<br>(-0.11) | 56.49<br>(-0.12) |
140
+ | GGUF BF16 | 63.52 | 0.6241<br>(-0.0003) | 0.5793<br>(+0.0007) | 0.8799<br>(0.0000) | 37.82<br>(+0.01) | 56.59<br>(-0.02) |
141
+ | GGUF Q4_K_M | 19.53 | 0.6237<br>(-0.0007) | 0.5770<br>(-0.0016) | 0.8810<br>(+0.0011) | 37.84<br>(+0.03) | 56.55<br>(-0.06) |
142
+ | GGUF Q3_K_M | 15.86 | 0.6223<br>(-0.0021) | 0.5780<br>(-0.0006) | 0.8813<br>(+0.0014) | 37.78<br>(-0.03) | 56.54<br>(-0.07) |
143
+ | GGUF Q2_K | 12.61 | 0.6126<br>(-0.0118) | 0.5745<br>(-0.0041) | 0.8801<br>(+0.0002) | 37.36<br>(-0.45) | 56.16<br>(-0.45) |
144
+ | MLX 4bit | 18.66 | 0.6222<br>(-0.0022) | 0.5779<br>(-0.0007) | 0.8800<br>(+0.0001) | 37.82<br>(+0.01) | 56.58<br>(-0.03) |
145
+
146
+ #### 8B
147
+
148
+ | 形式 | 容量(GB) | PFTB(英↔日) | SaaS(英→日) | WMT24++ COMET-22(英→日) | FLORES+ chrF++(日本語↔多言語) | FLORES+ chrF++(英語↔多言語) |
149
+ | --- | ---: | ---: | ---: | ---: | ---: | ---: |
150
+ | **BF16** | 17.06 | 0.6119 | 0.5750 | 0.8805 | 37.45 | 56.22 |
151
+ | FP8 | 9.41 | 0.6123<br>(+0.0004) | 0.5764<br>(+0.0014) | 0.8805<br>(0.0000) | 37.40<br>(-0.05) | 56.17<br>(-0.05) |
152
+ | W4A16 | 5.71 | 0.6114<br>(-0.0005) | 0.5749<br>(-0.0001) | 0.8789<br>(-0.0016) | 37.36<br>(-0.09) | 56.19<br>(-0.03) |
153
+ | W4AFP8 | 5.71 | 0.6174<br>(+0.0055) | 0.5759<br>(+0.0009) | 0.8794<br>(-0.0011) | 37.34<br>(-0.11) | 56.12<br>(-0.10) |
154
+ | NVFP4 | 6.07 | 0.6040<br>(-0.0079) | 0.5783<br>(+0.0033) | 0.8792<br>(-0.0013) | 37.26<br>(-0.19) | 56.10<br>(-0.12) |
155
+ | GGUF BF16 | 17.07 | 0.6110<br>(-0.0009) | 0.5755<br>(+0.0005) | 0.8802<br>(-0.0003) | 37.46<br>(+0.01) | 56.22<br>(0.00) |
156
+ | GGUF Q4_K_M | 5.28 | 0.6100<br>(-0.0019) | 0.5765<br>(+0.0015) | 0.8802<br>(-0.0003) | 37.39<br>(-0.06) | 56.18<br>(-0.04) |
157
+ | GGUF Q3_K_M | 4.31 | 0.6019<br>(-0.0100) | 0.5707<br>(-0.0043) | 0.8826<br>(+0.0021) | 37.20<br>(-0.25) | 55.93<br>(-0.29) |
158
+ | GGUF Q2_K | 3.45 | 0.5989<br>(-0.0130) | 0.5676<br>(-0.0074) | 0.8791<br>(-0.0014) | 36.54<br>(-0.91) | 55.31<br>(-0.91) |
159
+ | MLX 4bit | 6.07 | 0.6102<br>(-0.0017) | 0.5751<br>(+0.0001) | 0.8796<br>(-0.0009) | 37.41<br>(-0.04) | 56.19<br>(-0.03) |
160
+
161
+ #### 2B
162
+
163
+ | 形式 | 容量(GB) | PFTB(英↔日) | SaaS(英→日) | WMT24++ COMET-22(英→日) | FLORES+ chrF++(日本語↔多言語) | FLORES+ chrF++(英語↔多言語) |
164
+ | --- | ---: | ---: | ---: | ---: | ---: | ---: |
165
+ | **BF16** | 5.76 | 0.6061 | 0.5612 | 0.8780 | 37.02 | 55.74 |
166
+ | FP8 | 3.43 | 0.6067<br>(+0.0006) | 0.5613<br>(+0.0001) | 0.8776<br>(-0.0004) | 36.98<br>(-0.04) | 55.76<br>(+0.02) |
167
+ | W4A16 | 2.30 | 0.6032<br>(-0.0029) | 0.5594<br>(-0.0018) | 0.8783<br>(+0.0003) | 36.96<br>(-0.06) | 55.69<br>(-0.05) |
168
+ | W4AFP8 | 2.30 | 0.6022<br>(-0.0039) | 0.5612<br>(0.0000) | 0.8772<br>(-0.0008) | 36.95<br>(-0.07) | 55.71<br>(-0.03) |
169
+ | NVFP4 | 2.41 | 0.6032<br>(-0.0029) | 0.5626<br>(+0.0014) | 0.8783<br>(+0.0003) | 36.82<br>(-0.20) | 55.64<br>(-0.10) |
170
+ | GGUF BF16 | 5.76 | 0.6062<br>(+0.0001) | 0.5619<br>(+0.0007) | 0.8782<br>(+0.0002) | 37.02<br>(0.00) | 55.75<br>(+0.01) |
171
+ | GGUF Q4_K_M | 1.81 | 0.6062<br>(+0.0001) | 0.5602<br>(-0.0010) | 0.8774<br>(-0.0006) | 37.00<br>(-0.02) | 55.76<br>(+0.02) |
172
+ | GGUF Q4_0 | 1.70 | 0.6069<br>(+0.0008) | 0.5604<br>(-0.0008) | 0.8791<br>(+0.0011) | 36.12<br>(-0.90) | 55.62<br>(-0.12) |
173
+ | GGUF Q3_K_M | 1.50 | 0.6053<br>(-0.0008) | 0.5644<br>(+0.0032) | 0.8789<br>(+0.0009) | 36.81<br>(-0.21) | 55.59<br>(-0.15) |
174
+ | GGUF Q2_K | 1.23 | 0.5977<br>(-0.0084) | 0.5610<br>(-0.0002) | 0.8777<br>(-0.0003) | 36.45<br>(-0.57) | 55.02<br>(-0.72) |
175
+ | MLX 4bit | 2.41 | 0.6040<br>(-0.0021) | 0.5624<br>(+0.0012) | 0.8777<br>(-0.0003) | 36.99<br>(-0.03) | 55.64<br>(-0.10) |
176
+
177
+ #### 0.8B
178
+
179
+ | 形式 | 容量(GB) | PFTB(英↔日) | SaaS(英→日) | WMT24++ COMET-22(英→日) | FLORES+ chrF++(日本語↔多言語) | FLORES+ chrF++(英語↔多言語) |
180
+ | --- | ---: | ---: | ---: | ---: | ---: | ---: |
181
+ | **BF16** | 1.78 | 0.5862 | 0.5530 | 0.8724 | 36.08 | 54.44 |
182
+ | FP8 | 1.22 | 0.5846<br>(-0.0016) | 0.5491<br>(-0.0039) | 0.8726<br>(+0.0002) | 36.00<br>(-0.08) | 54.60<br>(+0.16) |
183
+ | W4A16 | 0.95 | 0.5847<br>(-0.0015) | 0.5439<br>(-0.0091) | 0.8711<br>(-0.0013) | 35.78<br>(-0.30) | 53.95<br>(-0.49) |
184
+ | W4AFP8 | 0.95 | 0.5783<br>(-0.0079) | 0.5456<br>(-0.0074) | 0.8718<br>(-0.0006) | 35.75<br>(-0.33) | 54.38<br>(-0.06) |
185
+ | NVFP4 | 0.98 | 0.5787<br>(-0.0075) | 0.5436<br>(-0.0094) | 0.8702<br>(-0.0022) | 35.54<br>(-0.54) | 54.20<br>(-0.24) |
186
+ | GGUF BF16 | 1.78 | 0.5873<br>(+0.0011) | 0.5533<br>(+0.0003) | 0.8727<br>(+0.0003) | 36.10<br>(+0.02) | 54.45<br>(+0.01) |
187
+ | GGUF Q4_K_M | 0.57 | 0.5832<br>(-0.0030) | 0.5451<br>(-0.0079) | 0.8716<br>(-0.0008) | 35.90<br>(-0.18) | 54.47<br>(+0.03) |
188
+ | GGUF Q4_0 | 0.55 | 0.5853<br>(-0.0009) | 0.5500<br>(-0.0030) | 0.8723<br>(-0.0001) | 34.97<br>(-1.11) | 54.11<br>(-0.33) |
189
+ | GGUF Q3_K_M | 0.49 | 0.5798<br>(-0.0064) | 0.5520<br>(-0.0010) | 0.8710<br>(-0.0014) | 35.32<br>(-0.76) | 54.15<br>(-0.29) |
190
+ | GGUF Q2_K | 0.41 | 0.5620<br>(-0.0242) | 0.5397<br>(-0.0133) | 0.8659<br>(-0.0065) | 33.56<br>(-2.52) | 51.15<br>(-3.29) |
191
+ | MLX 4bit | 0.98 | 0.5773<br>(-0.0089) | 0.5476<br>(-0.0054) | 0.8724<br>(0.0000) | 35.82<br>(-0.26) | 54.41<br>(-0.03) |
192
+
193
+ </details>
194
+
195
+ ### 配布形式の選び方
196
+
197
+ PLaMo 3 Translateの各サイズには、用途とハードウェアに応じて次の配布形式があります。
198
+
199
+ | 形式 | 主な対象環境 | 推論エンジン | 用途の目安 |
200
+ | --- | --- | --- | --- |
201
+ | BF16 | BF16対応GPU | Transformers/vLLM | 量子化なしの精度を優先。メモリに余裕がある場合 |
202
+ | FP8 | NVIDIA Ada Lovelace/Hopper/Blackwell | vLLM | 精度と省メモリ・速度のバランスを重視 |
203
+ | W4A16 | NVIDIA Ampere以降 | vLLM | 4bit重みでGPUメモリを抑えて実行 |
204
+ | **W4AFP8** | NVIDIA Hopper | vLLM | 4bit重みとFP8演算で、省メモリと処理量の両立を狙う |
205
+ | NVFP4 | NVIDIA Blackwell | vLLM | FP4演算を活用し、省メモリ・高速化を狙う |
206
+ | GGUF | CPU/各種GPU | llama.cpp | 手元のPCで実行。CPUとGPUの併用も可能 |
207
+ | MLX-4bit | Apple silicon | mlx-lm | Macで省メモリに実行 |
208
+
209
+ ## 使い方
210
+
211
+ 省メモリで実行する場合は、[vLLMの手順](#vllm)を参照してください。
212
+
213
+ ### Transformers
214
+
215
+ Transformersでは量子化された重みがBF16に展開されて実行されるため、量子化による省メモリ効果はありません。
216
+
217
+ モデルファイルをダウンロードし、そのディレクトリに移動します。以降の例はこのディレクトリで実行します。
218
+
219
+ ```bash
220
+ pip install -U huggingface_hub
221
+ hf download pfnet/plamo-3-translate-0.8b-W4AFP8 --local-dir plamo-3-translate-0.8b-W4AFP8
222
+ cd plamo-3-translate-0.8b-W4AFP8
223
+ ```
224
+
225
+ 必要なパッケージをインストールします。
226
+
227
+ ```bash
228
+ pip install -U torch transformers accelerate numba compressed-tensors
229
+ ```
230
+
231
+ #### 1つの文章を翻訳する
232
+
233
+ 手軽に翻訳を試せるよう、チャットテンプレートを用意しています。原文と翻訳先を指定すると、PFML3形式のプロンプトを作成できます。
234
+
235
+ アプリケーションへの組み込みなど、本格的に活用する場合は、[PFML3形式](#pfml3プロンプト形式)でプロンプトを直接組み立て、[vLLMのCompletions API](#completions-apiで翻訳する)に渡す方法をおすすめします。
236
+
237
+ 以下は英語から日本語に翻訳する例です。
238
+
239
+ ```python
240
+ from transformers import AutoModelForCausalLM, AutoTokenizer
241
+
242
+ tokenizer = AutoTokenizer.from_pretrained(".", trust_remote_code=True)
243
+ model = AutoModelForCausalLM.from_pretrained(
244
+ ".", trust_remote_code=True, dtype="bfloat16", device_map="auto",
245
+ )
246
+
247
+ inputs = tokenizer.apply_chat_template(
248
+ [{"role": "user", "content": "The meeting has been rescheduled to next Monday."}],
249
+ target_lang="ja",
250
+ add_generation_prompt=True,
251
+ return_dict=True, return_tensors="pt",
252
+ ).to(model.device)
253
+
254
+ output = model.generate(**inputs, do_sample=False, max_new_tokens=512)
255
+ text = tokenizer.decode(output[0, inputs["input_ids"].shape[1]:], skip_special_tokens=True)
256
+ print(text)
257
+ ```
258
+
259
+ `max_new_tokens`は訳文の生成上限です。この例では512トークンに設定しています。長文を翻訳する場合は、入力全体(原文・履歴・参考文脈・用語集など)と出力の合計が実行環境の上限に収まるように、生成上限を調整してください。
260
+
261
+ 翻訳例:
262
+
263
+ > 会議は来週の月曜日に変更されました。
264
+
265
+ 上の例では原文の言語を指定していません。`source_lang`を省略した場合は、モデルが原文から言語を判断して翻訳します。明示したい場合は、`source_lang="en"`のように指定してください。
266
+
267
+ #### 複数の文章をまとめて翻訳する
268
+
269
+ 複数の文章は、チャットテンプレートにまとめて渡すことでバッチ翻訳できます。以下は、上で読み込んだ`model`と`tokenizer`を使い、2つの文章を日本語に翻訳する例です。
270
+
271
+ ```python
272
+ tokenizer.padding_side = "left"
273
+ texts = [
274
+ "The meeting has been rescheduled to next Monday.",
275
+ "Please open the project dashboard.",
276
+ ]
277
+ messages = [[{"role": "user", "content": text}] for text in texts]
278
+
279
+ inputs = tokenizer.apply_chat_template(
280
+ messages,
281
+ target_lang="ja",
282
+ add_generation_prompt=True,
283
+ padding=True,
284
+ return_dict=True, return_tensors="pt",
285
+ ).to(model.device)
286
+
287
+ outputs = model.generate(**inputs, do_sample=False, max_new_tokens=512)
288
+ translations = tokenizer.batch_decode(
289
+ outputs[:, inputs["input_ids"].shape[1]:], skip_special_tokens=True,
290
+ )
291
+ for source, translation in zip(texts, translations):
292
+ print(f"{source} → {translation}")
293
+ ```
294
+
295
+ 文章の長さを揃えるために左側をパディングし、生成された訳文だけを取り出します。`target_lang`などの翻訳オプションは、この例ではバッチ内のすべての文章に適用されます。
296
+
297
+ ### これまでの訳文を参考に、続きを翻訳する
298
+
299
+ 文書を段落ごとに翻訳するときは、これまでの原文・訳文のペアを履歴として渡せます。前の訳語や文体を参考にしながら、続きの文章を翻訳するための方法です。
300
+
301
+ チャットテンプレートを使う場合は、原文を`user`、その訳文を`assistant`として交互に並べ、最後の`user`に今回の原文を渡します。履歴は自動では保存されないため、次のリクエストにも必要なペアを含めてください。
302
+
303
+ 翻訳方向はリクエスト全体で共通です。`source_lang`はすべての原文、`target_lang`はすべての訳文に適用されます。
304
+
305
+ 履歴も入力トークン数に含まれます。入力全体と生成する訳文が、32,768トークンおよび実行環境の上限に収まるようにしてください。履歴が長くなった場合は、古い原文・訳文のペアから順に外し、直近の履歴を残すことをおすすめします。
306
+
307
+ 上の例で読み込んだ`model`と`tokenizer`を使います。
308
+
309
+ ```python
310
+ messages = [
311
+ {"role": "user", "content": "Open the project dashboard."},
312
+ {"role": "assistant", "content": "プロジェクトの管理画面を開きます。"},
313
+ {"role": "user", "content": "It lists all active tasks."},
314
+ {"role": "assistant", "content": "進行中のタスクがすべて表示されます。"},
315
+ {"role": "user", "content": "You can also filter them by owner."},
316
+ ]
317
+
318
+ inputs = tokenizer.apply_chat_template(
319
+ messages, source_lang="en", target_lang="ja",
320
+ add_generation_prompt=True,
321
+ return_dict=True, return_tensors="pt",
322
+ ).to(model.device)
323
+ output = model.generate(**inputs, do_sample=False, max_new_tokens=512)
324
+ text = tokenizer.decode(output[0, inputs["input_ids"].shape[1]:], skip_special_tokens=True)
325
+ print(text)
326
+ ```
327
+
328
+ ### PFML3プロンプト形式
329
+
330
+ PFML3は、翻訳する文章や翻訳先などを特殊トークンで区切って表すPLaMoのプロンプト形式です。上のTransformersの例では、チャットテンプレートが原文と翻訳先をPFML3に変換しています。ここでは変換結果の見方と、プロンプトを手書きするときの使い方を説明します。
331
+
332
+ 本格的な活用には、PFML3でプロンプトを直接組み立て、[vLLMのCompletions API](#completions-apiで翻訳する)に渡す方法をおすすめします。
333
+
334
+ 上のTransformersの例をPFML3に変換すると、次のようになります。ここでは文頭トークンを省略し、Pythonの文字列を分割して示しています。実際のプロンプトには改行は入りません。
335
+
336
+ ```python
337
+ prompt = (
338
+ "<|plamo:tag|>dataset<|plamo:msg|>translation"
339
+ "<|plamo:tag|>input"
340
+ "<|plamo:msg|>The meeting has been rescheduled to next Monday."
341
+ "<|plamo:tag|>output<|plamo:key|>lang<|plamo:val|>ja<|plamo:msg|>"
342
+ )
343
+ ```
344
+
345
+ - `dataset`の`translation`は翻訳タスクを表します。このモデルは翻訳専用のため、`dataset`には必ず`translation`を指定します。
346
+ - `input`の`<|plamo:msg|>`に続く部分が翻訳する原文です。
347
+ - `output`の`<|plamo:key|>lang<|plamo:val|>ja`は、翻訳先が日本語であることを表します。最後の`<|plamo:msg|>`の直後から訳文が生成されます。
348
+
349
+ `<|plamo:tag|>`は各要素の始まりを、`<|plamo:msg|>`はその本文の始まりを表します。言語や文体などを指定するときは、要素名に続けて`<|plamo:key|>`の後に属性名、`<|plamo:val|>`の後に値を書きます。例えば、`output`に`<|plamo:key|>form<|plamo:val|>plain`を追加すると、常体を指定できます。
350
+
351
+ 参考文脈や用語集はオプショナルです。使う場合は、`dataset`と`input`の間に`context`、`glossary`の順で追加します。対訳履歴も使う場合は、`context`を`dataset`の直後に置き、過去の`input`・`output`の組を並べた後、今回の`input`の直前に`glossary`を置きます。用語集には、`<|plamo:index|>`の後に原語、`<|plamo:item|>`の後に訳語を書き、この組を用語の数だけ並べます。具体例は[翻訳オプション](#翻訳オプション)を参照してください。
352
+
353
+ #### 手書きのプロンプトを使う
354
+
355
+ PFML3を手書きするときは、`dataset`を`translation`に指定して始め、`output`要素の末尾を`<|plamo:msg|>`で終えます。モデルは訳文の生成後、`<|plamo:tag|>`または`<|plamo:bos|>`を出力して停止します。
356
+
357
+ 上の手書き例では、文頭を示す`<|plamo:bos|>`を省略しています。Transformersのトークナイザー、llama.cpp、mlx-lmは文頭トークンを自動で付けます。vLLMのCompletions APIでは`add_special_tokens=true`を指定してください。
358
+
359
+ チャットテンプレートで作った文字列には、文頭トークンがすでに含まれます。`tokenize=False`で受け取った文字列をTransformersのトークナイザーに渡す場合は、重複を避けるため`add_special_tokens=False`を指定してください。
360
+
361
+ 例えば、手書きのプロンプトをTransformersに渡すには、上のTransformersの例の`model`と`tokenizer`を使います。
362
+
363
+ ```python
364
+ inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
365
+ output = model.generate(**inputs, do_sample=False, max_new_tokens=512)
366
+ text = tokenizer.decode(output[0, inputs["input_ids"].shape[1]:], skip_special_tokens=True)
367
+ print(text)
368
+ ```
369
+
370
+ #### 対訳履歴をPFML3で指定する
371
+
372
+ 対訳履歴は手書きのPFML3でも指定できます。翻訳済みの`input`と`output`を文書の順に並べ、最後に今回の原文と、本文が空の`output`を置きます。次の例では、2組の対訳を参考にして、最後の「You can also filter them by owner.」だけを翻訳します。
373
+
374
+ ```python
375
+ prompt = (
376
+ "<|plamo:tag|>dataset<|plamo:msg|>translation"
377
+ "<|plamo:tag|>input<|plamo:key|>lang<|plamo:val|>en<|plamo:msg|>Open the project dashboard."
378
+ "<|plamo:tag|>output<|plamo:key|>lang<|plamo:val|>ja<|plamo:msg|>プロジェクトの管理画面を開きます。"
379
+ "<|plamo:tag|>input<|plamo:key|>lang<|plamo:val|>en<|plamo:msg|>It lists all active tasks."
380
+ "<|plamo:tag|>output<|plamo:key|>lang<|plamo:val|>ja<|plamo:msg|>進行中のタスクがすべて表示されます。"
381
+ "<|plamo:tag|>input<|plamo:key|>lang<|plamo:val|>en<|plamo:msg|>You can also filter them by owner."
382
+ "<|plamo:tag|>output<|plamo:key|>lang<|plamo:val|>ja<|plamo:msg|>"
383
+ )
384
+ ```
385
+
386
+ 上の「手書きのプロンプトを使う」の例で、`prompt`をこの文字列に置き換えて実行してください。
387
+
388
+ 続きを訳すときは、今回の原文と生成された訳文の組を履歴に追加します。その後に、次の原文を入れた`input`と、本文が空の`output`を続けます。
389
+
390
+ 履歴には訳文の本文���けを残します。上の例で受け取った訳文は、そのまま使えます。
391
+
392
+ 訳文の末尾に`<|plamo:tag|>`や`<|plamo:bos|>`が残っている場合は取り除き、次の`input`との間の`<|plamo:tag|>`が1つになるようにしてください。
393
+
394
+ ### 翻訳オプション
395
+
396
+ 翻訳先や文体、参考文脈、用語集などは、`system`メッセージや原文には書かず、`apply_chat_template()`の引数で指定します。
397
+
398
+ 上のTransformersの例で、`inputs`を作る部分を以下のコードに置き換えて実行してください。
399
+
400
+ | 引数 | 内容 |
401
+ | --- | --- |
402
+ | `target_lang` | 翻訳先の言語コード。必須。 |
403
+ | `source_lang` | 原文の言語コード。省略可能。 |
404
+ | `context` | 原文を解釈するための参考文脈(前後の文章や場面など)。 |
405
+ | `glossary` | `{"source": "原語", "target": "訳語"}`のリスト。 |
406
+ | `form` | 常体`plain`/敬体`polite`を指定(`target_lang="ja"`のみ)。 |
407
+
408
+ 対訳履歴と併用する場合、`context`は全体の参考文脈として渡し、`glossary`と`form`は今回の翻訳に適用されます。過去の訳文自体は変更しません。
409
+
410
+ #### 用語集で訳語を指定する
411
+
412
+ `glossary`に原語と訳語の組を渡して、用語の訳し方を指定します。
413
+
414
+ ```python
415
+ inputs = tokenizer.apply_chat_template(
416
+ [{"role": "user", "content": "Please open the project dashboard."}],
417
+ target_lang="ja",
418
+ glossary=[
419
+ {"source": "dashboard", "target": "管理画面"},
420
+ {"source": "project", "target": "プロジェクト"},
421
+ ],
422
+ add_generation_prompt=True,
423
+ return_dict=True, return_tensors="pt",
424
+ ).to(model.device)
425
+ ```
426
+
427
+ 翻訳例:
428
+
429
+ > プロジェクトの管理画面を開いてください。
430
+
431
+ <details>
432
+ <summary>この例のPFML3プロンプト</summary>
433
+
434
+ ```python
435
+ prompt = (
436
+ "<|plamo:tag|>dataset<|plamo:msg|>translation"
437
+ "<|plamo:tag|>glossary"
438
+ "<|plamo:index|>dashboard<|plamo:item|>管理画面"
439
+ "<|plamo:index|>project<|plamo:item|>プロジェクト"
440
+ "<|plamo:tag|>input<|plamo:msg|>Please open the project dashboard."
441
+ "<|plamo:tag|>output<|plamo:key|>lang<|plamo:val|>ja<|plamo:msg|>"
442
+ )
443
+ ```
444
+
445
+ </details>
446
+
447
+ #### 参考文脈を渡す
448
+
449
+ `context`に前後の文章や場面を伝えます。この例では、川辺を歩いているという文脈を添えています。
450
+
451
+ ```python
452
+ inputs = tokenizer.apply_chat_template(
453
+ [{"role": "user", "content": "The bank was muddy."}],
454
+ target_lang="ja",
455
+ context="They were walking beside a river after heavy rain.",
456
+ add_generation_prompt=True,
457
+ return_dict=True, return_tensors="pt",
458
+ ).to(model.device)
459
+ ```
460
+
461
+ 翻訳例:
462
+
463
+ > 川岸はぬかるんでいた。
464
+
465
+ <details>
466
+ <summary>この例のPFML3プロンプト</summary>
467
+
468
+ ```python
469
+ prompt = (
470
+ "<|plamo:tag|>dataset<|plamo:msg|>translation"
471
+ "<|plamo:tag|>context"
472
+ "<|plamo:msg|>They were walking beside a river after heavy rain."
473
+ "<|plamo:tag|>input<|plamo:msg|>The bank was muddy."
474
+ "<|plamo:tag|>output<|plamo:key|>lang<|plamo:val|>ja<|plamo:msg|>"
475
+ )
476
+ ```
477
+
478
+ </details>
479
+
480
+ #### 常体・敬体を指定する
481
+
482
+ 日本語への翻訳では、`form="plain"`で常体(だ・である調)、`form="polite"`で敬体(です・ます調)を指定できます。
483
+
484
+ ```python
485
+ inputs = tokenizer.apply_chat_template(
486
+ [{"role": "user", "content": "This system is convenient."}],
487
+ target_lang="ja",
488
+ form="plain",
489
+ add_generation_prompt=True,
490
+ return_dict=True, return_tensors="pt",
491
+ ).to(model.device)
492
+ ```
493
+
494
+ 同じ原文に対する翻訳例:
495
+
496
+ | 文体 | 指定 | 訳文 |
497
+ | --- | --- | --- |
498
+ | 常体 | `form="plain"` | このシステムは便利だ。 |
499
+ | 敬体 | `form="polite"` | このシステムは便利です。 |
500
+
501
+ <details>
502
+ <summary>この例のPFML3プロンプト</summary>
503
+
504
+ 常体:
505
+
506
+ ```python
507
+ prompt = (
508
+ "<|plamo:tag|>dataset<|plamo:msg|>translation"
509
+ "<|plamo:tag|>input<|plamo:msg|>This system is convenient."
510
+ "<|plamo:tag|>output<|plamo:key|>lang<|plamo:val|>ja"
511
+ "<|plamo:key|>form<|plamo:val|>plain<|plamo:msg|>"
512
+ )
513
+ ```
514
+
515
+ 敬体:
516
+
517
+ ```python
518
+ prompt = (
519
+ "<|plamo:tag|>dataset<|plamo:msg|>translation"
520
+ "<|plamo:tag|>input<|plamo:msg|>This system is convenient."
521
+ "<|plamo:tag|>output<|plamo:key|>lang<|plamo:val|>ja"
522
+ "<|plamo:key|>form<|plamo:val|>polite<|plamo:msg|>"
523
+ )
524
+ ```
525
+ </details>
526
+
527
+ #### すべてのオプションを同時に指定する
528
+
529
+ 対訳履歴、参考文脈、用語集、文体は同時に指定できます。次の例では、2組の対訳履歴に続けて3文目を翻訳し、参考文脈にページの種類、用語集に`owner`の訳語、文体に敬体を指定しています。`context`は全体の参考文脈として渡され、`glossary`と`form`は今回の翻訳に適用されます。
530
+
531
+ ```python
532
+ inputs = tokenizer.apply_chat_template(
533
+ [
534
+ {"role": "user", "content": "Open the project dashboard."},
535
+ {"role": "assistant", "content": "プロジェクトの管理画面を開きます。"},
536
+ {"role": "user", "content": "It lists all active tasks."},
537
+ {"role": "assistant", "content": "進行中のタスクがすべて表示されます。"},
538
+ {"role": "user", "content": "You can also filter them by owner."},
539
+ ],
540
+ source_lang="en", target_lang="ja",
541
+ context="Help page of a project management tool.",
542
+ glossary=[{"source": "owner", "target": "オーナー"}],
543
+ form="polite",
544
+ add_generation_prompt=True,
545
+ return_dict=True, return_tensors="pt",
546
+ ).to(model.device)
547
+ ```
548
+
549
+ 翻訳例:
550
+
551
+ > また、オーナー別に絞り込むこともできます。
552
+
553
+ <details>
554
+ <summary>この例のPFML3プロンプト</summary>
555
+
556
+ ```python
557
+ prompt = (
558
+ "<|plamo:tag|>dataset<|plamo:msg|>translation"
559
+ "<|plamo:tag|>context<|plamo:msg|>Help page of a project management tool."
560
+ "<|plamo:tag|>input<|plamo:key|>lang<|plamo:val|>en<|plamo:msg|>Open the project dashboard."
561
+ "<|plamo:tag|>output<|plamo:key|>lang<|plamo:val|>ja<|plamo:msg|>プロジェクトの管理画面を開きます。"
562
+ "<|plamo:tag|>input<|plamo:key|>lang<|plamo:val|>en<|plamo:msg|>It lists all active tasks."
563
+ "<|plamo:tag|>output<|plamo:key|>lang<|plamo:val|>ja<|plamo:msg|>進行中のタスクがすべて表示されます。"
564
+ "<|plamo:tag|>glossary<|plamo:index|>owner<|plamo:item|>オーナー"
565
+ "<|plamo:tag|>input<|plamo:key|>lang<|plamo:val|>en<|plamo:msg|>You can also filter them by owner."
566
+ "<|plamo:tag|>output<|plamo:key|>lang<|plamo:val|>ja<|plamo:key|>form<|plamo:val|>polite<|plamo:msg|>"
567
+ )
568
+ ```
569
+
570
+ </details>
571
+
572
+ ### vLLM
573
+
574
+ #### サーバーを起動する
575
+
576
+ モデルファイルをダウンロードし、そのディレクトリに移動します。[Transformers](#transformers)の手順でダウンロード済みの場合は不要です。
577
+
578
+ ```bash
579
+ pip install -U huggingface_hub
580
+ hf download pfnet/plamo-3-translate-0.8b-W4AFP8 --local-dir plamo-3-translate-0.8b-W4AFP8
581
+ cd plamo-3-translate-0.8b-W4AFP8
582
+ ```
583
+
584
+ 必要なパッケージをインストールして、vLLMサーバーを起動します。
585
+
586
+ ```bash
587
+ pip install -U vllm openai numba
588
+
589
+ vllm serve . --trust-remote-code \
590
+ --served-model-name plamo-3-translate \
591
+ --max-model-len 16384 --max-num-seqs 4
592
+ ```
593
+
594
+ この例では、入力と出力を合わせた最大長を16,384トークンに設定しています。必要に応じて、GPUメモリに合わせて調整してください。
595
+
596
+ #### Chat Completions APIで翻訳する
597
+
598
+ Chat Completions APIでは、最後の`user`メッセージに今回の原文を入れ、翻訳オプションを`chat_template_kwargs`で渡します。
599
+
600
+ ```bash
601
+ curl http://localhost:8000/v1/chat/completions \
602
+ -H 'Content-Type: application/json' \
603
+ -d '{
604
+ "model": "plamo-3-translate",
605
+ "messages": [{"role": "user", "content": "Hello."}],
606
+ "chat_template_kwargs": {"target_lang": "ja", "form": "polite"},
607
+ "temperature": 0,
608
+ "max_tokens": 512,
609
+ "stop": ["<|plamo:tag|>", "<|plamo:bos|>"]
610
+ }'
611
+ ```
612
+
613
+ `max_tokens`は訳文の生成上限です。この例では512トークンに設定しています。長文を翻訳する場合は、入力全体(原文・履歴・参考文脈・用語集など)と出力の合計が実行環境の上限に収まるように、生成上限を調整してください。
614
+
615
+ 訳文は`choices[0].message.content`に入ります。
616
+
617
+ **複数の文章をまとめて翻訳する場合**
618
+
619
+ 複数の文章を翻訳するときは、文章ごとにリクエストを送り、並列に実行できます。vLLMは受け取ったリクエストをまとめて処理します。
620
+
621
+ ```python
622
+ from concurrent.futures import ThreadPoolExecutor
623
+ from openai import OpenAI
624
+
625
+ client = OpenAI(base_url="http://localhost:8000/v1", api_key="EMPTY")
626
+ texts = [
627
+ "The meeting has been rescheduled to next Monday.",
628
+ "Please open the project dashboard.",
629
+ ]
630
+
631
+ def translate(text):
632
+ response = client.chat.completions.create(
633
+ model="plamo-3-translate",
634
+ messages=[{"role": "user", "content": text}],
635
+ temperature=0,
636
+ max_tokens=512,
637
+ stop=["<|plamo:tag|>", "<|plamo:bos|>"],
638
+ extra_body={"chat_template_kwargs": {"target_lang": "ja"}},
639
+ )
640
+ return response.choices[0].message.content
641
+
642
+ with ThreadPoolExecutor(max_workers=4) as executor:
643
+ translations = list(executor.map(translate, texts))
644
+
645
+ for source, translation in zip(texts, translations):
646
+ print(f"{source} → {translation}")
647
+ ```
648
+
649
+ **対訳履歴を使ってChat Completions APIで翻訳する場合**
650
+
651
+ 翻訳済みの原文・訳文を`user`/`assistant`のペアで渡します。最後の`user`だけが今回の翻訳対象です。
652
+
653
+ ```python
654
+ from openai import OpenAI
655
+
656
+ client = OpenAI(base_url="http://localhost:8000/v1", api_key="EMPTY")
657
+ messages = [
658
+ {"role": "user", "content": "Open the project dashboard."},
659
+ {"role": "assistant", "content": "プロジェクトの管理画面を開きます。"},
660
+ {"role": "user", "content": "It lists all active tasks."},
661
+ {"role": "assistant", "content": "進行中のタスクがすべて表示されます。"},
662
+ {"role": "user", "content": "You can also filter them by owner."},
663
+ ]
664
+
665
+ response = client.chat.completions.create(
666
+ model="plamo-3-translate",
667
+ messages=messages,
668
+ temperature=0,
669
+ max_tokens=512,
670
+ stop=["<|plamo:tag|>", "<|plamo:bos|>"],
671
+ extra_body={"chat_template_kwargs": {"source_lang": "en", "target_lang": "ja"}},
672
+ )
673
+ print(response.choices[0].message.content)
674
+ ```
675
+
676
+ #### Completions APIで翻訳する
677
+
678
+ `prompt`には、各翻訳例に掲載したPFML3プロンプトを渡します。
679
+
680
+ ```python
681
+ from openai import OpenAI
682
+
683
+ client = OpenAI(base_url="http://localhost:8000/v1", api_key="EMPTY")
684
+ prompt = (
685
+ "<|plamo:tag|>dataset<|plamo:msg|>translation"
686
+ "<|plamo:tag|>input"
687
+ "<|plamo:msg|>The meeting has been rescheduled to next Monday."
688
+ "<|plamo:tag|>output<|plamo:key|>lang<|plamo:val|>ja<|plamo:msg|>"
689
+ )
690
+
691
+ response = client.completions.create(
692
+ model="plamo-3-translate",
693
+ prompt=prompt,
694
+ temperature=0,
695
+ max_tokens=512,
696
+ stop=["<|plamo:tag|>", "<|plamo:bos|>"],
697
+ extra_body={"add_special_tokens": True},
698
+ )
699
+ print(response.choices[0].text)
700
+ ```
701
+
702
+ 訳文は`choices[0].text`に入ります。
703
+
704
+ **複数の文章をまとめて翻訳する場合**
705
+
706
+ PFML3プロンプトを直接使う場合も、文章ごとにリクエストを並列に送れます。
707
+
708
+ ```python
709
+ from concurrent.futures import ThreadPoolExecutor
710
+ from openai import OpenAI
711
+
712
+ client = OpenAI(base_url="http://localhost:8000/v1", api_key="EMPTY")
713
+ texts = [
714
+ "The meeting has been rescheduled to next Monday.",
715
+ "Please open the project dashboard.",
716
+ ]
717
+
718
+ def translate(text):
719
+ prompt = (
720
+ "<|plamo:tag|>dataset<|plamo:msg|>translation"
721
+ "<|plamo:tag|>input<|plamo:msg|>"
722
+ f"{text}"
723
+ "<|plamo:tag|>output<|plamo:key|>lang<|plamo:val|>ja<|plamo:msg|>"
724
+ )
725
+ response = client.completions.create(
726
+ model="plamo-3-translate",
727
+ prompt=prompt,
728
+ temperature=0,
729
+ max_tokens=512,
730
+ stop=["<|plamo:tag|>", "<|plamo:bos|>"],
731
+ extra_body={"add_special_tokens": True},
732
+ )
733
+ return response.choices[0].text
734
+
735
+ with ThreadPoolExecutor(max_workers=4) as executor:
736
+ translations = list(executor.map(translate, texts))
737
+
738
+ for source, translation in zip(texts, translations):
739
+ print(f"{source} → {translation}")
740
+ ```
741
+
742
+ **対訳履歴を使って続きを翻訳する場合**
743
+
744
+ [対訳履歴](#これまでの訳文を参考に続きを翻訳する)を使う翻訳は、Completions APIでも実行できます。翻訳済みの原文・訳文を含むPFML3プロンプトを渡すと、最後の原文に対する訳文が返ります。
745
+
746
+ ```python
747
+ from openai import OpenAI
748
+
749
+ client = OpenAI(base_url="http://localhost:8000/v1", api_key="EMPTY")
750
+ prompt = (
751
+ "<|plamo:tag|>dataset<|plamo:msg|>translation"
752
+ "<|plamo:tag|>input<|plamo:key|>lang<|plamo:val|>en<|plamo:msg|>Open the project dashboard."
753
+ "<|plamo:tag|>output<|plamo:key|>lang<|plamo:val|>ja<|plamo:msg|>プロジェクトの管理画面を開きます。"
754
+ "<|plamo:tag|>input<|plamo:key|>lang<|plamo:val|>en<|plamo:msg|>It lists all active tasks."
755
+ "<|plamo:tag|>output<|plamo:key|>lang<|plamo:val|>ja<|plamo:msg|>進行中のタスクがすべて表示されます。"
756
+ "<|plamo:tag|>input<|plamo:key|>lang<|plamo:val|>en<|plamo:msg|>You can also filter them by owner."
757
+ "<|plamo:tag|>output<|plamo:key|>lang<|plamo:val|>ja<|plamo:msg|>"
758
+ )
759
+
760
+ response = client.completions.create(
761
+ model="plamo-3-translate",
762
+ prompt=prompt,
763
+ temperature=0,
764
+ max_tokens=512,
765
+ stop=["<|plamo:tag|>", "<|plamo:bos|>"],
766
+ extra_body={"add_special_tokens": True},
767
+ )
768
+ print(response.choices[0].text)
769
+ ```
770
+
771
+ ## 対応言語
772
+
773
+ 日本語・英語を含む53言語に対応しています。中国語は簡体字と繁体字をそれぞれ1言語として数えています。Hugging Faceの言語表示では中国語が1言語にまとめられるため、52言語と表示されます。
774
+
775
+ <details>
776
+ <summary>対応言語と言語コードの一覧</summary>
777
+
778
+ | 言語 | コード | 言語 | コード |
779
+ |---|---|---|---|
780
+ | 日本語 | `ja` | 英語 | `en` |
781
+ | 中国語(簡体字) | `zh-hans` | 中国語(繁体字) | `zh-hant` |
782
+ | 韓国語 | `ko` | アラビア語 | `ar` |
783
+ | アゼルバイジャン語 | `az` | ベラルーシ語 | `be` |
784
+ | ブルガリア語 | `bg` | ベンガル語 | `bn` |
785
+ | カタルーニャ語 | `ca` | セブアノ語 | `ceb` |
786
+ | ドイツ語 | `de` | スペイン語 | `es` |
787
+ | エストニア語 | `et` | バスク語 | `eu` |
788
+ | ペルシャ語 | `fa` | フランス語 | `fr` |
789
+ | グジャラート語 | `gu` | ヘブライ語 | `he` |
790
+ | ヒンディー語 | `hi` | クロアチア語 | `hr` |
791
+ | ハンガリー語 | `hu` | アルメニア語 | `hy` |
792
+ | インドネシア語 | `id` | イタリア語 | `it` |
793
+ | ジャワ語 | `jv` | ジ��ージア語 | `ka` |
794
+ | カザフ語 | `kk` | クメール語 | `km` |
795
+ | リトアニア語 | `lt` | ラトビア語 | `lv` |
796
+ | マラヤーラム語 | `ml` | マラーティー語 | `mr` |
797
+ | マレー語 | `ms` | ミャンマー語 | `my` |
798
+ | ネパール語 | `ne` | オランダ語 | `nl` |
799
+ | パンジャーブ語 | `pa` | ポーランド語 | `pl` |
800
+ | ロシア語 | `ru` | シンハラ語 | `si` |
801
+ | スロバキア語 | `sk` | スロベニア語 | `sl` |
802
+ | セルビア語 | `sr` | スワヒリ語 | `sw` |
803
+ | タミル語 | `ta` | テルグ語 | `te` |
804
+ | タイ語 | `th` | タガログ語 | `tl` |
805
+ | ウルドゥー語 | `ur` | ウズベク語 | `uz` |
806
+ | ベトナム語 | `vi` | | |
807
+
808
+ </details>
809
+
810
+ ## ライセンス
811
+
812
+ PLaMo 3 Translate 0.8B W4AFP8は、[PLaMo Community License](https://plamo.preferredai.jp/info/plamo-community-license-en)のもとで公開されています。
813
+
814
+ - [英語版](https://plamo.preferredai.jp/info/plamo-community-license-en)
815
+ - [日本語版](https://plamo.preferredai.jp/info/plamo-community-license-ja)
816
+
817
+ **私的な用途・非商用利用**
818
+
819
+ 個人での学習や趣味など、私的な用途であれば、モデルを無償でダウンロードし、自由にご利用いただけます。学術用途を含む非商用利用でも、収入や売上の規模による制限はなく、PFNへの事前の利用登録も不要です。
820
+
821
+ **商用利用(収入または売上が10億円以下の場合)**
822
+
823
+ 利用者またはその関係会社の直近事業年度の収入または売上が10億円以下であれば、[PLaMo商用利用登録フォーム](https://forms.gle/mTL8tBLrMYXKNZD56)で利用用途を登録することで、送信した時点から無償で商用利用できます。
824
+
825
+ **商用利用(収入または売上が10億円を超える場合)**
826
+
827
+ 別途ライセンス契約が必要です。上記の登録フォームではなく、[PLaMo翻訳モデルに関するお問い合わせ](https://translate.preferredai.jp/llm/contact/)からPFNまでご相談ください。
828
+
829
+ 詳細はPLaMo Community Licenseの本文をご確認ください。
830
+
831
+ ## Preferred NetworksグループのAIポリシー
832
+
833
+ - [日本語](https://www.preferred.jp/ja/company/aipolicy/)
834
+ - [English](https://www.preferred.jp/en/company/aipolicy/)
chat_template.jinja ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {# Public translation request -> PFML3. Preserve all text whitespace. #}
2
+ {%- macro check_text(value, name, allow_empty=false) -%}
3
+ {%- if value is not string -%}
4
+ {{- raise_exception(name + ' must be a string.') -}}
5
+ {%- endif -%}
6
+ {%- if not allow_empty and not (value | trim) -%}
7
+ {{- raise_exception(name + ' must not be empty.') -}}
8
+ {%- endif -%}
9
+ {%- if '<|plamo:' in value -%}
10
+ {{- raise_exception(name + ' must not contain reserved PFML tokens (<|plamo:...).') -}}
11
+ {%- endif -%}
12
+ {%- endmacro -%}
13
+ {%- macro check_lang(value, name) -%}
14
+ {{- check_text(value, name) -}}
15
+ {%- if value != 'ja(easy)' -%}
16
+ {%- set parts = value.split('-') -%}
17
+ {%- if parts | length > 2 or parts[0] | length not in [2, 3] or (parts | length == 2 and parts[1] | length != 4) -%}
18
+ {{- raise_exception(name + ' must be a lowercase language code, e.g. en, ja, zh-hans, or ja(easy).') -}}
19
+ {%- endif -%}
20
+ {%- for char in value -%}
21
+ {%- if char not in 'abcdefghijklmnopqrstuvwxyz-' -%}
22
+ {{- raise_exception(name + ' must use lowercase language codes without region subtags.') -}}
23
+ {%- endif -%}
24
+ {%- endfor -%}
25
+ {%- endif -%}
26
+ {%- endmacro -%}
27
+ {%- if messages | length == 0 or messages | length % 2 != 1 -%}
28
+ {{- raise_exception('Provide source/translation pairs followed by one user message.') -}}
29
+ {%- endif -%}
30
+ {%- for message in messages -%}
31
+ {%- if message is not mapping -%}
32
+ {{- raise_exception('Each message must contain a role and text content.') -}}
33
+ {%- endif -%}
34
+ {%- if message['role'] == 'system' -%}
35
+ {{- raise_exception('System messages are not supported; use context for reference text.') -}}
36
+ {%- endif -%}
37
+ {%- if (loop.index0 % 2 == 0 and message['role'] != 'user') or (loop.index0 % 2 == 1 and message['role'] != 'assistant') -%}
38
+ {{- raise_exception('Alternate user source text and assistant translation; end with user.') -}}
39
+ {%- endif -%}
40
+ {%- if message['tool_calls'] or message['tool_call_id'] or message['function_call'] -%}
41
+ {{- raise_exception('Tool calls are not supported.') -}}
42
+ {%- endif -%}
43
+ {{- check_text(message['content'], 'message content') -}}
44
+ {%- endfor -%}
45
+ {%- if tools or documents -%}
46
+ {{- raise_exception('Tool calls and documents are not supported; use context for reference text.') -}}
47
+ {%- endif -%}
48
+ {%- if not add_generation_prompt -%}
49
+ {{- raise_exception('Use add_generation_prompt=True for translation inference.') -}}
50
+ {%- endif -%}
51
+ {%- if target_lang is not defined -%}
52
+ {{- raise_exception('target_lang is required, e.g. target_lang="ja".') -}}
53
+ {%- endif -%}
54
+ {{- check_lang(target_lang, 'target_lang') -}}
55
+ {%- if source_lang is defined and source_lang is not none -%}
56
+ {{- check_lang(source_lang, 'source_lang') -}}
57
+ {%- endif -%}
58
+ {%- if context is defined and context is not none -%}
59
+ {{- check_text(context, 'context', allow_empty=true) -}}
60
+ {%- endif -%}
61
+ {%- if form is defined and form is not none -%}
62
+ {%- if form not in ['polite', 'plain'] or target_lang != 'ja' -%}
63
+ {{- raise_exception('form must be polite or plain and requires target_lang="ja".') -}}
64
+ {%- endif -%}
65
+ {%- endif -%}
66
+ {%- if glossary is defined and glossary is not none -%}
67
+ {%- if glossary is not sequence or glossary is string or glossary is mapping -%}
68
+ {{- raise_exception('glossary must be a list of objects with source and target strings.') -}}
69
+ {%- endif -%}
70
+ {%- for term in glossary -%}
71
+ {%- if term is not mapping or term | length != 2 or 'source' not in term or 'target' not in term -%}
72
+ {{- raise_exception('Each glossary entry must contain exactly source and target.') -}}
73
+ {%- endif -%}
74
+ {{- check_text(term['source'], 'glossary source') -}}
75
+ {{- check_text(term['target'], 'glossary target') -}}
76
+ {%- endfor -%}
77
+ {%- endif -%}
78
+ {{- bos_token + '<|plamo:tag|>dataset<|plamo:msg|>translation' -}}
79
+ {%- if context is defined and context -%}
80
+ {{- '<|plamo:tag|>context<|plamo:msg|>' + context -}}
81
+ {%- endif -%}
82
+ {%- for message in messages[:-1] -%}
83
+ {%- if message['role'] == 'user' -%}
84
+ {{- '<|plamo:tag|>input' -}}
85
+ {%- if source_lang is defined and source_lang is not none -%}
86
+ {{- '<|plamo:key|>lang<|plamo:val|>' + source_lang -}}
87
+ {%- endif -%}
88
+ {%- else -%}
89
+ {{- '<|plamo:tag|>output<|plamo:key|>lang<|plamo:val|>' + target_lang -}}
90
+ {%- endif -%}
91
+ {{- '<|plamo:msg|>' + message['content'] -}}
92
+ {%- endfor -%}
93
+ {%- if glossary is defined and glossary -%}
94
+ {{- '<|plamo:tag|>glossary' -}}
95
+ {%- for term in glossary -%}
96
+ {{- '<|plamo:index|>' + term['source'] + '<|plamo:item|>' + term['target'] -}}
97
+ {%- endfor -%}
98
+ {%- endif -%}
99
+ {{- '<|plamo:tag|>input' -}}
100
+ {%- if source_lang is defined and source_lang is not none -%}
101
+ {{- '<|plamo:key|>lang<|plamo:val|>' + source_lang -}}
102
+ {%- endif -%}
103
+ {{- '<|plamo:msg|>' + messages[-1]['content'] + '<|plamo:tag|>output<|plamo:key|>lang<|plamo:val|>' + target_lang -}}
104
+ {%- if form is defined and form is not none -%}
105
+ {{- '<|plamo:key|>form<|plamo:val|>' + form -}}
106
+ {%- endif -%}
107
+ {{- '<|plamo:msg|>' -}}
config.json ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "Plamo3ForCausalLM"
4
+ ],
5
+ "auto_map": {
6
+ "AutoConfig": "modeling_plamo.Plamo3Config",
7
+ "AutoModelForCausalLM": "modeling_plamo.Plamo3ForCausalLM"
8
+ },
9
+ "bos_token_id": 1,
10
+ "dtype": "bfloat16",
11
+ "eos_token_id": 1,
12
+ "head_dim": 128,
13
+ "hidden_size": 1536,
14
+ "image_feature_size": null,
15
+ "image_proj_type": "linear",
16
+ "image_token_id": null,
17
+ "initial_context_length": 4096,
18
+ "intermediate_size": 6144,
19
+ "linear_type": "normal",
20
+ "max_position_embeddings": 262144,
21
+ "model_type": "plamo3",
22
+ "num_attention_heads": 16,
23
+ "num_hidden_layers": 16,
24
+ "num_key_value_heads": 1,
25
+ "pad_token_id": 3,
26
+ "rms_norm_eps": 1e-06,
27
+ "rope_local_theta": 10000,
28
+ "rope_scaling_factor": 256.0,
29
+ "rope_theta": 1000000,
30
+ "scale_embedding": false,
31
+ "sliding_window_pattern": 8,
32
+ "tie_word_embeddings": false,
33
+ "tokenizer_class": "Plamo3Tokenizer",
34
+ "transformers_version": "4.57.1",
35
+ "use_cache": true,
36
+ "vocab_size": 107520,
37
+ "window_size": 2048,
38
+ "rope_parameters": {
39
+ "full_attention": {
40
+ "rope_type": "yarn",
41
+ "rope_theta": 1000000,
42
+ "factor": 256.0,
43
+ "original_max_position_embeddings": 4096,
44
+ "beta_fast": 32.0,
45
+ "beta_slow": 1.0,
46
+ "truncate": false
47
+ },
48
+ "sliding_attention": {
49
+ "rope_type": "default",
50
+ "rope_theta": 10000
51
+ }
52
+ },
53
+ "quantization_config": {
54
+ "quant_method": "compressed-tensors",
55
+ "format": "pack-quantized",
56
+ "quantization_status": "compressed",
57
+ "kv_cache_scheme": null,
58
+ "global_compression_ratio": null,
59
+ "ignore": [
60
+ "lm_head"
61
+ ],
62
+ "config_groups": {
63
+ "group_0": {
64
+ "targets": [
65
+ "Linear"
66
+ ],
67
+ "format": "pack-quantized",
68
+ "weights": {
69
+ "num_bits": 4,
70
+ "type": "int",
71
+ "strategy": "group",
72
+ "group_size": 128,
73
+ "symmetric": true,
74
+ "dynamic": false,
75
+ "actorder": null,
76
+ "block_structure": null,
77
+ "observer": "minmax",
78
+ "observer_kwargs": {}
79
+ },
80
+ "input_activations": {
81
+ "num_bits": 8,
82
+ "type": "float",
83
+ "strategy": "token",
84
+ "symmetric": true,
85
+ "dynamic": true,
86
+ "actorder": null,
87
+ "block_structure": null,
88
+ "group_size": null,
89
+ "observer": null,
90
+ "observer_kwargs": {}
91
+ },
92
+ "output_activations": null
93
+ }
94
+ }
95
+ }
96
+ }
figures/benchmark_en.png ADDED

Git LFS Details

  • SHA256: 6c58fa2348a9f38e1fb6ec3b0f6a95e325ffa51a69c4fe996cc7f6fbaf0ba876
  • Pointer size: 131 Bytes
  • Size of remote file: 579 kB
figures/benchmark_ja.png ADDED

Git LFS Details

  • SHA256: db3974d9fdcaad96517d385027fb1f986be31a3e0e0bfad56b8df0295f205f80
  • Pointer size: 131 Bytes
  • Size of remote file: 586 kB
generation_config.json ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token_id": 1,
3
+ "eos_token_id": [
4
+ 1,
5
+ 16
6
+ ],
7
+ "pad_token_id": 3,
8
+ "transformers_version": "4.57.1"
9
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:843a53e780e4da07ea137a684a6041ea3e2eb428206d9c98c7f72ac13777ef1a
3
+ size 949564544
modeling_plamo.py ADDED
@@ -0,0 +1,1091 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import enum
2
+ import math
3
+ import warnings
4
+ from typing import Any, Dict, List, Literal, NamedTuple, Optional, Tuple, Union
5
+
6
+ import torch
7
+ from torch import nn
8
+ from torch.nn import functional as F
9
+ from transformers import GenerationMixin, PretrainedConfig, PreTrainedModel
10
+ from transformers.cache_utils import DynamicCache
11
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
12
+
13
+
14
+ def _swiglu(h: torch.Tensor) -> torch.Tensor:
15
+ h0, h1 = h.chunk(2, dim=-1)
16
+ return torch.nn.functional.silu(h0) * h1
17
+
18
+
19
+ class RotaryEmbedding(torch.nn.Module):
20
+ def __init__(
21
+ self,
22
+ dim: int,
23
+ max_position_embeddings: int,
24
+ parameter: dict,
25
+ device: Optional[torch.device] = None,
26
+ ) -> None:
27
+ super().__init__()
28
+
29
+ self.dim = dim
30
+ self.max_position_embeddings = max_position_embeddings
31
+ self.base = parameter["rope_theta"]
32
+ self.scaling = None if parameter.get("rope_type", "default") == "default" else parameter
33
+ if device is None:
34
+ device = torch.zeros(1).device # get default device
35
+ if device.type == "meta":
36
+ device = torch.device("cpu")
37
+ self.device = device
38
+ self._compute_buffers()
39
+
40
+ def _compute_buffers(self) -> None:
41
+ # Explicit `device=` instead of a torch.device context: entering one under `deepspeed.zero.Init` freezes
42
+ # torch's cached constructor set on DeepSpeed's wrappers, so later contexts (vLLM's loader) stop working.
43
+ freq = self.base ** (torch.arange(0, self.dim, 2, device=self.device).float() / self.dim)
44
+ if self.scaling is None:
45
+ inv_freq = 1.0 / freq
46
+ concentration = 1.0
47
+ else:
48
+ factor = self.scaling["factor"]
49
+ beta_fast = self.scaling["beta_fast"]
50
+ beta_slow = self.scaling["beta_slow"]
51
+ original_length = self.scaling["original_max_position_embeddings"]
52
+ assert self.scaling["rope_type"] == "yarn"
53
+ assert not self.scaling["truncate"]
54
+
55
+ d_h = self.dim // 2
56
+ low = d_h * math.log(original_length / (beta_fast * 2 * math.pi)) / math.log(self.base)
57
+ high = d_h * math.log(original_length / (beta_slow * 2 * math.pi)) / math.log(self.base)
58
+ assert 0 < low < high < d_h - 1, (low, high, d_h, self.scaling)
59
+ interpolation = 1.0 / (factor * freq)
60
+ extrapolation = 1.0 / freq
61
+ ramp = (torch.arange(d_h, device=self.device).to(torch.float32) - low) / (
62
+ high - low
63
+ ) # differs from pretrain: stays fp32 under deepspeed.zero.Init
64
+ mask = 1 - torch.clamp(ramp, 0, 1)
65
+ inv_freq = interpolation * (1.0 - mask) + extrapolation * mask
66
+
67
+ concentration = 0.1 * math.log(factor) + 1.0
68
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
69
+ self.concentration = concentration
70
+
71
+ def _apply(self, fn: Any, recurse: bool = True) -> "RotaryEmbedding":
72
+ # `Module.to(dtype)` casts buffers too; rebuild `inv_freq` in fp32 instead of keeping the rounded one.
73
+ super()._apply(fn, recurse=recurse)
74
+ if self.inv_freq.device.type != "meta":
75
+ self.device = self.inv_freq.device
76
+ self._compute_buffers()
77
+ return self
78
+
79
+ def forward(self, x: torch.Tensor, seq_len: int) -> Tuple[torch.Tensor, torch.Tensor]:
80
+ # x: [bs, num_attention_heads, seq_len, head_size]
81
+ device = x.device
82
+ inv_freq = self.inv_freq if self.inv_freq.device == device else self.inv_freq.to(device=device)
83
+ t = torch.arange(seq_len, device=device, dtype=inv_freq.dtype)
84
+
85
+ freqs = torch.einsum("i,j->ij", t, inv_freq)
86
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
87
+ emb = torch.cat((freqs, freqs), dim=-1)
88
+ cos = emb.cos()[None, None, :, :].to(dtype=x.dtype) * self.concentration
89
+ sin = emb.sin()[None, None, :, :].to(dtype=x.dtype) * self.concentration
90
+ return cos, sin
91
+
92
+
93
+ def _rotate_half(x: torch.Tensor) -> torch.Tensor:
94
+ """Rotates half the hidden dims of the input."""
95
+ x1 = x[..., : x.shape[-1] // 2]
96
+ x2 = x[..., x.shape[-1] // 2 :]
97
+ return torch.cat((-x2, x1), dim=-1)
98
+
99
+
100
+ def _rotary_pos_emb(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor, position_ids: torch.Tensor) -> torch.Tensor:
101
+ # The first two dimensions of cos and sin are always 1, so we can `squeeze` them.
102
+ cos = cos.squeeze(1).squeeze(0) # [seq_len, dim]
103
+ sin = sin.squeeze(1).squeeze(0) # [seq_len, dim]
104
+ cos = cos[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim]
105
+ sin = sin[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim]
106
+ x_embed = (x * cos) + (_rotate_half(x) * sin)
107
+ return x_embed
108
+
109
+
110
+ class LinearType(str, enum.Enum):
111
+ Normal = "normal"
112
+ Fp8 = "fp8"
113
+
114
+
115
+ def is_full_attn(sliding_window_pattern: int, layer_idx: int) -> bool:
116
+ return not bool((layer_idx + 1) % sliding_window_pattern)
117
+
118
+
119
+ class Plamo3Config(PretrainedConfig): # type: ignore
120
+ model_type: str = "plamo3"
121
+
122
+ def __init__(
123
+ self,
124
+ hidden_size: int = 4096,
125
+ num_hidden_layers: int = 32,
126
+ rms_norm_eps: float = 1e-6,
127
+ # Embedding
128
+ scale_embedding: bool = False,
129
+ tie_word_embeddings: bool = True,
130
+ # Attention
131
+ num_attention_heads: int = 32,
132
+ num_key_value_heads: int = 4,
133
+ head_dim: int = 128,
134
+ max_position_embeddings: int = 2048,
135
+ window_size: int = 2048,
136
+ sliding_window_pattern: int = 8,
137
+ rope_theta: int = 150000,
138
+ rope_local_theta: int = 10000,
139
+ rope_scaling_factor: float = 1,
140
+ initial_context_length: int | None = None,
141
+ # MLP
142
+ intermediate_size: int = 13312,
143
+ # Tokenizer
144
+ vocab_size: int = 32000,
145
+ tokenizer_class: str = "Plamo3Tokenizer",
146
+ pad_token_id: Optional[int] = None,
147
+ bos_token_id: int = 1,
148
+ eos_token_id: int = 2,
149
+ # Multimodal
150
+ image_token_id: Optional[int] = None,
151
+ image_feature_size: Optional[int] = None,
152
+ image_proj_type: Literal["linear", "mlp"] = "linear",
153
+ # FP8
154
+ linear_type: LinearType = LinearType.Normal,
155
+ # Evaluation
156
+ use_cache: bool = True,
157
+ **kwargs: Any,
158
+ ) -> None:
159
+ self.max_position_embeddings = max_position_embeddings
160
+ self.hidden_size = hidden_size
161
+ self.rms_norm_eps = rms_norm_eps
162
+
163
+ self.num_hidden_layers = num_hidden_layers
164
+ self.num_attention_heads = num_attention_heads
165
+ self.head_dim = head_dim
166
+ self.num_key_value_heads = num_key_value_heads
167
+ self.window_size = window_size
168
+ self.sliding_window_pattern = sliding_window_pattern
169
+ self.rope_theta = rope_theta
170
+ self.rope_local_theta = rope_local_theta
171
+ self.rope_scaling_factor = rope_scaling_factor
172
+ self.initial_context_length = initial_context_length
173
+
174
+ self.intermediate_size = intermediate_size
175
+
176
+ self.vocab_size = vocab_size
177
+
178
+ self.image_token_id = image_token_id
179
+ self.image_feature_size = image_feature_size
180
+ self.image_proj_type = image_proj_type
181
+
182
+ self.linear_type = linear_type
183
+
184
+ self.use_cache = use_cache
185
+
186
+ self.scale_embedding = scale_embedding
187
+
188
+ super().__init__(
189
+ tokenizer_class=tokenizer_class,
190
+ pad_token_id=pad_token_id,
191
+ bos_token_id=bos_token_id,
192
+ eos_token_id=eos_token_id,
193
+ tie_word_embeddings=tie_word_embeddings,
194
+ **kwargs,
195
+ )
196
+
197
+ @property
198
+ def rope_parameters(self) -> dict:
199
+ rope_parameters_all = {
200
+ "full_attention": {},
201
+ "sliding_attention": {
202
+ "rope_theta": self.rope_local_theta,
203
+ "rope_type": "default",
204
+ },
205
+ }
206
+ if self.rope_scaling_factor == 1:
207
+ assert self.initial_context_length is None
208
+ rope_parameters_all["full_attention"] = {
209
+ "rope_theta": self.rope_theta,
210
+ "rope_type": "default",
211
+ }
212
+ else:
213
+ assert self.initial_context_length is not None
214
+ rope_parameters_all["full_attention"] = {
215
+ "rope_theta": self.rope_theta,
216
+ "beta_fast": 32.0,
217
+ "beta_slow": 1.0,
218
+ "factor": self.rope_scaling_factor,
219
+ "original_max_position_embeddings": self.initial_context_length,
220
+ "rope_type": "yarn",
221
+ "truncate": False,
222
+ }
223
+ rope_parameters = {}
224
+ for layer_type in set(self.layer_types):
225
+ rope_parameters[layer_type] = rope_parameters_all[layer_type]
226
+ return rope_parameters
227
+
228
+ @rope_parameters.setter
229
+ def rope_parameters(self, rope_parameters: dict) -> None:
230
+ # Notes: transformers>=5.0.0 try to convert `rope_parameters`,
231
+ # but it raises error if config does not have setter of `rope_parameters`.
232
+ pass
233
+
234
+ def _validate_yarn_rope_parameters(self, rope_parameters: dict, ignore_keys: set | None = None) -> None:
235
+ # Work around a transformers v5.8.0 YaRN validation bug. For nested
236
+ # per-layer RoPE parameters, transformers passes the layer-local dict
237
+ # here, but then reads `self.rope_parameters["original_max_position_embeddings"]`
238
+ # as if the config were not nested.
239
+ required_keys = {"rope_type", "factor", "original_max_position_embeddings"}
240
+ optional_keys = {
241
+ "rope_theta",
242
+ "attention_factor",
243
+ "beta_fast",
244
+ "beta_slow",
245
+ "mscale",
246
+ "mscale_all_dim",
247
+ "truncate",
248
+ }
249
+ received_keys = set(rope_parameters.keys())
250
+ rope_type = rope_parameters["rope_type"]
251
+ self._check_received_keys(rope_type, received_keys, required_keys, optional_keys, ignore_keys=ignore_keys)
252
+
253
+ factor = rope_parameters["factor"]
254
+ if factor is None or not isinstance(factor, (float, int)) or factor < 1.0:
255
+ warnings.warn(f"`rope_parameters`'s factor field must be a float or int >= 1, got {factor}", stacklevel=2)
256
+
257
+ attention_factor = rope_parameters.get("attention_factor")
258
+ if attention_factor is not None and (not isinstance(attention_factor, float) or attention_factor < 0):
259
+ warnings.warn(
260
+ f"`rope_parameters`'s attention_factor field must be a float greater than 0, got {attention_factor}",
261
+ stacklevel=2,
262
+ )
263
+ beta_fast = rope_parameters.get("beta_fast")
264
+ if beta_fast is not None and not isinstance(beta_fast, (float, int)):
265
+ warnings.warn(f"`rope_parameters`'s beta_fast field must be a float or int, got {beta_fast}", stacklevel=2)
266
+ beta_slow = rope_parameters.get("beta_slow")
267
+ if beta_slow is not None and not isinstance(beta_slow, (float, int)):
268
+ warnings.warn(f"`rope_parameters`'s beta_slow field must be a float or int, got {beta_slow}", stacklevel=2)
269
+
270
+ if (beta_fast or 32) < (beta_slow or 1):
271
+ warnings.warn(
272
+ f"`rope_parameters`'s beta_fast field must be greater than beta_slow, got beta_fast={beta_fast} "
273
+ f"(defaults to 32 if None) and beta_slow={beta_slow} (defaults to 1 if None)",
274
+ stacklevel=2,
275
+ )
276
+
277
+ @property
278
+ def sliding_window(self) -> int:
279
+ return self.window_size
280
+
281
+ @property
282
+ def interleaved_sliding_window(self) -> list[int | None]:
283
+ interleaved_sliding_window: list[int | None] = []
284
+ for i in range(self.num_hidden_layers):
285
+ if is_full_attn(self.sliding_window_pattern, i):
286
+ interleaved_sliding_window.append(None)
287
+ else:
288
+ interleaved_sliding_window.append(self.window_size)
289
+ assert len(interleaved_sliding_window) == self.num_hidden_layers
290
+ return interleaved_sliding_window
291
+
292
+ @property
293
+ def layer_types(self) -> list[str]:
294
+ sliding_window: list[int | None] = []
295
+ for i in range(self.num_hidden_layers):
296
+ if is_full_attn(self.sliding_window_pattern, i):
297
+ sliding_window.append(None)
298
+ else:
299
+ sliding_window.append(self.window_size)
300
+ assert len(sliding_window) == self.num_hidden_layers
301
+
302
+ return [
303
+ "full_attention" if sliding_window_size is None else "sliding_attention"
304
+ for sliding_window_size in sliding_window
305
+ ]
306
+
307
+ @property
308
+ def layers_block_type(self) -> list[str]:
309
+ return ["attention" for i in range(self.num_hidden_layers)]
310
+
311
+ @property
312
+ def rope_local_base_freq(self) -> int:
313
+ return self.rope_local_theta
314
+
315
+
316
+ class DecoderInput(NamedTuple):
317
+ hidden_states: torch.Tensor
318
+ attention_mask: Optional[torch.Tensor] = None
319
+ past_states: Optional[DynamicCache] = None
320
+ output_hidden_states: Optional[bool] = False
321
+ output_attentions: Optional[bool] = False
322
+ gradient_checkpointing: bool = False
323
+ input_ids: Optional[torch.Tensor] = None
324
+
325
+
326
+ class DecoderOutput(NamedTuple):
327
+ hidden_states: torch.Tensor
328
+ all_hidden_states: Optional[Tuple[torch.Tensor, ...]]
329
+ all_self_attns: Optional[Tuple[torch.Tensor, ...]]
330
+
331
+
332
+ def _make_causal_mask(
333
+ input_ids_shape: Tuple[int, int],
334
+ dtype: torch.dtype,
335
+ device: torch.device,
336
+ seq_len: int,
337
+ cache_position: torch.Tensor,
338
+ ) -> torch.Tensor:
339
+ """
340
+ Make a causal attention mask.
341
+
342
+ Follows the logic in `LlamaModel._prepare_4d_causal_attention_mask_with_cache_position`
343
+ https://github.com/huggingface/transformers/blob/main/src/transformers/models/llama/modeling_llama.py#L664
344
+
345
+ NOTE: seq_len (sequence_length) and tgt_len(target_length) are swapped in the original code.
346
+ Our implementation:
347
+ - seq_len: the length of the sequences which is being processed as well as which have been processed
348
+ - tgt_len: the length of the sequences which is being processed
349
+
350
+ Original (Llama) implementation:
351
+ - sequence_length: "The sequence length being processed"
352
+ - target_length: "when generating with static cache, the mask should be as long as the static cache,
353
+ to account for the 0 padding, the part of the cache that is not filled yet."
354
+ """
355
+ bsz, tgt_len = input_ids_shape
356
+
357
+ mask = torch.full((tgt_len, seq_len), float("-inf"), device=device)
358
+ if tgt_len != 1:
359
+ # TODO: is this necessary?
360
+ mask = torch.triu(mask, diagonal=1)
361
+ mask = torch.where(torch.arange(seq_len, device=device) > cache_position.reshape(-1, 1), mask, 0.0)
362
+ mask = mask.to(dtype)
363
+ return mask[None, None, :, :].expand(bsz, 1, tgt_len, seq_len)
364
+
365
+
366
+ # Copied from transformers.models.bart.modeling_bart._expand_mask
367
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None) -> torch.Tensor:
368
+ """
369
+ Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
370
+ """
371
+ bsz, src_len = mask.size()
372
+ tgt_len = tgt_len if tgt_len is not None else src_len
373
+
374
+ expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
375
+
376
+ inverted_mask = 1.0 - expanded_mask
377
+
378
+ return inverted_mask.masked_fill(inverted_mask.to(torch.bool), float("-inf")) # type: ignore
379
+
380
+
381
+ def _plamo3_rms_norm(
382
+ hidden_states: torch.Tensor, weight: Optional[torch.Tensor], eps: float, offset: float = 1.0
383
+ ) -> torch.Tensor:
384
+ input_dtype = hidden_states.dtype
385
+ hidden_states = hidden_states.to(torch.float32)
386
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
387
+ hidden_states = hidden_states * torch.rsqrt(variance + eps)
388
+ hidden_states = hidden_states.to(input_dtype)
389
+ if weight is not None:
390
+ hidden_states = (offset + weight) * hidden_states
391
+ return hidden_states
392
+
393
+
394
+ class Plamo3RMSNorm(nn.Module):
395
+ """
396
+ Note:
397
+ This is a customized RMSNorm used in PLaMo-2/3.
398
+ An explicit offset (e.g. 1.0) is added to the weight during forward,
399
+ so its behavior differs from torch.nn.RMSNorm, especially under weight decay.
400
+ For inference-only replacement with torch.nn.RMSNorm,
401
+ the offset must be folded into the weight (weight += offset).
402
+ """
403
+
404
+ def __init__(
405
+ self,
406
+ hidden_size: int,
407
+ eps: float = 1e-6,
408
+ offset: float = 1.0,
409
+ device: Optional[Union[torch.device, str]] = None,
410
+ ) -> None:
411
+ super().__init__()
412
+ self.weight = nn.Parameter(torch.zeros(hidden_size, device=device))
413
+ self.variance_epsilon = eps
414
+ self.offset = offset
415
+
416
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
417
+ return _plamo3_rms_norm(hidden_states, self.weight, self.variance_epsilon, offset=self.offset)
418
+
419
+
420
+ class Plamo3Embedding(nn.Embedding):
421
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
422
+ y = super().forward(x)
423
+ return y * (self.embedding_dim**0.5) # type: ignore
424
+
425
+
426
+ def swa_mask(q_len: int, kv_len: int, device: torch.device, window_size: int) -> torch.Tensor:
427
+ max_len = max(q_len, kv_len)
428
+ query_positions = torch.arange(max_len - q_len, max_len, device=device)
429
+ key_positions = torch.arange(max_len - kv_len, max_len, device=device)
430
+ mask = key_positions[None, :] > query_positions[:, None] - window_size
431
+ mask &= key_positions[None, :] < query_positions[:, None] + window_size
432
+ return mask
433
+
434
+
435
+ class Attention(torch.nn.Module):
436
+ def __init__(self, config: Plamo3Config, layer_idx: int) -> None:
437
+ super().__init__()
438
+ self.config = config
439
+ self.layer_idx = layer_idx
440
+ self.hidden_size = config.hidden_size
441
+ head_dim = config.head_dim
442
+ self.max_position_embeddings = config.max_position_embeddings
443
+
444
+ self.q_num_heads = config.num_attention_heads
445
+ self.qk_dim = self.v_dim = head_dim
446
+ self.k_num_heads = self.v_num_heads = config.num_key_value_heads
447
+ assert self.q_num_heads % self.k_num_heads == 0
448
+ self.n_group = self.q_num_heads // self.k_num_heads
449
+
450
+ self.q_proj_dim = self.q_num_heads * self.qk_dim
451
+ self.k_proj_dim = self.k_num_heads * self.qk_dim
452
+ self.v_proj_dim = self.v_num_heads * self.v_dim
453
+ self.qkv_proj = nn.Linear(self.hidden_size, self.q_proj_dim + self.k_proj_dim + self.v_proj_dim, bias=False)
454
+ self.o_proj = nn.Linear(self.q_num_heads * self.v_dim, self.hidden_size, bias=False)
455
+
456
+ self.q_norm = Plamo3RMSNorm(self.qk_dim, eps=self.config.rms_norm_eps, offset=1.0)
457
+ self.k_norm = Plamo3RMSNorm(self.qk_dim, eps=self.config.rms_norm_eps, offset=1.0)
458
+
459
+ self.full_attn = config.layer_types[layer_idx] == "full_attention"
460
+ parameter = self.config.rope_parameters[config.layer_types[layer_idx]]
461
+ self.rotary_emb = RotaryEmbedding(
462
+ self.qk_dim, max_position_embeddings=self.config.max_position_embeddings, parameter=parameter
463
+ )
464
+
465
+ def forward(
466
+ self,
467
+ hidden_states: torch.Tensor,
468
+ attention_mask: Optional[torch.Tensor] = None,
469
+ past_states: Optional[DynamicCache] = None,
470
+ output_attentions: bool = False,
471
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[DynamicCache]]:
472
+ bsz, q_len, _ = hidden_states.size()
473
+
474
+ qkv = self.qkv_proj(hidden_states)
475
+ query_states, key_states, value_states = torch.split(
476
+ qkv, [self.q_proj_dim, self.k_proj_dim, self.v_proj_dim], dim=-1
477
+ )
478
+ query_states = query_states.view(bsz, q_len, self.q_num_heads, self.qk_dim).transpose(1, 2)
479
+ key_states = key_states.view(bsz, q_len, self.k_num_heads, self.qk_dim).transpose(1, 2)
480
+ value_states = value_states.view(bsz, q_len, self.v_num_heads, self.v_dim).transpose(1, 2)
481
+
482
+ attn_dtype = query_states.dtype
483
+
484
+ query_states = self.q_norm(query_states)
485
+ key_states = self.k_norm(key_states)
486
+
487
+ if past_states is not None:
488
+ key_states, value_states = past_states.update(key_states, value_states, self.layer_idx)
489
+
490
+ # NICT inference path: each cached key keeps its own position; the query
491
+ # occupies the tail of the same local coordinate system after SWA cropping.
492
+ kv_seq_len = key_states.shape[-2]
493
+ key_position_ids = torch.arange(kv_seq_len, dtype=torch.long, device=hidden_states.device)[None]
494
+ q_position_ids = key_position_ids[:, -query_states.shape[2] :]
495
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
496
+ query_states = _rotary_pos_emb(query_states, cos, sin, q_position_ids)
497
+ key_states = _rotary_pos_emb(key_states, cos, sin, key_position_ids)
498
+ # [bsz, nh, t, hd]
499
+
500
+ query_states = query_states.to(attn_dtype)
501
+ key_states = key_states.to(attn_dtype)
502
+ value_states = value_states.to(attn_dtype)
503
+ if attention_mask is not None and attention_mask.dtype != torch.bool:
504
+ attention_mask = attention_mask.to(attn_dtype)
505
+
506
+ if attention_mask is None:
507
+ assert self.full_attn or key_states.shape[2] <= self.config.window_size + 1
508
+ attn_output = F.scaled_dot_product_attention(
509
+ query_states, key_states, value_states, is_causal=True, enable_gqa=True
510
+ )
511
+ else:
512
+ if attention_mask.dtype == torch.bool:
513
+ attention_mask = torch.where(attention_mask, torch.tensor(0.0, dtype=torch.float), float("-inf"))
514
+ if len(attention_mask.shape) == 2:
515
+ attention_mask = attention_mask[None, None]
516
+ assert len(attention_mask.shape) == 4
517
+
518
+ if not self.full_attn:
519
+ m_swa = swa_mask(
520
+ query_states.shape[2], key_states.shape[2], query_states.device, self.config.window_size
521
+ )
522
+ # `generate` function creates attention mask that does not consider sliding window
523
+ m_swa = m_swa[None, None]
524
+ attention_mask = attention_mask[:, :, -query_states.shape[2] :, -key_states.shape[2] :]
525
+ attention_mask = torch.where(m_swa, attention_mask, float("-inf"))
526
+
527
+ # like AttentionMaskConverter._unmask_unattended in huggingface.transfoermers,
528
+ # we need to attend to all tokens in masked rows for `scaled_dot_product_attention`
529
+ bool_mask = torch.logical_not(torch.isneginf(attention_mask))
530
+ valid_tokens = torch.any(bool_mask, dim=-1) # (..., q_len)
531
+ attention_mask = torch.where(valid_tokens[..., None], attention_mask, float(0.0))
532
+ attn_output = F.scaled_dot_product_attention(
533
+ query_states,
534
+ key_states,
535
+ value_states,
536
+ attn_mask=attention_mask,
537
+ enable_gqa=True,
538
+ )
539
+
540
+ attn_output = attn_output.transpose(1, 2)
541
+
542
+ attn_output = attn_output.reshape(bsz, q_len, self.q_num_heads * self.v_dim)
543
+ attn_output = self.o_proj(attn_output)
544
+
545
+ return attn_output, None, past_states
546
+
547
+
548
+ class MLP(nn.Module):
549
+ def __init__(self, config: Plamo3Config) -> None:
550
+ super().__init__()
551
+ self.config = config
552
+ self.hidden_size = config.hidden_size
553
+ self.intermediate_size = config.intermediate_size
554
+ self.gate_up_proj = torch.nn.Linear(self.hidden_size, self.intermediate_size * 2, bias=False)
555
+ self.down_proj = torch.nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
556
+
557
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
558
+ h = self.gate_up_proj(x)
559
+ h = _swiglu(h)
560
+ return self.down_proj(h) # type: ignore
561
+
562
+
563
+ class Plamo3DecoderLayer(torch.nn.Module):
564
+ def __init__(self, config: Plamo3Config, layer_idx: int) -> None:
565
+ super().__init__()
566
+ self.config = config
567
+ self.hidden_size = config.hidden_size
568
+ self.mixer: torch.nn.Module
569
+ self.mixer = Attention(config, layer_idx)
570
+ self.mlp = MLP(config)
571
+ """
572
+ Notes: The model performance was degraded when setting all offsets to 1.
573
+ """
574
+ self.pre_mixer_norm = Plamo3RMSNorm(config.hidden_size, eps=config.rms_norm_eps, offset=1.0)
575
+ self.post_mixer_norm = Plamo3RMSNorm(config.hidden_size, eps=config.rms_norm_eps, offset=1.0 / 5)
576
+ self.pre_mlp_norm = Plamo3RMSNorm(config.hidden_size, eps=config.rms_norm_eps, offset=1.0)
577
+ self.post_mlp_norm = Plamo3RMSNorm(config.hidden_size, eps=config.rms_norm_eps, offset=1.0 / (5**1.5))
578
+
579
+ def forward(
580
+ self,
581
+ hidden_states: torch.Tensor,
582
+ attention_mask: Optional[torch.Tensor] = None,
583
+ past_state: Optional[DynamicCache] = None,
584
+ output_attentions: Optional[bool] = False,
585
+ ) -> Tuple[Any, ...]:
586
+ # from LlamaDecoder
587
+ residual = hidden_states
588
+ hidden_states = self.pre_mixer_norm(hidden_states)
589
+
590
+ # Self Attention
591
+ hidden_states_sa, self_attn_weights, present_key_value = self.mixer(
592
+ hidden_states=hidden_states,
593
+ attention_mask=attention_mask,
594
+ past_states=past_state,
595
+ output_attentions=output_attentions,
596
+ )
597
+
598
+ hidden_states_sa = self.post_mixer_norm(hidden_states_sa)
599
+ hidden_states = residual + hidden_states_sa
600
+
601
+ residual = hidden_states
602
+ hidden_states = self.pre_mlp_norm(hidden_states)
603
+
604
+ # Fully Connected
605
+ hidden_states_mlp = self.mlp(hidden_states)
606
+
607
+ # Residual
608
+ hidden_states_mlp = self.post_mlp_norm(hidden_states_mlp)
609
+ hidden_states = residual + hidden_states_mlp
610
+
611
+ outputs: Any = (hidden_states,)
612
+
613
+ if output_attentions:
614
+ outputs += (self_attn_weights,)
615
+
616
+ return outputs # type: ignore
617
+
618
+
619
+ class Plamo3Decoder(torch.nn.Module):
620
+ def __init__(self, config: Plamo3Config) -> None:
621
+ super().__init__()
622
+
623
+ self.layers = torch.nn.ModuleList(
624
+ [Plamo3DecoderLayer(config, layer_idx=i) for i in range(config.num_hidden_layers)]
625
+ )
626
+ self.gradient_checkpointing = False
627
+
628
+ def forward(self, x: DecoderInput) -> DecoderOutput:
629
+ if not isinstance(x, DecoderInput):
630
+ x = DecoderInput(*x)
631
+
632
+ # Unpack DecoderInput fields to locals for torch.fx compatibility.
633
+ hidden_states = x.hidden_states
634
+ attention_mask = x.attention_mask
635
+ past_states = x.past_states
636
+ output_hidden_states = x.output_hidden_states
637
+ output_attentions = x.output_attentions
638
+ gradient_checkpointing = x.gradient_checkpointing
639
+
640
+ all_hidden_states: Optional[Tuple[torch.Tensor, ...]] = () if output_hidden_states else None
641
+ all_self_attns: Optional[Tuple[torch.Tensor, ...]] = () if output_attentions else None
642
+
643
+ for decoder_layer in self.layers:
644
+ if output_hidden_states:
645
+ assert all_hidden_states is not None
646
+ all_hidden_states += (hidden_states,)
647
+
648
+ if self.training and gradient_checkpointing:
649
+ layer_outputs = self._gradient_checkpointing_func( # type: ignore
650
+ decoder_layer.__call__,
651
+ hidden_states,
652
+ attention_mask,
653
+ past_states,
654
+ output_attentions,
655
+ )
656
+ else:
657
+ layer_outputs = decoder_layer(
658
+ hidden_states,
659
+ attention_mask=attention_mask,
660
+ past_state=past_states,
661
+ output_attentions=output_attentions,
662
+ )
663
+
664
+ hidden_states = layer_outputs[0]
665
+
666
+ if output_attentions:
667
+ assert layer_outputs[1] is not None
668
+ assert all_self_attns is not None
669
+ all_self_attns += (layer_outputs[1],)
670
+ return DecoderOutput(hidden_states, all_hidden_states, all_self_attns)
671
+
672
+
673
+ class Plamo3PreTrainedModel(PreTrainedModel): # type: ignore
674
+ config_class = Plamo3Config
675
+ _no_split_modules: List[str]
676
+ base_model_prefix = "model"
677
+ supports_gradient_checkpointing = True
678
+ _no_split_modules = ["Plamo3DecoderLayer"]
679
+ _skip_keys_device_placement = "past_key_values"
680
+ _keys_to_ignore_on_load_unexpected = [r"decoder\.version"]
681
+
682
+ def _init_weights(self, module: torch.nn.Module) -> None:
683
+ std = 0.02
684
+ if isinstance(module, nn.Linear):
685
+ if getattr(module.weight, "_is_hf_initialized", False):
686
+ if module.bias is not None:
687
+ assert getattr(module.bias, "_is_hf_initialized", False)
688
+ return
689
+ module.weight.data.normal_(mean=0.0, std=std)
690
+ if module.bias is not None:
691
+ module.bias.data.zero_()
692
+ elif isinstance(module, nn.Embedding):
693
+ if getattr(module.weight, "_is_hf_initialized", False):
694
+ return
695
+ module.weight.data.normal_(mean=0.0, std=std)
696
+ if module.padding_idx is not None:
697
+ module.weight.data[module.padding_idx].zero_()
698
+ elif isinstance(module, RotaryEmbedding):
699
+ # Transformers may materialize this buffer on a different device during loading.
700
+ if module.inv_freq.device.type != "meta":
701
+ module.device = module.inv_freq.device
702
+ module._compute_buffers()
703
+
704
+
705
+ class Plamo3Model(Plamo3PreTrainedModel):
706
+ def __init__(self, config: Plamo3Config):
707
+ super().__init__(config)
708
+ self.padding_idx = config.pad_token_id
709
+ self.vocab_size = config.vocab_size
710
+
711
+ self.embed_tokens: nn.Embedding
712
+ if config.scale_embedding:
713
+ self.embed_tokens = Plamo3Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
714
+ else:
715
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
716
+ if config.image_feature_size is not None:
717
+ if config.image_proj_type == "mlp":
718
+ self.image_proj = MLPImageProjector(config) # type: ignore
719
+ elif config.image_proj_type == "linear":
720
+ self.image_proj = nn.Linear(config.image_feature_size, config.hidden_size, bias=False) # type: ignore
721
+ else:
722
+ raise ValueError(f"Unknown image_proj_type: {config.image_proj_type}")
723
+ self.layers = Plamo3Decoder(config) # type: ignore
724
+ self.norm = Plamo3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
725
+
726
+ self.gradient_checkpointing = False
727
+ # Initialize weights and apply final processing
728
+ self.post_init()
729
+
730
+ def get_input_embeddings(self) -> torch.nn.Embedding:
731
+ return self.embed_tokens
732
+
733
+ def set_input_embeddings(self, value: torch.nn.Embedding) -> None:
734
+ self.embed_tokens = value
735
+
736
+ def _prepare_decoder_attention_mask(
737
+ self,
738
+ attention_mask: torch.Tensor,
739
+ input_shape: Tuple[int, int],
740
+ inputs_embeds: torch.Tensor,
741
+ cache_position: torch.LongTensor,
742
+ ) -> Optional[torch.Tensor]:
743
+ # create causal mask
744
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
745
+ combined_attention_mask = _make_causal_mask(
746
+ input_shape,
747
+ inputs_embeds.dtype,
748
+ device=inputs_embeds.device,
749
+ seq_len=attention_mask.shape[-1],
750
+ cache_position=cache_position,
751
+ )
752
+ input_shape = (input_shape[0], combined_attention_mask.shape[2])
753
+
754
+ if attention_mask.dim() == 4:
755
+ # Custom 4D attention mask
756
+ expanded_attn_mask = attention_mask
757
+ else:
758
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
759
+ expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(
760
+ inputs_embeds.device
761
+ )
762
+ combined_attention_mask = (
763
+ expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
764
+ )
765
+
766
+ return combined_attention_mask
767
+
768
+ def forward(
769
+ self,
770
+ input_ids: Optional[torch.LongTensor] = None,
771
+ attention_mask: Optional[torch.Tensor] = None,
772
+ position_ids: Optional[torch.Tensor] = None,
773
+ past_key_values: Optional[DynamicCache] = None,
774
+ inputs_embeds: Optional[torch.Tensor] = None,
775
+ image_features: Optional[torch.Tensor] = None,
776
+ use_cache: Optional[bool] = None,
777
+ output_attentions: Optional[bool] = None,
778
+ output_hidden_states: Optional[bool] = None,
779
+ cache_position: Optional[torch.LongTensor] = None,
780
+ **kwargs: Any,
781
+ ) -> BaseModelOutputWithPast:
782
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
783
+ if output_attentions:
784
+ raise NotImplementedError("PLaMo 3 does not support output_attentions=True with its SDPA implementation.")
785
+ output_hidden_states = (
786
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
787
+ )
788
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
789
+
790
+ # retrieve input_ids and inputs_embeds
791
+ if (input_ids is None) ^ (inputs_embeds is not None):
792
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
793
+
794
+ if self.gradient_checkpointing and self.training and use_cache:
795
+ use_cache = False
796
+
797
+ if inputs_embeds is None:
798
+ inputs_embeds = self.embed_tokens(input_ids)
799
+ batch_size, seq_length, _ = inputs_embeds.shape
800
+
801
+ seq_length_with_past = seq_length
802
+ past_key_values_length = 0
803
+ if past_key_values is not None:
804
+ past_key_values_length = past_key_values.get_seq_length()
805
+ seq_length_with_past = seq_length_with_past + past_key_values_length
806
+
807
+ if cache_position is None:
808
+ cache_position = torch.arange(
809
+ past_key_values_length,
810
+ past_key_values_length + seq_length,
811
+ device=inputs_embeds.device,
812
+ ) # type: ignore
813
+
814
+ if image_features is not None:
815
+ assert self.config.image_token_id is not None
816
+ image_embeds = self.image_proj(image_features)
817
+ assert image_embeds.shape == inputs_embeds.shape, (image_embeds.shape, inputs_embeds.shape)
818
+ mask = input_ids == self.config.image_token_id
819
+ inputs_embeds[mask] = image_embeds[mask]
820
+
821
+ # embed positions
822
+ require_attn_mask = False
823
+ if not self.training or past_key_values is not None:
824
+ require_attn_mask = True
825
+ if seq_length_with_past > self.config.window_size + 1:
826
+ require_attn_mask = True
827
+
828
+ if require_attn_mask and attention_mask is None:
829
+ attention_mask = torch.ones(
830
+ (batch_size, seq_length_with_past), dtype=torch.bool, device=inputs_embeds.device
831
+ )
832
+
833
+ if attention_mask is not None:
834
+ attention_mask = self._prepare_decoder_attention_mask(
835
+ attention_mask,
836
+ (batch_size, seq_length),
837
+ inputs_embeds,
838
+ cache_position, # type: ignore
839
+ )
840
+
841
+ hidden_states = inputs_embeds
842
+
843
+ if use_cache and past_key_values is None:
844
+ past_key_values = DynamicCache(config=self.config)
845
+
846
+ # decoder layers
847
+ out = self.layers(
848
+ DecoderInput(
849
+ hidden_states,
850
+ attention_mask,
851
+ past_key_values,
852
+ output_hidden_states,
853
+ output_attentions,
854
+ self.gradient_checkpointing,
855
+ )
856
+ )
857
+ assert isinstance(out, DecoderOutput)
858
+ hidden_states = out.hidden_states
859
+ all_hidden_states = out.all_hidden_states
860
+ all_self_attns = out.all_self_attns
861
+
862
+ hidden_states = self.norm(hidden_states)
863
+
864
+ # add hidden states from the last decoder layer
865
+ if output_hidden_states:
866
+ assert all_hidden_states is not None
867
+ all_hidden_states += (hidden_states,)
868
+
869
+ return BaseModelOutputWithPast(
870
+ last_hidden_state=hidden_states,
871
+ past_key_values=past_key_values,
872
+ hidden_states=all_hidden_states,
873
+ attentions=all_self_attns,
874
+ )
875
+
876
+
877
+ class Plamo3ForCausalLM(Plamo3PreTrainedModel, GenerationMixin): # type: ignore
878
+ # Without this, the model cannot be loaded into a meta device.
879
+ # Relevant code:
880
+ # https://github.com/huggingface/transformers/blob/v4.44.2/src/transformers/modeling_utils.py#L4376-L4381
881
+ # https://github.com/huggingface/transformers/blob/v4.44.2/src/transformers/modeling_utils.py#L356
882
+ # https://github.com/pytorch/pytorch/blob/v2.4.1/torch/nn/modules/module.py#L2068
883
+ _supports_param_buffer_assignment = False
884
+
885
+ def __init__(self, config: Plamo3Config) -> None:
886
+ super().__init__(config)
887
+ self.model = Plamo3Model(config)
888
+
889
+ self.vocab_size = config.vocab_size
890
+ vocab_size = ((self.vocab_size + 15) // 16) * 16
891
+ self.lm_head: torch.nn.Module = nn.Linear(config.hidden_size, vocab_size, bias=False)
892
+ if self.config.tie_word_embeddings:
893
+ self._tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
894
+
895
+ # Initialize weights and apply final processing
896
+ self.post_init()
897
+
898
+ def get_input_embeddings(self) -> torch.nn.Embedding:
899
+ return self.model.embed_tokens
900
+
901
+ def set_input_embeddings(self, value: torch.nn.Embedding) -> None:
902
+ self.model.embed_tokens = value
903
+
904
+ def get_output_embeddings(self) -> torch.nn.Module:
905
+ return self.lm_head
906
+
907
+ def set_output_embeddings(self, new_embeddings: torch.nn.Module) -> None:
908
+ self.lm_head = new_embeddings
909
+
910
+ def set_decoder(self, decoder: Plamo3Model) -> None:
911
+ self.model = decoder
912
+
913
+ def get_decoder(self) -> Plamo3Model:
914
+ return self.model
915
+
916
+ def forward( # type: ignore
917
+ self,
918
+ input_ids: Optional[torch.LongTensor] = None,
919
+ attention_mask: Optional[torch.Tensor] = None,
920
+ position_ids: Optional[torch.Tensor] = None,
921
+ past_key_values: Optional[DynamicCache] = None,
922
+ inputs_embeds: Optional[torch.FloatTensor] = None,
923
+ image_features: Optional[torch.Tensor] = None,
924
+ labels: Optional[torch.LongTensor] = None,
925
+ use_cache: Optional[bool] = None,
926
+ output_attentions: Optional[bool] = None,
927
+ output_hidden_states: Optional[bool] = None,
928
+ cache_position: Optional[torch.LongTensor] = None,
929
+ logits_to_keep: int | torch.Tensor = 0,
930
+ **kwargs: Any,
931
+ ) -> CausalLMOutputWithPast:
932
+ r"""
933
+ Args:
934
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
935
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
936
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
937
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
938
+
939
+ """
940
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
941
+ output_hidden_states = (
942
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
943
+ )
944
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
945
+ outputs = self.model(
946
+ input_ids=input_ids,
947
+ attention_mask=attention_mask,
948
+ position_ids=position_ids,
949
+ past_key_values=past_key_values,
950
+ inputs_embeds=inputs_embeds,
951
+ image_features=image_features,
952
+ use_cache=use_cache,
953
+ output_attentions=output_attentions,
954
+ output_hidden_states=output_hidden_states,
955
+ cache_position=cache_position,
956
+ **kwargs,
957
+ )
958
+
959
+ hidden_states = outputs[0]
960
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
961
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
962
+ logits = logits[..., : self.vocab_size]
963
+
964
+ loss = None
965
+ if labels is not None:
966
+ if len(kwargs) > 0 and set(kwargs.keys()) != set(["ignore_index"]):
967
+ warnings.warn(
968
+ f"The following kwargs may not be supported: {', '.join(kwargs.keys())}. ",
969
+ stacklevel=2,
970
+ )
971
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
972
+
973
+ return CausalLMOutputWithPast(
974
+ loss=loss,
975
+ logits=logits,
976
+ past_key_values=outputs.past_key_values,
977
+ hidden_states=outputs.hidden_states,
978
+ attentions=outputs.attentions,
979
+ )
980
+
981
+ def prepare_inputs_for_generation(
982
+ self,
983
+ input_ids: torch.Tensor,
984
+ past_key_values: Optional[DynamicCache] = None,
985
+ attention_mask: Optional[torch.Tensor] = None,
986
+ inputs_embeds: Optional[torch.Tensor] = None,
987
+ image_features: Optional[torch.Tensor] = None,
988
+ **kwargs: Any,
989
+ ) -> Dict[str, Any]:
990
+ past_length = past_key_values.get_seq_length() if past_key_values is not None else 0
991
+ cache_position = kwargs.get("cache_position")
992
+ # Transformers 5.14 supplies positions; newer 5.x releases supply the pending length.
993
+ input_length = kwargs.get("next_sequence_length")
994
+ use_inputs_embeds = inputs_embeds is not None and kwargs.get("is_first_iteration", past_length == 0)
995
+ if input_length is None:
996
+ if cache_position is not None:
997
+ input_length = cache_position.shape[0]
998
+ elif attention_mask is not None:
999
+ input_length = attention_mask.shape[1] - past_length
1000
+ elif use_inputs_embeds:
1001
+ input_length = inputs_embeds.shape[1] - past_length
1002
+ elif input_ids.shape[1] > past_length:
1003
+ input_length = input_ids.shape[1] - past_length
1004
+ else:
1005
+ # The caller has already removed the cached prefix.
1006
+ input_length = input_ids.shape[1]
1007
+ if input_length <= 0:
1008
+ raise ValueError("Generation requires at least one input token not already present in the cache.")
1009
+
1010
+ if use_inputs_embeds:
1011
+ model_inputs: Dict[str, Any] = {"inputs_embeds": inputs_embeds[:, -input_length:, :]}
1012
+ else:
1013
+ model_inputs = {"input_ids": input_ids[:, -input_length:]}
1014
+ if image_features is not None:
1015
+ image_features = image_features[:, -input_length:, :]
1016
+
1017
+ position_ids = kwargs.get("position_ids", None)
1018
+ if attention_mask is not None and position_ids is None:
1019
+ # create position_ids on the fly for batch generation
1020
+ position_ids = attention_mask.long().cumsum(-1) - 1
1021
+ position_ids.masked_fill_(attention_mask == 0, 1)
1022
+ if position_ids is not None:
1023
+ position_ids = position_ids[:, -input_length:]
1024
+
1025
+ model_inputs.update(
1026
+ {
1027
+ "position_ids": position_ids,
1028
+ "cache_position": cache_position,
1029
+ "past_key_values": past_key_values,
1030
+ "use_cache": kwargs.get("use_cache"),
1031
+ "output_attentions": kwargs.get("output_attentions"),
1032
+ "output_hidden_states": kwargs.get("output_hidden_states"),
1033
+ "logits_to_keep": kwargs.get("logits_to_keep"),
1034
+ "attention_mask": attention_mask,
1035
+ "image_features": image_features,
1036
+ }
1037
+ )
1038
+ return model_inputs
1039
+
1040
+ @staticmethod
1041
+ def _reorder_cache(past_key_values: DynamicCache, beam_idx: torch.Tensor) -> DynamicCache:
1042
+ past_key_values.reorder_cache(beam_idx)
1043
+ return past_key_values
1044
+
1045
+
1046
+ class MLPImageProjector(nn.Module):
1047
+ def __init__(self, config: Plamo3Config) -> None:
1048
+ super().__init__()
1049
+ self.config = config
1050
+
1051
+ assert config.image_feature_size is not None # for typing
1052
+
1053
+ # nn.LayerNorm is not supported by PFVM, so use RMSNorm + Bias instead to approximate this.
1054
+ self.norm0 = Plamo3RMSNorm(config.image_feature_size, eps=config.rms_norm_eps)
1055
+ self.bias0 = Bias(config.image_feature_size)
1056
+
1057
+ # PFVM doesn't support Linear with bias, so add bias manually afterwards.
1058
+ self.linear1 = nn.Linear(config.image_feature_size, config.hidden_size, bias=False)
1059
+ self.bias1 = Bias(config.hidden_size)
1060
+ self.act1 = nn.GELU()
1061
+
1062
+ self.linear2 = nn.Linear(config.hidden_size, config.hidden_size, bias=False)
1063
+ self.bias2 = Bias(config.hidden_size)
1064
+
1065
+ def forward(
1066
+ self,
1067
+ hidden_states: torch.Tensor,
1068
+ ) -> torch.Tensor:
1069
+ hidden_states = self.norm0(hidden_states)
1070
+ hidden_states = self.bias0(hidden_states)
1071
+
1072
+ hidden_states = self.linear1(hidden_states)
1073
+ hidden_states = self.bias1(hidden_states)
1074
+ hidden_states = self.act1(hidden_states)
1075
+
1076
+ hidden_states = self.linear2(hidden_states)
1077
+ hidden_states = self.bias2(hidden_states)
1078
+
1079
+ return hidden_states
1080
+
1081
+
1082
+ class Bias(nn.Module):
1083
+ def __init__(self, num_features: int) -> None:
1084
+ super().__init__()
1085
+ self._bias = nn.Parameter(torch.zeros((num_features,)))
1086
+
1087
+ def forward(
1088
+ self,
1089
+ x: torch.Tensor,
1090
+ ) -> torch.Tensor:
1091
+ return x + self._bias
special_tokens_map.json ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": {
3
+ "content": "<|plamo:bos|>",
4
+ "lstrip": false,
5
+ "normalized": false,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "eos_token": {
10
+ "content": "<|plamo:bos|>",
11
+ "lstrip": false,
12
+ "normalized": false,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "pad_token": {
17
+ "content": "<|plamo:pad|>",
18
+ "lstrip": false,
19
+ "normalized": false,
20
+ "rstrip": false,
21
+ "single_word": false
22
+ },
23
+ "unk_token": {
24
+ "content": "<|plamo:unk|>",
25
+ "lstrip": false,
26
+ "normalized": false,
27
+ "rstrip": false,
28
+ "single_word": false
29
+ }
30
+ }
tokenization_plamo.py ADDED
@@ -0,0 +1,486 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import math
3
+ import os
4
+ import re
5
+ from shutil import copyfile
6
+ from typing import Any
7
+
8
+ import numpy as np
9
+
10
+ # NOTE: numba does not support type hints for njit: https://github.com/python/mypy/issues/16149
11
+ from numba import njit # type: ignore[attr-defined]
12
+ from numba.core import types # type: ignore[import-untyped]
13
+ from numba.typed import Dict
14
+ from transformers.tokenization_utils import PreTrainedTokenizer
15
+ from transformers.utils import logging
16
+
17
+ VOCAB_FILES_NAMES = {"vocab_file": "tokenizer.jsonl"}
18
+ logger = logging.get_logger(__name__)
19
+
20
+ INVALID_SCORE = -20000000
21
+ UNKNOWN_SCORE = -10000000
22
+
23
+ TABLE_PIECE_LENGTH = 0
24
+ TABLE_TOKEN_ID = 1
25
+ TABLE_SCORE = 2
26
+ TABLE_PIECE_ID = 3
27
+
28
+ PATH_TOKEN_LENGTH = 0
29
+ PATH_TOKEN_ID = 1
30
+ PATH_NUM_TOKENS = 2
31
+
32
+ # In Unicode, the character U+EE00 is a private use character that is not assigned to any specific
33
+ # character. This is internally used as a boundary character in tokenization.
34
+ BOUNDARY_CHAR = "\uee00"
35
+ BOUNDARY_TOKEN_ID = 10000000
36
+
37
+
38
+ class AhoCorasick:
39
+ def __init__(self) -> None:
40
+ # List of tokens in the vocabulary.
41
+ self._tokens: list[str]
42
+
43
+ # A mapping from a byte code point to a token ID, used for byte fallback.
44
+ self._bytes: np.ndarray
45
+
46
+ # A mapping from a suffix's piece code to a suffix ID.
47
+ #
48
+ # Typically, the Aho-Corasick algorithm builds a Trie and adds suffix links between nodes
49
+ # of the Trie. In this implementation, a suffix ID corresponds to a node in the trie, and
50
+ # a piece code to an edge (in other words, a pair of a node and the next character).
51
+ #
52
+ # A piece code is a 64-bit integer:
53
+ # - The upper 32 bits store the Unicode code point of the first character.
54
+ # - The lower 32 bits store the suffix ID of the remaining suffix.
55
+ #
56
+ # A suffix ID is an integer indicating the starting position in the _table.
57
+ self._to_suffix_id: dict[np.int64, np.int32] # numba.typed.Dict if jit is enabled
58
+
59
+ # Flattened table representing the Trie structure for the Aho-Corasick algorithm.
60
+ # It stores information including scores for each piece (prefix) within each suffix.
61
+ # It is flattened for memory efficiency and performance. Suffixes are stored in
62
+ # lexicographical order of their reversed strings, which improves memory access locality
63
+ # when exploring new characters starting from the string's end. Pieces within a suffix are
64
+ # stored in the decreasing order of their lengths.
65
+ #
66
+ # Each piece (a prefix fo the suffix) contains four pieces of information:
67
+ # - TABLE_PIECE_LENGTH: Length of the piece.
68
+ # - TABLE_TOKEN_ID: Token ID (or -1 if the piece is not a valid token).
69
+ # - TABLE_SCORE: Score (or INVALID_SCORE if the piece is not a valid token).
70
+ # - TABLE_PIECE_ID: Piece ID of the suffix.
71
+ #
72
+ # Each suffix also includes a sentinel row with a length of 1, a score of UNKNOWN_SCORE,
73
+ # and a token ID of -1. Sentinel rows are identified by the score being UNKNOWN_SCORE.
74
+ self._table: np.ndarray
75
+
76
+ # Regular expression matcher for identifying special tokens in the format <|plamo:*|>.
77
+ # Used to split text around special tokens during tokenization preprocessing.
78
+ self._sp_token_matcher: re.Pattern[str] | None = None
79
+
80
+ # Preprocessor to prevent boundary shifts in Unigram tokenization.
81
+ # The global DP in Unigram can create long lookahead dependencies, causing token boundaries
82
+ # to shift unexpectedly based on later context. While various sequences can trigger this,
83
+ # the most common culprits are long runs of spaces or repeated characters. This matcher
84
+ # finds sequences of two or more spaces or any character repeated four or more times, and
85
+ # forces hard splits immediately before and after each match, treating the span as its own
86
+ # token. By explicitly marking these boundaries, we eliminate most boundary jitter without
87
+ # trying to cover every rare case.
88
+ self._matcher: re.Pattern[str] | None = None
89
+
90
+ def build(
91
+ self,
92
+ vocab: list[Any],
93
+ *,
94
+ break_around_consecutive_spaces_threshold: int | None = None,
95
+ break_around_repeated_chars_threshold: int | None = None,
96
+ ) -> None:
97
+ """Build the Aho-Corasick data structure from vocabulary.
98
+
99
+ Args:
100
+ vocab: List of vocabulary entries, where each entry is [token, score, type, ...].
101
+ break_around_consecutive_spaces_threshold: Minimum number of consecutive spaces to trigger boundary splits.
102
+ If None, consecutive spaces won't trigger splits.
103
+ break_around_repeated_chars_threshold: Minimum number of repeated characters to trigger boundary splits.
104
+ If None, repeated characters won't trigger splits.
105
+ """
106
+ self._bytes = np.zeros(256, dtype=np.int32)
107
+ self._to_suffix_id = Dict.empty(key_type=types.int64, value_type=types.int32)
108
+
109
+ # Build suffix_to_score and token_to_token_id.
110
+ # The suffix_to_score dictionary maps a suffix to its score. It also includes all suffixes
111
+ # of the token for the Trie structure for the Aho-Corasick algorithm. If a suffix is not a
112
+ # valid token, its score is set to math.nan.
113
+ # The token_to_token_id dictionary maps a token to its token ID.
114
+ suffix_to_score: dict[str, float] = {}
115
+ token_to_token_id: dict[str, int] = {}
116
+ self._tokens = []
117
+ for token_id, row in list(enumerate(vocab)) + [(BOUNDARY_TOKEN_ID, [BOUNDARY_CHAR, 0, "CONTROL"])]:
118
+ assert isinstance(row[0], str), row
119
+ assert isinstance(row[1], (int, float)), row
120
+
121
+ token = str(row[0])
122
+ self._tokens.append(token)
123
+ token_to_token_id[token] = token_id
124
+
125
+ # Special handling for byte tokens.
126
+ if len(row) > 2 and row[2] == "BYTE":
127
+ assert len(token) == 6 and token.startswith("<0x") and token.endswith(">"), row[0]
128
+ self._bytes[int(row[0][3:5], 16)] = token_id
129
+ continue
130
+
131
+ suffix_to_score[token] = float(row[1])
132
+ # Ensure that all suffixes are included in suffix_to_score.
133
+ for i in range(1, len(token)):
134
+ suffix_to_score[token[i:]] = suffix_to_score.get(token[i:], math.nan)
135
+
136
+ # Ensure all byte tokens are set.
137
+ for i in range(256):
138
+ assert self._bytes[i] != 0, f"Byte token for <0x{i:02X}> is not set."
139
+
140
+ # Build a matcher for special tokens.
141
+ self._sp_token_matcher = re.compile(r"(<\|plamo:[^|\s]{,64}\|>)")
142
+
143
+ # Build matcher pattern to prevent boundary shifts.
144
+ patterns = []
145
+ if break_around_repeated_chars_threshold is not None:
146
+ patterns.append(f"(.)\\2{{{break_around_repeated_chars_threshold - 1},}}")
147
+ if break_around_consecutive_spaces_threshold is not None:
148
+ patterns.append(f" {{{break_around_consecutive_spaces_threshold},}}")
149
+ self._matcher = re.compile(f"({'|'.join(patterns)})") if patterns else None
150
+
151
+ # List suffixes in lexicographical order of their reversed strings.
152
+ suffixes = list(suffix_to_score.keys())
153
+ suffixes.append("")
154
+ suffixes.sort(key=lambda x: x[::-1])
155
+
156
+ # Build suffix_to_id, which is a mapping from a suffix to a suffix ID, and _to_suffix_id,
157
+ # which is a mapping from a piece code to a suffix ID.
158
+ suffix_to_id: dict[str, int] = {}
159
+ num_pieces = 0
160
+ for s in suffixes:
161
+ suffix_to_id[s] = num_pieces
162
+ if s != "":
163
+ self._to_suffix_id[
164
+ ord(s[0]) << 32 | suffix_to_id[s[1:]] # type: ignore[index] # cast int to np.int64
165
+ ] = np.int32(num_pieces)
166
+ num_pieces += 1 + sum(s[:i] in suffix_to_score for i in range(1, len(s) + 1))
167
+ assert suffix_to_id[""] == 0, suffix_to_id[""]
168
+
169
+ # Build _table, which is a flattened table representing the Trie structure for the Aho-Corasick.
170
+ self._table = np.zeros((num_pieces, 4), dtype=np.int32)
171
+ i = 0
172
+ for suffix in suffixes:
173
+ # Add all prefixes of the suffix to the table.
174
+ for piece_length in range(len(suffix), 0, -1):
175
+ piece = suffix[:piece_length]
176
+ score = suffix_to_score.get(piece, None)
177
+ if score is None:
178
+ continue
179
+ self._table[i, TABLE_PIECE_LENGTH] = piece_length
180
+ self._table[i, TABLE_TOKEN_ID] = token_to_token_id.get(piece, -1)
181
+ self._table[i, TABLE_SCORE] = round(score * 1e4) if math.isfinite(score) else INVALID_SCORE
182
+ self._table[i, TABLE_PIECE_ID] = suffix_to_id[piece]
183
+ i += 1
184
+
185
+ # Add a sentinel row.
186
+ self._table[i, TABLE_PIECE_LENGTH] = 1
187
+ self._table[i, TABLE_TOKEN_ID] = -1
188
+ self._table[i, TABLE_SCORE] = UNKNOWN_SCORE
189
+ i += 1
190
+ assert i == num_pieces, (i, num_pieces)
191
+
192
+ @staticmethod
193
+ @njit # type: ignore[misc] # untyped decorator
194
+ def _encode(
195
+ to_suffix_id: dict[np.int64, np.int32], # numba.typed.Dict if jit is enabled
196
+ table: np.ndarray,
197
+ bytes: np.ndarray,
198
+ data: np.ndarray,
199
+ ) -> np.ndarray:
200
+ # Initialize scores array with a high value and set the score at the end to 0.
201
+ # This array keeps track of the minimum cost (best score) to encode from each position to the end.
202
+ scores = np.full((len(data) + 1,), 2**60, dtype=np.int64)
203
+ scores[-1] = 0
204
+
205
+ # Path array to store the best path information.
206
+ # The path array keeps track of token length, token ID, and number of tokens needed to encode.
207
+ path = np.zeros((len(data) + 1, 3), dtype=np.int32)
208
+
209
+ # Initialize suffix_id to 0, which represents the root of the Trie.
210
+ suffix_id = np.int32(0)
211
+
212
+ # Process the input data from the end to the beginning.
213
+ for i in range(len(data) - 1, -1, -1):
214
+ c: np.int32 = data[i]
215
+
216
+ # Find the next suffix ID by iterating the suffix IDs of prefixes of the current suffix.
217
+ # NOTE: If no suffix ID is found, suffix_id will be set to 0.
218
+ for p in range(suffix_id, len(table)):
219
+ suffix_id = to_suffix_id.get(np.int64(c) << 32 | table[p, TABLE_PIECE_ID], np.int32(0))
220
+ # If a next suffix ID is found or a sentinel row is reached, break the loop.
221
+ if suffix_id > 0 or table[p, TABLE_SCORE] == UNKNOWN_SCORE:
222
+ break
223
+
224
+ # Update the best path to the current position. If multiple paths have the same score,
225
+ # this chooses the longest prefix as the best path (table is sorted in the decreasing
226
+ # order of piece length).
227
+ for p in range(suffix_id, len(table)):
228
+ score = table[p, TABLE_SCORE]
229
+ if score > INVALID_SCORE:
230
+ piece_length = table[p, TABLE_PIECE_LENGTH]
231
+ s = scores[i + piece_length] - score
232
+ if s < scores[i]:
233
+ scores[i] = s
234
+ path[i, PATH_TOKEN_LENGTH] = piece_length
235
+ path[i, PATH_TOKEN_ID] = table[p, TABLE_TOKEN_ID]
236
+ path[i, PATH_NUM_TOKENS] = path[i + piece_length, PATH_NUM_TOKENS] + 1
237
+ if score == UNKNOWN_SCORE:
238
+ # Add number of bytes to represent `c` in UTF-8 (minus 1; 1 is already
239
+ # added above).
240
+ path[i, PATH_NUM_TOKENS] += (c >= 0x80) + (c >= 0x800) + (c >= 0x10000)
241
+
242
+ # If it reaches a sentinel row, break the loop.
243
+ if score == UNKNOWN_SCORE:
244
+ break
245
+
246
+ # Decode the best path from the beginning to get the token IDs.
247
+ pos = 0
248
+ token_ids = np.zeros(path[0, PATH_NUM_TOKENS], dtype=np.int32)
249
+ token_pos = 0
250
+ while pos < len(data):
251
+ if path[pos, PATH_TOKEN_ID] >= 0:
252
+ token_ids[token_pos] = path[pos, PATH_TOKEN_ID]
253
+ if token_ids[token_pos] != BOUNDARY_TOKEN_ID:
254
+ token_pos += 1
255
+ else:
256
+ # Fall back to byte tokens.
257
+ c = data[pos]
258
+ s = 1 + (c >= 0x80) + (c >= 0x800) + (c >= 0x10000)
259
+ # Add byte tokens representing UTF-8 bytes.
260
+ for i in range(s):
261
+ b = c if s == 1 else (0xF00 >> s) & 0xFF if i == 0 else 0x80
262
+ token_ids[token_pos] = bytes[b | ((c >> (s - i - 1) * 6) & 0x3F)]
263
+ token_pos += 1
264
+
265
+ # Ensure that pos should increase by at least 1.
266
+ assert path[pos, PATH_TOKEN_LENGTH] > 0, (pos, path[pos])
267
+ pos += path[pos, PATH_TOKEN_LENGTH]
268
+
269
+ return token_ids[:token_pos]
270
+
271
+ def encode(self, data: str) -> np.ndarray:
272
+ """Encodes a string into a sequence of token IDs."""
273
+ if self._sp_token_matcher is not None:
274
+ data = self._sp_token_matcher.sub(BOUNDARY_CHAR + "\\1" + BOUNDARY_CHAR, data)
275
+ if self._matcher is not None:
276
+ data = self._matcher.sub(BOUNDARY_CHAR + "\\1" + BOUNDARY_CHAR, data)
277
+ return np.asarray(
278
+ self._encode(
279
+ self._to_suffix_id,
280
+ self._table,
281
+ self._bytes,
282
+ # Convert a string into a numpy array of Unicode code points.
283
+ # NOTE: This skips UTF-32 BOM.
284
+ np.frombuffer(data.encode("utf-32"), dtype=np.int32)[1:],
285
+ )
286
+ )
287
+
288
+ def encode_as_tokens(self, data: str) -> list[str]:
289
+ """Encodes a string into a sequence of tokens."""
290
+ return [self._tokens[token_id] for token_id in self.encode(data)]
291
+
292
+
293
+ class Plamo3Tokenizer(PreTrainedTokenizer):
294
+ vocab_files_names = VOCAB_FILES_NAMES
295
+ model_input_names = ["input_ids", "attention_mask"]
296
+
297
+ _save_files = [
298
+ "tokenization_plamo.py",
299
+ "tokenizer.jsonl",
300
+ "tokenizer_config.json",
301
+ ]
302
+
303
+ def __init__(
304
+ self,
305
+ vocab_file: str,
306
+ unk_token: str = "<|plamo:unk|>",
307
+ bos_token: str = "<|plamo:bos|>",
308
+ eos_token: str = "<|plamo:eos|>",
309
+ pad_token: str = "<|plamo:pad|>",
310
+ cls_token: str | None = None,
311
+ sep_token: str | None = None,
312
+ mask_token: str | None = None,
313
+ clean_up_tokenization_spaces: bool = False,
314
+ break_around_consecutive_spaces_threshold: int | None = None,
315
+ break_around_repeated_chars_threshold: int | None = None,
316
+ **kwargs: Any,
317
+ ) -> None:
318
+ """Tokenizer for PLaMo.
319
+
320
+ Args:
321
+ vocab_file (str): Vocabrary file path.
322
+ unk_token (str): Unknown token.
323
+ bos_token (str): Beginning of sentence token.
324
+ eos_token (str): End of sentence token.
325
+ pad_token (str): Padding token.
326
+ cls_token (str):
327
+ Classification token, to extract a summary of an input sequence leveraging self-attention along the
328
+ full depth of the model.
329
+ sep_token (str): Separation token, to separate context and query in an input sequence.
330
+ mask_token (str): Mask token, to use when training a model with masked-language modeling.
331
+ clean_up_tokenization_spaces (bool): Whether or not to clean up the tokenization spaces.
332
+ break_around_consecutive_spaces_threshold (int, optional): Minimum number of consecutive spaces to trigger
333
+ boundary splits. If None, consecutive spaces won't trigger splits.
334
+ break_around_repeated_chars_threshold (int, optional): Minimum number of repeated characters to trigger
335
+ boundary splits. If None, repeated characters won't trigger splits.
336
+ """
337
+ if "add_bos_token" not in kwargs:
338
+ kwargs["add_bos_token"] = False
339
+ if "add_eos_token" not in kwargs:
340
+ kwargs["add_eos_token"] = False
341
+ with open(vocab_file, encoding="utf-8") as f:
342
+ self.data: list[Any] = [json.loads(line) for line in f]
343
+ self.vocab: dict[str, int] = {v[0]: i for i, v in enumerate(self.data)}
344
+ self.aho_corasick = AhoCorasick()
345
+ self.break_around_consecutive_spaces_threshold = break_around_consecutive_spaces_threshold
346
+ self.break_around_repeated_chars_threshold = break_around_repeated_chars_threshold
347
+ self.aho_corasick.build(
348
+ self.data,
349
+ break_around_consecutive_spaces_threshold=self.break_around_consecutive_spaces_threshold,
350
+ break_around_repeated_chars_threshold=self.break_around_repeated_chars_threshold,
351
+ )
352
+ self.vocab_file = vocab_file
353
+ self.add_bos_token = kwargs["add_bos_token"]
354
+ self.add_eos_token = kwargs["add_eos_token"]
355
+
356
+ super().__init__( # type: ignore[no-untyped-call]
357
+ vocab_file=vocab_file,
358
+ unk_token=unk_token,
359
+ bos_token=bos_token,
360
+ eos_token=eos_token,
361
+ pad_token=pad_token,
362
+ cls_token=cls_token,
363
+ sep_token=sep_token,
364
+ mask_token=mask_token,
365
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
366
+ break_around_consecutive_spaces_threshold=break_around_consecutive_spaces_threshold,
367
+ break_around_repeated_chars_threshold=break_around_repeated_chars_threshold,
368
+ **kwargs,
369
+ )
370
+
371
+ # the functions below are copied from hf transformers LlamaTokenizer's implementation to fix the behaviour of the tokenizer
372
+ # https://github.com/huggingface/transformers/blob/v4.30.2/src/transformers/models/llama/tokenization_llama.py
373
+
374
+ def __getstate__(self) -> dict[str, Any]:
375
+ state = self.__dict__.copy()
376
+ state["aho_corasick"] = None
377
+ return state
378
+
379
+ def __setstate__(self, d: dict[str, Any]) -> None:
380
+ self.__dict__ = d
381
+ self.aho_corasick = AhoCorasick()
382
+ self.aho_corasick.build(
383
+ self.data,
384
+ break_around_consecutive_spaces_threshold=self.break_around_consecutive_spaces_threshold,
385
+ break_around_repeated_chars_threshold=self.break_around_repeated_chars_threshold,
386
+ )
387
+
388
+ @property
389
+ def vocab_size(self) -> Any:
390
+ """Returns vocab size"""
391
+ return len(self.data)
392
+
393
+ def token_to_score(self, token: str) -> float | None:
394
+ """Returns score of the token"""
395
+ token_id = self.vocab.get(token, None)
396
+ return None if token_id is None else self.data[token_id][1]
397
+
398
+ def get_vocab(self) -> dict[str, int]:
399
+ """Returns vocab as a dict"""
400
+ vocab = self.vocab.copy()
401
+ vocab.update(self.added_tokens_encoder)
402
+ return vocab
403
+
404
+ def convert_tokens_to_string(self, tokens: list[str]) -> str:
405
+ """Converts a sequence of tokens (string) in a single string."""
406
+ return b"".join(
407
+ [bytes([int(t[3:5], 16)]) if t.startswith("<0x") else t.encode("utf-8") for t in tokens]
408
+ ).decode("utf-8", errors="replace")
409
+
410
+ def _tokenize(self, text: str, **kwargs: Any) -> list[str]:
411
+ """Returns a tokenized string."""
412
+ return self.aho_corasick.encode_as_tokens(text)
413
+
414
+ def _convert_token_to_id(self, token: str) -> int:
415
+ """Converts a token (str) in an id using the vocab."""
416
+ return self.vocab.get(token, 0)
417
+
418
+ def _convert_id_to_token(self, index: int) -> str:
419
+ """Converts an index (integer) in a token (str) using the vocab."""
420
+ return self.data[index][0] # type: ignore[no-any-return]
421
+
422
+ def build_inputs_with_special_tokens(
423
+ self, token_ids_0: list[int], token_ids_1: list[int] | None = None
424
+ ) -> list[int]:
425
+ bos_token_id = [self.bos_token_id] if self.add_bos_token else []
426
+ eos_token_id = [self.eos_token_id] if self.add_eos_token else []
427
+
428
+ output = bos_token_id + token_ids_0 + eos_token_id
429
+
430
+ if token_ids_1 is not None:
431
+ output = output + bos_token_id + token_ids_1 + eos_token_id
432
+
433
+ return output
434
+
435
+ def _save_pretrained(
436
+ self,
437
+ save_directory: str | os.PathLike[str],
438
+ file_names: tuple[str, ...],
439
+ legacy_format: bool | None = None,
440
+ filename_prefix: str | None = None,
441
+ ) -> tuple[str, ...]:
442
+ """Restore BOS/EOS flags before save_pretrained optionally uploads the files.
443
+
444
+ Transformers v5 omits these flags from tokenizer_config.json, but this
445
+ tokenizer needs them to preserve its behavior after saving and reloading.
446
+ """
447
+ saved_files = super()._save_pretrained(
448
+ save_directory,
449
+ file_names=file_names,
450
+ legacy_format=legacy_format,
451
+ filename_prefix=filename_prefix,
452
+ )
453
+ config_file = file_names[0]
454
+ with open(config_file, encoding="utf-8") as f:
455
+ tokenizer_config = json.load(f)
456
+ tokenizer_config.update(add_bos_token=self.add_bos_token, add_eos_token=self.add_eos_token)
457
+ with open(config_file, "w", encoding="utf-8") as f:
458
+ f.write(json.dumps(tokenizer_config, indent=2, sort_keys=True, ensure_ascii=False) + "\n")
459
+ return saved_files
460
+
461
+ def save_vocabulary(self, save_directory: str, filename_prefix: str | None = None) -> tuple[str]:
462
+ """
463
+ Save the vocabulary and special tokens file to a directory.
464
+
465
+ Args:
466
+ save_directory (`str`):
467
+ The directory in which to save the vocabulary.
468
+
469
+ Returns:
470
+ `Tuple(str)`: Paths to the files saved.
471
+ """
472
+ if not os.path.isdir(save_directory):
473
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
474
+ return ("",)
475
+ out_vocab_file = os.path.join(
476
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
477
+ )
478
+
479
+ if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
480
+ copyfile(self.vocab_file, out_vocab_file)
481
+ elif not os.path.isfile(self.vocab_file):
482
+ with open(out_vocab_file, "w") as f:
483
+ for token in self.data:
484
+ print(json.dumps(token, ensure_ascii=False), file=f)
485
+
486
+ return (out_vocab_file,)
tokenizer.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": true,
3
+ "add_eos_token": false,
4
+ "added_tokens_decoder": {
5
+ "0": {
6
+ "content": "<|plamo:unk|>",
7
+ "lstrip": false,
8
+ "normalized": false,
9
+ "rstrip": false,
10
+ "single_word": false,
11
+ "special": true
12
+ },
13
+ "1": {
14
+ "content": "<|plamo:bos|>",
15
+ "lstrip": false,
16
+ "normalized": false,
17
+ "rstrip": false,
18
+ "single_word": false,
19
+ "special": true
20
+ },
21
+ "16": {
22
+ "content": "<|plamo:tag|>",
23
+ "lstrip": false,
24
+ "normalized": false,
25
+ "rstrip": false,
26
+ "single_word": false,
27
+ "special": true
28
+ },
29
+ "2": {
30
+ "content": "<|plamo:eos|>",
31
+ "lstrip": false,
32
+ "normalized": false,
33
+ "rstrip": false,
34
+ "single_word": false,
35
+ "special": true
36
+ },
37
+ "3": {
38
+ "content": "<|plamo:pad|>",
39
+ "lstrip": false,
40
+ "normalized": false,
41
+ "rstrip": false,
42
+ "single_word": false,
43
+ "special": true
44
+ }
45
+ },
46
+ "auto_map": {
47
+ "AutoTokenizer": [
48
+ "tokenization_plamo.Plamo3Tokenizer",
49
+ null
50
+ ]
51
+ },
52
+ "bos_token": "<|plamo:bos|>",
53
+ "break_around_consecutive_spaces_threshold": 2,
54
+ "break_around_repeated_chars_threshold": 4,
55
+ "clean_up_tokenization_spaces": false,
56
+ "cls_token": null,
57
+ "eos_token": "<|plamo:bos|>",
58
+ "additional_special_tokens": [
59
+ "<|plamo:tag|>"
60
+ ],
61
+ "mask_token": null,
62
+ "model_max_length": 1000000000000000019884624838656,
63
+ "pad_token": "<|plamo:pad|>",
64
+ "padding_side": "left",
65
+ "sep_token": null,
66
+ "tokenizer_class": "Plamo3Tokenizer",
67
+ "unk_token": "<|plamo:unk|>"
68
+ }