alea-institute commited on
Commit
d459062
·
verified ·
1 Parent(s): e0ddf90

Update README and config files - README.md

Browse files
Files changed (1) hide show
  1. README.md +226 -87
README.md CHANGED
@@ -44,81 +44,202 @@ This model is particularly useful for:
44
  - Feature extraction for downstream legal analysis tasks
45
  - Clustering documents by type, purpose, or content
46
 
47
- Document similarities from most similar to least similar:
48
 
49
- 1. Consumer Terms vs. Credit Agreement: 0.8092
50
- 2. Consumer Terms vs. Financial Memo: 0.7604
51
- 3. Court Complaint vs. Financial Memo: 0.7320
52
- 4. Credit Agreement vs. Financial Memo: 0.7303
53
- 5. Court Complaint vs. Credit Agreement: 0.6867
54
- 6. Court Complaint vs. Consumer Terms: 0.6824
55
 
56
- Note how documents of similar types (e.g., both contracts) show higher similarity despite different subject matter.
57
 
58
- The moderately sized architecture makes this model a good balance between the lighter 41M parameter kl3m-doc-pico-001 model and larger language models, offering improved representation quality while remaining efficient for production deployments.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59
 
60
  ## Usage
61
 
62
- The primary use case for this model is feature extraction for document embedding and downstream classification tasks. Here's how to use it:
 
 
 
 
63
 
64
  ```python
65
- from transformers import AutoModel, AutoTokenizer
66
- import torch
67
  import numpy as np
 
68
 
69
- # Load model and tokenizer
70
- tokenizer = AutoTokenizer.from_pretrained("alea-institute/kl3m-doc-nano-001")
71
- model = AutoModel.from_pretrained("alea-institute/kl3m-doc-nano-001")
72
 
73
- # Prepare diverse example texts from legal and financial domains
74
  texts = [
75
- # Example 1: Court Complaint
76
  "<|cls|> IN THE UNITED STATES DISTRICT COURT FOR THE EASTERN DISTRICT OF PENNSYLVANIA\n\nJOHN DOE,\nPlaintiff,\n\nvs.\n\nACME CORPORATION,\nDefendant.\n\nCIVIL ACTION NO. 21-12345\n\nCOMPLAINT\n\nPlaintiff John Doe, by and through his undersigned counsel, hereby files this Complaint against Defendant Acme Corporation, and in support thereof, alleges as follows: <|sep|>",
77
 
78
- # Example 2: Consumer Terms and Conditions
79
  "<|cls|> TERMS AND CONDITIONS\n\nLast Updated: April 10, 2025\n\nThese Terms and Conditions (\"Terms\") govern your access to and use of the Service. By accessing or using the Service, you agree to be bound by these Terms. If you do not agree to these Terms, you may not access or use the Service. These Terms constitute a legally binding agreement between you and the Company. <|sep|>",
80
 
81
- # Example 3: Credit Agreement
82
- "<|cls|> CREDIT AGREEMENT\n\nDated as of April 10, 2025\n\nAmong\n\nACME BORROWER INC.,\nas the Borrower,\n\nBANK OF FINANCE,\nas Administrative Agent,\n\nand\n\nTHE LENDERS PARTY HERETO\n\nThis CREDIT AGREEMENT (\"Agreement\") is entered into as of April 10, 2025, among ACME BORROWER INC., a Delaware corporation (the \"Borrower\"), each lender from time to time party hereto (collectively, the \"Lenders\"), and BANK OF FINANCE, as Administrative Agent. <|sep|>",
83
-
84
- # Example 4: Financial Memorandum
85
- "<|cls|> MEMORANDUM\n\nTO: Investment Committee\nFROM: John Smith, Chief Investment Officer\nDATE: April 10, 2025\nSUBJECT: Q2 2025 Investment Strategy\n\nThis memorandum outlines our proposed investment strategy for Q2 2025. Based on current market conditions and economic indicators, we recommend the following asset allocation adjustments to the portfolio. <|sep|>"
86
  ]
87
 
88
- # Get embeddings for text classification or similarity
89
- inputs = tokenizer(texts, padding=True, truncation=True, return_tensors="pt")
90
- outputs = model(**inputs)
91
-
92
- # Extract CLS token embeddings (for classification tasks)
93
- cls_embeddings = outputs.last_hidden_state[:, 0, :]
94
- print(f"CLS embeddings shape: {cls_embeddings.shape}") # Should be [4, 512]
95
-
96
- # Calculate similarity between documents
97
- def cosine_similarity(a, b):
98
- return torch.dot(a, b) / (torch.norm(a) * torch.norm(b))
99
-
100
- # Calculate and print similarities (sorted from highest to lowest)
101
- print("\nCosine similarities (from highest to lowest):")
102
- similarities = [
103
- ("Consumer Terms vs. Credit Agreement", cosine_similarity(cls_embeddings[1], cls_embeddings[2]).item()),
104
- ("Consumer Terms vs. Financial Memo", cosine_similarity(cls_embeddings[1], cls_embeddings[3]).item()),
105
- ("Court Complaint vs. Financial Memo", cosine_similarity(cls_embeddings[0], cls_embeddings[3]).item()),
106
- ("Credit Agreement vs. Financial Memo", cosine_similarity(cls_embeddings[2], cls_embeddings[3]).item()),
107
- ("Court Complaint vs. Credit Agreement", cosine_similarity(cls_embeddings[0], cls_embeddings[2]).item()),
108
- ("Court Complaint vs. Consumer Terms", cosine_similarity(cls_embeddings[0], cls_embeddings[1]).item())
109
- ]
110
-
111
- # Sort by similarity score (descending)
112
- similarities.sort(key=lambda x: x[1], reverse=True)
113
-
114
- # Print sorted similarities
115
- for desc, score in similarities:
116
- print(f"{desc}: {score:.4f}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
117
 
118
  # For document retrieval, you can index these embeddings in a vector database
119
  # such as FAISS, Pinecone, or Weaviate for efficient similarity search
120
  ```
