melon1891 commited on
Commit
e817b87
·
verified ·
1 Parent(s): 9a72171

Initial release of shiori-bert-jp

Browse files
Files changed (6) hide show
  1. LICENSE +202 -0
  2. NOTICE +16 -0
  3. README.md +168 -0
  4. config.json +53 -0
  5. model.safetensors +3 -0
  6. shiori_infer.py +146 -0
LICENSE ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
NOTICE ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ shiori-bert-jp
2
+ Licensed under the Apache License, Version 2.0 (see LICENSE).
3
+
4
+ This model is a modified version of tohoku-nlp/bert-base-japanese-v3
5
+ (https://huggingface.co/tohoku-nlp/bert-base-japanese-v3), which is distributed
6
+ under the Apache License, Version 2.0. The base model repository provides no NOTICE file.
7
+
8
+ Modifications: the base BERT encoder was fine-tuned for Japanese dialogue
9
+ topic-boundary classification, and a new 3-class linear classification head
10
+ (C0 / C1 / C2+) on the [CLS] hidden state was added. The weights were converted
11
+ from a PyTorch checkpoint to safetensors. The base model's pretraining heads are
12
+ not included.
13
+
14
+ Runtime dependencies (not bundled): fugashi (MIT; bundles MeCab, BSD-3-Clause)
15
+ and unidic-lite (code MIT or WTFPL; UniDic 2.1.2 dictionary, BSD license,
16
+ copyright the UniDic Consortium).
README.md ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ language:
4
+ - ja
5
+ base_model: tohoku-nlp/bert-base-japanese-v3
6
+ pipeline_tag: text-classification
7
+ library_name: pytorch
8
+ tags:
9
+ - bert
10
+ - japanese
11
+ - dialogue
12
+ - topic-segmentation
13
+ - event-segmentation
14
+ - knowledge-distillation
15
+ ---
16
+
17
+ # shiori-bert-jp
18
+
19
+ **English summary.** shiori-bert-jp is a small Japanese BERT classifier that finds topic boundaries in a chat
20
+ conversation. For each boundary between two sentences it looks at the 2 sentences before and the 2 after
21
+ (with speaker tags) and outputs 3 classes: C0 (no boundary), C1 (side topic inside the current topic) and C2+
22
+ (new topic). It was distilled from LLM teacher labels (Claude Opus 5.5 given human-labelled examples) on 400
23
+ synthetic Japanese chats generated with Claude Sonnet 5.5. On 8 fresh human-labelled conversations
24
+ (287 boundaries) the 5-seed mean F1 of this configuration is 0.770 (this released seed: 0.790), on par with its
25
+ LLM teacher (0.769), at about 45 ms per boundary on a desktop CPU. The training data is not released.
26
+ It is a non-generative classifier for research and hobby use. Load it with the bundled `shiori_infer.py`
27
+ (it is **not** loadable with `AutoModelForSequenceClassification`).
28
+
29
+ > Not to be confused with cl-nagoya/shioriha (shioriha-large-pt / shioriha-large-reranker), which are unrelated models.
30
+
31
+ ## 何をするモデルか
32
+
33
+ 日本語の雑談で、文と文の間 (境界) ごとに「ここで話の区切りがあるか」を判定する分類器です。
34
+
35
+ - 入力: 境界の前の 2 文と後の 2 文。各文に話し手の札を付けます (`利用者:…`、`相棒:…`、コロンは全角)。
36
+ - 出力: 3 クラスの確率 (C0 / C1 / C2+)。
37
+ - 判定は 2 段です。
38
+ - **細かい区切り** (piece boundary): P(C1) + P(C2+) ≥ 0.5
39
+ - **話題の区切り** (topic boundary): P(C2+) ≥ 0.5
40
+
41
+ 境界の 1 文先まで見て判断するので、会話の流れに合わせて文が 1 つ届くたびに、その直前の境界を判定する使い方ができます。
42
+
43
+ ## ラベル
44
+
45
+ | ラベル | 意味 |
46
+ |---|---|
47
+ | C0 | 区切りなし。同じやりとりの続き |
48
+ | C1 | 小さな区切り。いまの話題の中の脇道 |
49
+ | C2+ | 話題の区切り。新しい話題が始まる (会話がいったん閉じて新しく始まる場面を含む) |
50
+
51
+ 学習時のラベルは C0〜C3 の 4 段階でしたが、C3 (会話が閉じて新しく始まる) は数が少ないので C2 にまとめて 3 クラスにしています。
52
+
53
+ ## 使い方
54
+
55
+ 必要なもの: `torch`、`transformers`、`safetensors`、`huggingface_hub`、`fugashi`、`unidic-lite`
56
+ (動作確認: torch 2.6.0 / transformers 5.20.1 / safetensors 0.8.0 / fugashi 1.5.2 / unidic-lite 1.0.8)。
57
+
58
+ ```bash
59
+ pip install torch transformers safetensors huggingface_hub fugashi unidic-lite
60
+ ```
61
+
62
+ トークナイザと BERT の設定はベースモデル (`tohoku-nlp/bert-base-japanese-v3`) から読み、学習済みの重みとヘッドは
63
+ このリポジトリの `model.safetensors` から読みます。読み込みは同梱の `shiori_infer.py` で行います。
64
+
65
+ ```python
66
+ from huggingface_hub import hf_hub_download
67
+ import importlib.util
68
+
69
+ repo = "melon1891/shiori-bert-jp"
70
+ path = hf_hub_download(repo, "shiori_infer.py")
71
+ spec = importlib.util.spec_from_file_location("shiori_infer", path)
72
+ shiori_infer = importlib.util.module_from_spec(spec)
73
+ spec.loader.exec_module(shiori_infer)
74
+
75
+ seg = shiori_infer.ShioriSegmenter(repo) # ローカルのフォルダを渡してもよい
76
+ conv = [
77
+ ("利用者", "今朝、駅まで走ったら汗だくになったよ。"),
78
+ ("相棒", "急いでたの?"),
79
+ ("利用者", "うん、目覚ましを止めて二度寝しちゃって。"),
80
+ ("相棒", "寝坊なんて珍しいね。"),
81
+ ("利用者", "そうだ、週末に図書館で借りた本がすごく面白かったんだ。"),
82
+ ("相棒", "どんな本?"),
83
+ ]
84
+ for r in seg.segment(conv):
85
+ print(r["index"], r["probs"], r["piece_boundary"], r["topic_boundary"])
86
+ ```
87
+
88
+ - `segment()` は 1 文ずつの `(話し手, 文)` のリストを受け取り、境界 i (i-1 番目と i 番目の文の間、i ≥ 1) ごとに
89
+ 確率と 2 段の判定を返します。
90
+ - 1 つの発話に複数の文がある場合は、`shiori_infer.split_sentences()` で文に分けてから渡してください
91
+ (学習データと同じ規則: 「。!?!?」と、その後に続く閉じ括弧で文が終わる)。
92
+ - 学習時の話し手の札は `利用者` と `相棒` の 2 つだけです。別の名前の話し手は
93
+ `speaker_map={"A": "利用者", "B": "相棒"}` のように置き換えて渡すのがおすすめです。
94
+ - 最大長は 256 トークンです。長すぎる場合は、前側は後ろ寄りの約 126 トークン、後側は残りの長さまで切り詰めます。
95
+ - `config.json` は transformers の設定ファイルではなく、このモデルの入力形式と判定規則をまとめたものです。
96
+ ヘッドは BERT の pooler で���なく [CLS] の最終層の隠れ状態に直接かかります (pooler の重みは含まれますが使いません)。
97
+
98
+ `python shiori_infer.py` で、上の 6 文の作例に対する判定を表示します。
99
+
100
+ ## 学習
101
+
102
+ - 方式: LLM の先生のラベルを小さな BERT (生徒) に写す、知識の蒸留です。
103
+ - 学習用の会話: Anthropic の Claude (Sonnet 5.5) で生成した、合成の日本語雑談 400 本 (14,744 境界)。
104
+ 同じ家で暮らす 2 人が 18〜22 ターンで 3〜4 個の日常の話題を話す形で、手がかり語 (「そういえば」など) のない
105
+ 話題の変わり目や、ターンの途中での話題の切り替えを意図的に含めています。
106
+ - ラベル: Claude Opus 5.5 が、人手でラベルを付けた会話を例として見たうえで、すべての境界に C0〜C3 を付けたもの。
107
+ - モデル: `tohoku-nlp/bert-base-japanese-v3` を fine-tune し、[CLS] の隠れ状態に 3 クラスの線形ヘッドを追加。
108
+ - 設定: 8 エポック、学習率 5e-5、バッチ 16、最大 256 トークン、クラスの重みは頻度の −0.5 乗。
109
+ 種 0〜4 の 5 つで学習し、このリポジトリはそのうち種 3 のモデルです。学習は RTX 2070 1 枚。
110
+ - **学習データ (会話・ラベル) は公開していません。**
111
+
112
+ ## 評価
113
+
114
+ 学習にも改良の判断にも使っていない、新しく生成した 8 会話 (287 境界) に、1 名の作業者が人手でラベルを付けた
115
+ 評価セットで、1 回だけ採点しました。指標は「区切りあり (C1 以上) / なし」の F 値 (F1) です。
116
+
117
+ | モデル | F 値 |
118
+ |---|---|
119
+ | **この構成 (Opus + 例を先生にした生徒) の 5 種平均** | **0.770** (種ごとの範囲 0.756〜0.790) |
120
+ | このリポジトリの種 (種 3、5 種の中で最高) | 0.790 |
121
+ | 先生: Claude Opus 5.5 + 人手ラベルの例 | 0.769 |
122
+ | 参考: Claude Sonnet 5.5 (例なし、zero-shot) | 0.736 |
123
+
124
+ - 主に見るべき値は 5 種の平均 0.770 です。公開している種 3 の 0.790 は種の揺れの上端にあたります。
125
+ - 評価セットが小さいため区間は広く、先生や Sonnet との差は偶然と区別できる大きさではありません。
126
+ 言えるのは「生徒が先生と同じ水準」までです。
127
+ - 速さ: CPU (AMD Ryzen 9 3900X、8 スレッド) で 1 境界あたり中央値 約 45 ms (同じ作りの生徒で測定)。
128
+
129
+ ## 限界
130
+
131
+ - **合成会話で学習。** 会話は LLM が書いた整った雑談で、実際の会話より言いよどみや脱線が少なめです。
132
+ 実会話、3 人以上の会話、雑談以外の分野では精度が下がる可能性があります。
133
+ - **人手ラベルは 1 名。** 評価の正解は 1 名の作業者のラベルです。
134
+ - **評価セットは 8 会話。** 数字の信頼区間は広いです。
135
+ - **日本語の 2 人の雑談のみ。** 話し手の札は `利用者` / `相棒` の 2 つでしか学習していません。
136
+ - **細かく切りすぎる傾向。** 人が 1 つの話題とみなす所を小さな脇道に分けたり、話題の区切りを細かい区切り (C1) と
137
+ して出したりしがちです。誤りの多くは位置ではなく、区切りの大きさ (粒度) の誤りです。
138
+
139
+ ## 想定する用途
140
+
141
+ - 対話システムでの研究・趣味の利用。たとえば会話ログを話題ごとにまとめる、記憶の単位を決める、など。
142
+ - 文章を生成しない分類器として使うことを想定しています。
143
+ - 想定外: 人の評価や判断の材料に使うこと、ここに書いた評価の数字を別の評価セットの代わりに使うこと。
144
+
145
+ ## Claude の出力についての注意
146
+
147
+ このモデルの学習に使った会話とラベルは、Anthropic の Claude で作成しました。このモデルやその出力を使う方は、
148
+ ご自身が利用するサービスの規約を守る責任があります。
149
+
150
+ ## ライセンスと帰属
151
+
152
+ - ライセンス: Apache License 2.0 (`LICENSE`)。帰属と変更点は `NOTICE` にあります。
153
+ - ベースモデル: [tohoku-nlp/bert-base-japanese-v3](https://huggingface.co/tohoku-nlp/bert-base-japanese-v3)
154
+ (Apache-2.0)。
155
+ - 変更点: ベースの BERT を日本語の会話の話題境界の分類に fine-tune し、[CLS] の隠れ状態に 3 クラス
156
+ (C0 / C1 / C2+) の線形ヘッドを追加しました。重みは PyTorch の checkpoint から safetensors に変換しています。
157
+ - 依存 (同梱していません): [fugashi](https://pypi.org/project/fugashi/) (MIT、同梱の MeCab は BSD-3-Clause)、
158
+ [unidic-lite](https://github.com/polm/unidic-lite) (コードは MIT または WTFPL、UniDic 2.1.2 の辞書は BSD)。
159
+
160
+ ## 引用
161
+
162
+ ```
163
+ 猫飼人. 「AI キャラクター向けイベントセグメント検出モデルを作って検証してみた」. 技術書典 21.
164
+ ```
165
+
166
+ ## 名前について
167
+
168
+ cl-nagoya/shioriha (shioriha-large-pt、shioriha-large-reranker) とは無関係の���デルです。名前が似ているので混同しないようご注意ください。
config.json ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "shiori-bert-jp",
3
+ "format_note": "Not a transformers auto-loadable config. Load with shiori_infer.py (CLS hidden state -> dropout -> linear head; the BERT pooler weights are stored but unused).",
4
+ "base_model": "tohoku-nlp/bert-base-japanese-v3",
5
+ "weights": "model.safetensors",
6
+ "state_dict_prefixes": {
7
+ "enc.": "BertModel encoder (fine-tuned from the base model)",
8
+ "head.": "Linear(768, 3) classification head applied to last_hidden_state[:, 0]"
9
+ },
10
+ "num_labels": 3,
11
+ "id2label": {
12
+ "0": "C0",
13
+ "1": "C1",
14
+ "2": "C2+"
15
+ },
16
+ "label_meanings": {
17
+ "C0": "No boundary: the same exchange continues.",
18
+ "C1": "Small boundary: a side topic / sub-topic inside the current topic.",
19
+ "C2+": "Topic boundary: a new topic starts (includes the conversation closing and restarting)."
20
+ },
21
+ "input_format": {
22
+ "unit": "sentence (a piece ending at one of 。!?!? plus any closing brackets, or at a newline)",
23
+ "context_sentences_before": 2,
24
+ "context_sentences_after": 2,
25
+ "speaker_tag_format": "{speaker}:{sentence} (full-width colon U+FF1A)",
26
+ "speaker_tags_seen_in_training": ["利用者", "相棒"],
27
+ "sentence_join": "",
28
+ "pair_encoding": "[CLS] left [SEP] right [SEP]; token_type_ids 0 for [CLS]+left+[SEP], 1 for right+[SEP]",
29
+ "truncation": "left side keeps its last (max_length - 3) // 2 tokens; right side keeps its first (max_length - 3 - len(left)) tokens",
30
+ "max_length": 256,
31
+ "unicode_normalization": "NFC"
32
+ },
33
+ "decision_rules": {
34
+ "piece_boundary": "P(C1) + P(C2+) >= 0.5",
35
+ "topic_boundary": "P(C2+) >= 0.5"
36
+ },
37
+ "training": {
38
+ "teacher": "LLM labels (Claude Opus 5.5 with human-labelled examples)",
39
+ "train_conversations": 400,
40
+ "epochs": 8,
41
+ "learning_rate": 5e-05,
42
+ "batch_size": 16,
43
+ "class_weights": "frequency ^ -0.5",
44
+ "seed": 3
45
+ },
46
+ "tested_with": {
47
+ "torch": "2.6.0",
48
+ "transformers": "5.20.1",
49
+ "safetensors": "0.8.0",
50
+ "fugashi": "1.5.2",
51
+ "unidic-lite": "1.0.8"
52
+ }
53
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0759feaaf388f68524108cb07489534f2ca58b721d89bfd5152ab2cf78e3d8f4
3
+ size 444861236
shiori_infer.py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Minimal inference for shiori-bert-jp (Japanese dialogue topic-boundary classifier).
2
+
3
+ The model scores every boundary between two consecutive sentences of a conversation:
4
+ C0 = no boundary, C1 = small boundary (side topic), C2+ = topic boundary.
5
+ Decision rules:
6
+ piece boundary : P(C1) + P(C2+) >= 0.5
7
+ topic boundary : P(C2+) >= 0.5
8
+
9
+ Requirements: torch, transformers, safetensors, huggingface_hub, fugashi, unidic-lite.
10
+ The base tokenizer/config come from the Hugging Face Hub (tohoku-nlp/bert-base-japanese-v3);
11
+ the fine-tuned encoder and the head come from model.safetensors in `model_dir`.
12
+
13
+ License: Apache-2.0.
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import json
18
+ import os
19
+ import unicodedata
20
+ from pathlib import Path
21
+
22
+ import torch
23
+ import torch.nn as nn
24
+
25
+ TAG_SEP = ":" # full-width colon
26
+ _TERM = "。!?!?" # 。!?!?
27
+ _CLOSE = "」』))】〉》\"'”’"
28
+
29
+
30
+ def split_sentences(text: str) -> list[str]:
31
+ """Split a turn into sentences the way the training data was split: a sentence ends after a run of
32
+ 。!?!? plus any closing brackets that follow it, at a newline, or at the end of the text."""
33
+ text = unicodedata.normalize("NFC", text)
34
+ out, cur, i, n = [], [], 0, len(text)
35
+ while i < n:
36
+ ch = text[i]
37
+ if ch in "\r\n":
38
+ out.append("".join(cur)); cur = []; i += 1; continue
39
+ cur.append(ch); i += 1
40
+ if ch in _TERM:
41
+ while i < n and text[i] in _TERM:
42
+ cur.append(text[i]); i += 1
43
+ while i < n and text[i] in _CLOSE:
44
+ cur.append(text[i]); i += 1
45
+ out.append("".join(cur)); cur = []
46
+ out.append("".join(cur))
47
+ return [s.strip() for s in out if s.strip()]
48
+
49
+
50
+ class ShioriSegModel(nn.Module):
51
+ """BERT encoder -> [CLS] hidden state -> dropout -> Linear(hidden, 3). The pooler is not used."""
52
+
53
+ def __init__(self, bert_config, num_labels: int):
54
+ super().__init__()
55
+ from transformers import AutoModel
56
+ self.enc = AutoModel.from_config(bert_config)
57
+ self.drop = nn.Dropout(0.1)
58
+ self.head = nn.Linear(bert_config.hidden_size, num_labels)
59
+
60
+ def forward(self, input_ids, token_type_ids, attention_mask):
61
+ h = self.enc(input_ids=input_ids, token_type_ids=token_type_ids,
62
+ attention_mask=attention_mask).last_hidden_state[:, 0]
63
+ return self.head(self.drop(h))
64
+
65
+
66
+ class ShioriSegmenter:
67
+ def __init__(self, model_dir: str | os.PathLike | None = None, device: str | None = None):
68
+ """model_dir: a local folder with config.json + model.safetensors, or a Hub repo id.
69
+ Defaults to the folder this file is in."""
70
+ from safetensors.torch import load_file
71
+ from transformers import AutoConfig, AutoTokenizer
72
+
73
+ d = Path(model_dir) if model_dir is not None else Path(__file__).resolve().parent
74
+ if not (d / "config.json").is_file():
75
+ if model_dir is None:
76
+ raise FileNotFoundError(f"config.json not found next to shiori_infer.py ({d}); pass model_dir")
77
+ from huggingface_hub import snapshot_download
78
+ d = Path(snapshot_download(str(model_dir), allow_patterns=["config.json", "model.safetensors"]))
79
+ self.cfg = json.loads((d / "config.json").read_text(encoding="utf-8"))
80
+ base = self.cfg["base_model"]
81
+ fmt = self.cfg["input_format"]
82
+ self.k_before = fmt["context_sentences_before"]
83
+ self.k_after = fmt["context_sentences_after"]
84
+ self.max_len = fmt["max_length"]
85
+ self.tok = AutoTokenizer.from_pretrained(base)
86
+ self.model = ShioriSegModel(AutoConfig.from_pretrained(base), self.cfg["num_labels"])
87
+ self.model.load_state_dict(load_file(str(d / self.cfg["weights"])), strict=True)
88
+ self.device = device or ("cuda" if torch.cuda.is_available() else "cpu")
89
+ self.model.to(self.device).eval()
90
+
91
+ def _encode(self, left: str, right: str):
92
+ half = (self.max_len - 3) // 2
93
+ li = self.tok.encode(left, add_special_tokens=False)[-half:] if left else []
94
+ ri = self.tok.encode(right, add_special_tokens=False)[:self.max_len - 3 - len(li)]
95
+ ids = [self.tok.cls_token_id] + li + [self.tok.sep_token_id] + ri + [self.tok.sep_token_id]
96
+ tt = [0] * (len(li) + 2) + [1] * (len(ri) + 1)
97
+ return ids, tt
98
+
99
+ @torch.no_grad()
100
+ def segment(self, utterances: list[tuple[str, str]], speaker_map: dict[str, str] | None = None,
101
+ batch_size: int = 64) -> list[dict]:
102
+ """utterances: [(speaker, sentence), ...], one sentence per item (see split_sentences).
103
+ The model was trained with the speaker tags 利用者 (user) and 相棒 (partner); pass
104
+ speaker_map to rename your speakers to those tags, e.g. {"A": "利用者", "B": "相棒"}.
105
+
106
+ Returns one dict per boundary i (between sentence i-1 and sentence i, i >= 1):
107
+ {"index": i, "probs": {"C0": p0, "C1": p1, "C2+": p2},
108
+ "piece_boundary": bool, "topic_boundary": bool}
109
+ """
110
+ smap = speaker_map or {}
111
+ s = [f"{smap.get(spk, spk)}{TAG_SEP}{unicodedata.normalize('NFC', txt)}" for spk, txt in utterances]
112
+ pairs = [(i, "".join(s[max(0, i - self.k_before):i]), "".join(s[i:i + self.k_after]))
113
+ for i in range(1, len(s))]
114
+ out = []
115
+ for b0 in range(0, len(pairs), batch_size):
116
+ chunk = pairs[b0:b0 + batch_size]
117
+ enc = [self._encode(l, r) for _, l, r in chunk]
118
+ mx = max(len(e[0]) for e in enc)
119
+ ids = torch.full((len(enc), mx), self.tok.pad_token_id, dtype=torch.long)
120
+ tt = torch.zeros((len(enc), mx), dtype=torch.long)
121
+ am = torch.zeros((len(enc), mx), dtype=torch.long)
122
+ for r, (a, t) in enumerate(enc):
123
+ ids[r, :len(a)] = torch.tensor(a); tt[r, :len(t)] = torch.tensor(t); am[r, :len(a)] = 1
124
+ logits = self.model(ids.to(self.device), tt.to(self.device), am.to(self.device))
125
+ P = torch.softmax(logits.float(), -1).cpu().tolist()
126
+ for (i, _, _), p in zip(chunk, P):
127
+ out.append({"index": i, "probs": {"C0": p[0], "C1": p[1], "C2+": p[2]},
128
+ "piece_boundary": p[1] + p[2] >= 0.5, "topic_boundary": p[2] >= 0.5})
129
+ return out
130
+
131
+
132
+ if __name__ == "__main__":
133
+ demo = [
134
+ ("利用者", "今朝、駅まで走ったら汗だくになったよ。"),
135
+ ("相棒", "急いでたの?"),
136
+ ("利用者", "うん、目覚ましを止めて二度寝しちゃって。"),
137
+ ("相棒", "寝坊なんて珍しいね。"),
138
+ ("利用者", "そうだ、週末に図書館で借りた本がすごく面白かったんだ。"),
139
+ ("相棒", "どんな本?"),
140
+ ]
141
+ seg = ShioriSegmenter()
142
+ for r in seg.segment(demo):
143
+ p = r["probs"]
144
+ mark = "TOPIC" if r["topic_boundary"] else ("piece" if r["piece_boundary"] else "-")
145
+ print(f"before #{r['index']}: C0={p['C0']:.3f} C1={p['C1']:.3f} C2+={p['C2+']:.3f} {mark} "
146
+ f"{demo[r['index']][1]}")