121
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
122
  ## Training
123
 
124
  The model was trained on a diverse corpus of legal and financial documents, ensuring high-quality performance in these domains. It incorporates the following key aspects:
@@ -148,8 +269,9 @@ import torch
148
  tokenizer = AutoTokenizer.from_pretrained("alea-institute/kl3m-doc-nano-001")
149
  mlm_model = AutoModelForMaskedLM.from_pretrained("alea-institute/kl3m-doc-nano-001")
150
 
151
- # Example 1: Contract with masked entity type
152
- text1 = "<|cls|> This Credit Agreement is made and entered into as of January 1, 2025, by and between Acme Corporation, a Delaware <|mask|>, and First National Bank, as lender. <|sep|>"
 
153
  inputs1 = tokenizer(text1, return_tensors="pt")
154
  outputs1 = mlm_model(**inputs1)
155
 
@@ -158,20 +280,20 @@ masked_index1 = torch.where(inputs1.input_ids[0] == tokenizer.mask_token_id)[0].
158
  probs1 = outputs1.logits[0, masked_index1].softmax(dim=0)
159
  top_5_1 = torch.topk(probs1, 5)
160
 
161
- print("Credit Agreement Example - Top 5 predictions:")
162
  for i, (score, idx) in enumerate(zip(top_5_1.values, top_5_1.indices)):
163
  token = tokenizer.decode(idx).strip()
164
  print(f"{i+1}. {token} ({score.item():.4f})")
165
 
166
  # Output:
167
- # 1. Corp. (0.1706)
168
- # 2. C. (0.1694)
169
- # 3. Bank. (0.1556)
170
- # 4. Inc. (0.0596)
171
- # 5. U.S. (0.0491)
172
-
173
- # Example 2: Regulatory document with masked term
174
- text2 = "<|cls|> Pursuant to Section 13(a) of the <|mask|> Exchange Act of 1934, the undersigned hereby certifies that the quarterly report fully complies with the requirements. <|sep|>"
175
  inputs2 = tokenizer(text2, return_tensors="pt")
176
  outputs2 = mlm_model(**inputs2)
177
 
@@ -180,20 +302,20 @@ masked_index2 = torch.where(inputs2.input_ids[0] == tokenizer.mask_token_id)[0].
180
  probs2 = outputs2.logits[0, masked_index2].softmax(dim=0)
181
  top_5_2 = torch.topk(probs2, 5)
182
 
183
- print("\nRegulatory Example - Top 5 predictions:")
184
  for i, (score, idx) in enumerate(zip(top_5_2.values, top_5_2.indices)):
185
  token = tokenizer.decode(idx).strip()
186
  print(f"{i+1}. {token} ({score.item():.4f})")
187
 
188
  # Output:
189
- # 1. U.S. (0.2473)
190
- # 2. Trad (0.2095)
191
- # 3. Securities (0.1251)
192
- # 4. (0.0478)
193
- # 5. ## (0.0183)
194
-
195
- # Example 3: Corporate governance with masked term
196
- text3 = "<|cls|> The Board of Directors shall consist of not less than three nor more than fifteen <|mask|>, with the exact number to be fixed by resolution of the Board. <|sep|>"
197
  inputs3 = tokenizer(text3, return_tensors="pt")
198
  outputs3 = mlm_model(**inputs3)
199
 
@@ -202,40 +324,46 @@ masked_index3 = torch.where(inputs3.input_ids[0] == tokenizer.mask_token_id)[0].
202
  probs3 = outputs3.logits[0, masked_index3].softmax(dim=0)
203
  top_5_3 = torch.topk(probs3, 5)
204
 
205
- print("\nCorporate Governance Example - Top 5 predictions:")
206
  for i, (score, idx) in enumerate(zip(top_5_3.values, top_5_3.indices)):
207
  token = tokenizer.decode(idx).strip()
208
  print(f"{i+1}. {token} ({score.item():.4f})")
209
 
210
  # Output:
211
- # 1. (15) (0.6526)
212
- # 2. (10) (0.0732)
213
- # 3. (14) (0.0627)
214
- # 4. (5) (0.0296)
215
- # 5. (3) (0.0244)
216
  ```
217
 
218
- These examples show that the model can predict contextually appropriate tokens across different legal and financial domains:
 
 
219
 
220
- 1. In a credit agreement context, it correctly suggests entity suffixes like "Corp." and "Inc."
221
- 2. In a regulatory context, it suggests appropriate terms like "Securities" and "U.S."
222
- 3. In corporate governance documents, it accurately predicts numeric parenthetical references like "(15)" that are common in bylaws and similar documents
223
 
224
  For applications primarily focused on masked language modeling, you may still want to consider models specifically optimized for that task.
225
 
226
  ## Special Tokens
227
 
228
- This model uses custom special tokens which must be used explicitly:
229
 
230
- - CLS token: `<|cls|>` (ID: 5) - Should be added at the beginning of input text
231
- - SEP token: `<|sep|>` (ID: 4) - Should be added at the end of input text
232
  - PAD token: `<|pad|>` (ID: 2) - Used for padding sequences to a uniform length
233
  - BOS token: `<|start|>` (ID: 0) - Beginning of sequence
234
  - EOS token: `<|end|>` (ID: 1) - End of sequence
235
  - UNK token: `<|unk|>` (ID: 3) - Unknown token
236
  - MASK token: `<|mask|>` (ID: 6) - Used for masked language modeling tasks
237
 
238
- For best results, you should **explicitly add** the CLS and SEP tokens to your input text, as shown in the examples above. The CLS token embedding is particularly important as it's commonly used for classification tasks.
 
 
 
 
239
 
240
  ## Limitations
241
 
@@ -250,7 +378,7 @@ While providing a good balance between size and performance, this model has some
250
  ## References
251
 
252
  - [KL3M Tokenizers: A Family of Domain-Specific and Character-Level Tokenizers for Legal, Financial, and Preprocessing Applications](https://arxiv.org/abs/2503.17247)
253
- - [The KL3M Data Project: Copyright-Clean Training Resources for Large Language Models]() (Forthcoming)
254
 
255
  ## Citation
256
 
@@ -267,6 +395,17 @@ If you use this model in your research, please cite:
267
  }
268
  ```
269
 
 
 
 
 
 
 
 
 
 
 
 
270
  ## License
271
 
272
  This model is licensed under [CC-BY 4.0](https://creativecommons.org/licenses/by/4.0/).
 
44
  - Feature extraction for downstream legal analysis tasks
45
  - Clustering documents by type, purpose, or content
46
 
47
+ The moderately sized architecture makes this model a good balance between the lighter 41M parameter kl3m-doc-pico-001 model and larger language models, offering improved representation quality while remaining efficient for production deployments.
48
 
49
+ ## Standard Test Examples
 
 
 
 
 
50
 
51
+ Using our standardized test examples for comparing embedding models:
52
 
53
+ ### Fill-Mask Results
54
+
55
+ 1. **Contract Clause Heading**:
56
+ `"<|cls|> 8. REPRESENTATIONS AND<|mask|>. Each party hereby represents and warrants to the other party as of the date hereof as follows: <|sep|>"`
57
+
58
+ Top 5 predictions:
59
+ 1. WARRANTIES (0.9271)
60
+ 2. Warranties (0.0191)
61
+ 3. REPRESENTATIONS (0.0156)
62
+ 4. warrants (0.0123)
63
+ 5. COVENANTS (0.0118)
64
+
65
+ Note: This model shows extremely strong performance on contract-specific language, predicting "WARRANTIES" with over 92% confidence.
66
+
67
+ 2. **Defined Term Example**:
68
+ `"<|cls|> \"Effective<|mask|>\" means the date on which all conditions precedent set forth in Article V are satisfied or waived by the Administrative Agent. <|sep|>"`
69
+
70
+ Top 5 predictions:
71
+ 1. Date (0.9601)
72
+ 2. Time (0.0211)
73
+ 3. date (0.0099)
74
+ 4. Dates (0.0034)
75
+ 5. Day (0.0006)
76
+
77
+ 3. **Regulation Example**:
78
+ `"<|cls|> All transactions shall comply with the requirements set forth in the Truth in<|mask|> Act and its implementing Regulation Z. <|sep|>"`
79
+
80
+ Top 5 predictions:
81
+ 1. Lending (0.9075)
82
+ 2. the (0.0114)
83
+ 3. Reinvestment (0.0083)
84
+ 4. Disclosure (0.0036)
85
+ 5. Credit (0.0026)
86
+
87
+ Despite being designed primarily for feature extraction rather than masked language modeling, this model demonstrates excellent performance in predicting domain-specific terminology with high confidence.
88
+
89
+ ### Document Similarity Results
90
+
91
+ Using the standardized document examples for embeddings:
92
+
93
+ | Document Pair | Cosine Similarity (CLS token) | Cosine Similarity (Mean pooling) |
94
+ |---------------|-------------------------------|----------------------------------|
95
+ | Court Complaint vs. Consumer Terms | 0.682 | 0.721 |
96
+ | Court Complaint vs. Credit Agreement | 0.687 | 0.770 |
97
+ | Consumer Terms vs. Credit Agreement | 0.809 | 0.711 |
98
+
99
+ The nano-sized model captures document similarities effectively with both CLS token and mean pooling strategies. With CLS tokens, it shows higher similarity between Consumer Terms and Credit Agreements (0.809), while with mean pooling, the highest similarity is observed between Court Complaints and Credit Agreements (0.770). This suggests the pooling strategy can significantly impact similarity measurements in this model with its moderate hidden size (512).
100
 
101
  ## Usage
102
 
103
+ The primary use case for this model is feature extraction for document embedding and downstream classification tasks.
104
+
105
+ ### Feature Extraction using Pipeline API
106
+
107
+ The recommended way to use this model is through the Hugging Face pipeline API:
108
 
109
  ```python
110
+ from transformers import pipeline
 
111
  import numpy as np
112
+ from sklearn.metrics.pairwise import cosine_similarity
113
 
114
+ # Load the feature-extraction pipeline
115
+ extractor = pipeline('feature-extraction', model="alea-institute/kl3m-doc-nano-001", return_tensors=True)
 
116
 
117
+ # Example legal documents
118
  texts = [
119
+ # Court Complaint
120
  "<|cls|> IN THE UNITED STATES DISTRICT COURT FOR THE EASTERN DISTRICT OF PENNSYLVANIA\n\nJOHN DOE,\nPlaintiff,\n\nvs.\n\nACME CORPORATION,\nDefendant.\n\nCIVIL ACTION NO. 21-12345\n\nCOMPLAINT\n\nPlaintiff John Doe, by and through his undersigned counsel, hereby files this Complaint against Defendant Acme Corporation, and in support thereof, alleges as follows: <|sep|>",
121
 
122
+ # Consumer Terms
123
  "<|cls|> TERMS AND CONDITIONS\n\nLast Updated: April 10, 2025\n\nThese Terms and Conditions (\"Terms\") govern your access to and use of the Service. By accessing or using the Service, you agree to be bound by these Terms. If you do not agree to these Terms, you may not access or use the Service. These Terms constitute a legally binding agreement between you and the Company. <|sep|>",
124
 
125
+ # Credit Agreement
126
+ "<|cls|> CREDIT AGREEMENT\n\nDated as of April 10, 2025\n\nAmong\n\nACME BORROWER INC.,\nas the Borrower,\n\nBANK OF FINANCE,\nas Administrative Agent,\n\nand\n\nTHE LENDERS PARTY HERETO\n\nThis CREDIT AGREEMENT (\"Agreement\") is entered into as of April 10, 2025, among ACME BORROWER INC., a Delaware corporation (the \"Borrower\"), each lender from time to time party hereto (collectively, the \"Lenders\"), and BANK OF FINANCE, as Administrative Agent. <|sep|>"
 
 
 
127
  ]
128
 
129
+ # Strategy 1: CLS token embeddings
130
+ cls_embeddings = []
131
+ for text in texts:
132
+ features = extractor(text)
133
+ # Get the CLS token (first token) embedding
134
+ features_array = features[0].numpy() if hasattr(features[0], 'numpy') else features[0]
135
+ cls_embedding = features_array[0]
136
+ cls_embeddings.append(cls_embedding)
137
+
138
+ # Calculate similarity between documents using CLS tokens
139
+ cls_similarity = cosine_similarity(np.vstack(cls_embeddings))
140
+ print("\nDocument similarity (CLS token):")
141
+ print(np.round(cls_similarity, 3))
142
+ # Output:
143
+ # [[1. 0.682 0.687]
144
+ # [0.682 1. 0.809]
145
+ # [0.687 0.809 1. ]]
146
+
147
+ # Strategy 2: Mean pooling
148
+ mean_embeddings = []
149
+ for text in texts:
150
+ features = extractor(text)
151
+ # Average over all tokens
152
+ features_array = features[0].numpy() if hasattr(features[0], 'numpy') else features[0]
153
+ mean_embedding = np.mean(features_array, axis=0)
154
+ mean_embeddings.append(mean_embedding)
155
+
156
+ # Calculate similarity using mean pooling
157
+ mean_similarity = cosine_similarity(np.vstack(mean_embeddings))
158
+ print("\nDocument similarity (Mean pooling):")
159
+ print(np.round(mean_similarity, 3))
160
+ # Output:
161
+ # [[1. 0.721 0.77 ]
162
+ # [0.721 1. 0.711]
163
+ # [0.77 0.711 1. ]]
164
+
165
+ # Print pairwise similarities
166
+ doc_names = ["Court Complaint", "Consumer Terms", "Credit Agreement"]
167
+ print("\nPairwise similarities:")
168
+ for i in range(len(doc_names)):
169
+ for j in range(i+1, len(doc_names)):
170
+ print(f"{doc_names[i]} vs. {doc_names[j]}:")
171
+ print(f" - CLS token: {cls_similarity[i, j]:.4f}")
172
+ print(f" - Mean pooling: {mean_similarity[i, j]:.4f}")
173
 
174
  # For document retrieval, you can index these embeddings in a vector database
175
  # such as FAISS, Pinecone, or Weaviate for efficient similarity search
176
  ```
177
 
178
+ ### Masked Language Modeling
179
+
180
+ While primarily designed for feature extraction, the model also supports masked language modeling:
181
+
182
+ ```python
183
+ from transformers import pipeline
184
+
185
+ # Load the fill-mask pipeline
186
+ fill_mask = pipeline('fill-mask', model="alea-institute/kl3m-doc-nano-001")
187
+
188
+ # Example text with mask token
189
+ # Note the mask token placement - directly adjacent to "AND" without space
190
+ text = "<|cls|> 8. REPRESENTATIONS AND<|mask|>. Each party hereby represents and warrants to the other party as of the date hereof as follows: <|sep|>"
191
+ results = fill_mask(text)
192
+
193
+ # Display predictions
194
+ print("Top predictions:")
195
+ for result in results:
196
+ print(f"- {result['token_str']} (score: {result['score']:.4f})")
197
+
198
+ # Output:
199
+ # Top predictions:
200
+ # - WARRANTIES (score: 0.9271)
201
+ # - Warranties (score: 0.0191)
202
+ # - REPRESENTATIONS (score: 0.0156)
203
+ # - warrants (score: 0.0123)
204
+ # - COVENANTS (score: 0.0118)
205
+ ```
206
+
207
+ Here are some additional examples:
208
+
209
+ ```python
210
+ # Example 2: Defined term
211
+ text2 = "<|cls|> \"Effective<|mask|>\" means the date on which all conditions precedent set forth in Article V are satisfied or waived by the Administrative Agent. <|sep|>"
212
+ results2 = fill_mask(text2)
213
+
214
+ print("\nDefined Term Example - Top 5 predictions:")
215
+ for i, result in enumerate(results2[:5]):
216
+ print(f"{i+1}. {result['token_str']} ({result['score']:.4f})")
217
+
218
+ # Output:
219
+ # Defined Term Example - Top 5 predictions:
220
+ # 1. Date (0.9601)
221
+ # 2. Time (0.0211)
222
+ # 3. date (0.0099)
223
+ # 4. Dates (0.0034)
224
+ # 5. Day (0.0006)
225
+
226
+ # Example 3: Regulatory context
227
+ text3 = "<|cls|> All transactions shall comply with the requirements set forth in the Truth in<|mask|> Act and its implementing Regulation Z. <|sep|>"
228
+ results3 = fill_mask(text3)
229
+
230
+ print("\nRegulatory Example - Top 5 predictions:")
231
+ for i, result in enumerate(results3[:5]):
232
+ print(f"{i+1}. {result['token_str']} ({result['score']:.4f})")
233
+
234
+ # Output:
235
+ # Regulatory Example - Top 5 predictions:
236
+ # 1. Lending (0.9075)
237
+ # 2. the (0.0114)
238
+ # 3. Reinvestment (0.0083)
239
+ # 4. Disclosure (0.0036)
240
+ # 5. Credit (0.0026)
241
+ ```
242
+
243
  ## Training
244
 
245
  The model was trained on a diverse corpus of legal and financial documents, ensuring high-quality performance in these domains. It incorporates the following key aspects:
 
269
  tokenizer = AutoTokenizer.from_pretrained("alea-institute/kl3m-doc-nano-001")
270
  mlm_model = AutoModelForMaskedLM.from_pretrained("alea-institute/kl3m-doc-nano-001")
271
 
272
+ # Example 1: Contract clause with mask token immediately after word (no space)
273
+ # Note the placement - directly after "AND" without a space
274
+ text1 = "<|cls|> 8. REPRESENTATIONS AND<|mask|>. Each party hereby represents and warrants to the other party as of the date hereof as follows: <|sep|>"
275
  inputs1 = tokenizer(text1, return_tensors="pt")
276
  outputs1 = mlm_model(**inputs1)
277
 
 
280
  probs1 = outputs1.logits[0, masked_index1].softmax(dim=0)
281
  top_5_1 = torch.topk(probs1, 5)
282
 
283
+ print("Contract Clause Example - Top 5 predictions:")
284
  for i, (score, idx) in enumerate(zip(top_5_1.values, top_5_1.indices)):
285
  token = tokenizer.decode(idx).strip()
286
  print(f"{i+1}. {token} ({score.item():.4f})")
287
 
288
  # Output:
289
+ # 1. WARRANTIES (0.9271)
290
+ # 2. Warranties (0.0191)
291
+ # 3. REPRESENTATIONS (0.0156)
292
+ # 4. warrants (0.0123)
293
+ # 5. COVENANTS (0.0118)
294
+
295
+ # Example 2: Defined term with mask token immediately after word (no space)
296
+ text2 = "<|cls|> \"Effective<|mask|>\" means the date on which all conditions precedent set forth in Article V are satisfied or waived by the Administrative Agent. <|sep|>"
297
  inputs2 = tokenizer(text2, return_tensors="pt")
298
  outputs2 = mlm_model(**inputs2)
299
 
 
302
  probs2 = outputs2.logits[0, masked_index2].softmax(dim=0)
303
  top_5_2 = torch.topk(probs2, 5)
304
 
305
+ print("\nDefined Term Example - Top 5 predictions:")
306
  for i, (score, idx) in enumerate(zip(top_5_2.values, top_5_2.indices)):
307
  token = tokenizer.decode(idx).strip()
308
  print(f"{i+1}. {token} ({score.item():.4f})")
309
 
310
  # Output:
311
+ # 1. Date (0.9601)
312
+ # 2. Time (0.0211)
313
+ # 3. date (0.0099)
314
+ # 4. Dates (0.0034)
315
+ # 5. Day (0.0006)
316
+
317
+ # Example 3: Regulatory example with mask token immediately after word (no space)
318
+ text3 = "<|cls|> All transactions shall comply with the requirements set forth in the Truth in<|mask|> Act and its implementing Regulation Z. <|sep|>"
319
  inputs3 = tokenizer(text3, return_tensors="pt")
320
  outputs3 = mlm_model(**inputs3)
321
 
 
324
  probs3 = outputs3.logits[0, masked_index3].softmax(dim=0)
325
  top_5_3 = torch.topk(probs3, 5)
326
 
327
+ print("\nRegulatory Example - Top 5 predictions:")
328
  for i, (score, idx) in enumerate(zip(top_5_3.values, top_5_3.indices)):
329
  token = tokenizer.decode(idx).strip()
330
  print(f"{i+1}. {token} ({score.item():.4f})")
331
 
332
  # Output:
333
+ # 1. Lending (0.9075)
334
+ # 2. the (0.0114)
335
+ # 3. Reinvestment (0.0083)
336
+ # 4. Disclosure (0.0036)
337
+ # 5. Credit (0.0026)
338
  ```
339
 
340
+ These examples demonstrate the model's exceptional performance with domain-specific terminology and its ability to predict appropriate terms with very high confidence (over 90% in some cases). Note the careful placement of the mask token - immediately after a word without a space when we want to predict a word that would normally be adjacent to the previous word.
341
+
342
+ These examples show that the model can predict contextually appropriate tokens across different legal and financial domains with extremely high confidence:
343
 
344
+ 1. In a contract clause context, it correctly predicts "WARRANTIES" with over 92% confidence
345
+ 2. In a defined term context, it predicts "Date" with 96% confidence
346
+ 3. In a regulatory context, it correctly identifies "Lending" for the Truth in Lending Act with 90% confidence
347
 
348
  For applications primarily focused on masked language modeling, you may still want to consider models specifically optimized for that task.
349
 
350
  ## Special Tokens
351
 
352
+ This model includes the following special tokens:
353
 
354
+ - CLS token: `<|cls|>` (ID: 5) - Used for the beginning of input text
355
+ - SEP token: `<|sep|>` (ID: 4) - Used for the end of input text
356
  - PAD token: `<|pad|>` (ID: 2) - Used for padding sequences to a uniform length
357
  - BOS token: `<|start|>` (ID: 0) - Beginning of sequence
358
  - EOS token: `<|end|>` (ID: 1) - End of sequence
359
  - UNK token: `<|unk|>` (ID: 3) - Unknown token
360
  - MASK token: `<|mask|>` (ID: 6) - Used for masked language modeling tasks
361
 
362
+ Important usage notes:
363
+
364
+ When using the MASK token for predictions, be aware that this model uses a **space-prefixed BPE tokenizer**. The <|mask|> token should be placed IMMEDIATELY after the previous token with NO space, because most tokens in this tokenizer have an initial space encoded within them. For example: `"word<|mask|>"` rather than `"word <|mask|>"`.
365
+
366
+ This space-aware placement is crucial for getting accurate predictions, as demonstrated in our test examples.
367
 
368
  ## Limitations
369
 
 
378
  ## References
379
 
380
  - [KL3M Tokenizers: A Family of Domain-Specific and Character-Level Tokenizers for Legal, Financial, and Preprocessing Applications](https://arxiv.org/abs/2503.17247)
381
+ - [The KL3M Data Project: Copyright-Clean Training Resources for Large Language Models](https://arxiv.org/abs/2504.07854)
382
 
383
  ## Citation
384
 
 
395
  }
396
  ```
397
 
398
+ ```bibtex
399
+ @misc{bommarito2025kl3mdata,
400
+ title={The KL3M Data Project: Copyright-Clean Training Resources for Large Language Models},
401
+ author={Bommarito II, Michael J. and Bommarito, Jillian and Katz, Daniel Martin},
402
+ year={2025},
403
+ eprint={2504.07854},
404
+ archivePrefix={arXiv},
405
+ primaryClass={cs.CL}
406
+ }
407
+ ```
408
+
409
  ## License
410
 
411
  This model is licensed under [CC-BY 4.0](https://creativecommons.org/licenses/by/4.0/).