ProCreations commited on
Commit
f829eea
·
verified ·
1 Parent(s): 43e5857

Upload folder using huggingface_hub

Browse files
LICENSE ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ LFM Open License v1.0
2
+
3
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
4
+
5
+ 1. Definitions.
6
+
7
+ "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by this document.
8
+
9
+ "Licensor" shall mean Liquid AI, Inc.
10
+
11
+ "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
12
+
13
+ "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
14
+
15
+ "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
16
+
17
+ "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
18
+
19
+ "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work.
20
+
21
+ "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
22
+
23
+ "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
24
+
25
+ "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
26
+
27
+ "Commercial Use" shall mean any use of the Work for direct or indirect commercial advantage or monetary compensation.
28
+
29
+ "Qualified Non-Profit Organization" shall mean a Legal Entity that is organized and operated exclusively for religious, charitable, scientific, testing for public safety, literary, or educational purposes, and which is exempt from federal income tax under Section 501(c)(3) of the United States Internal Revenue Code of 1986, as amended, or any equivalent non-profit or charitable organization in a foreign jurisdiction.
30
+
31
+ "Non-Commercial or Research Purposes" shall mean purposes that do not involve any use of the Work or a Derivative Work for Commercial Use.
32
+
33
+ "Threshold" shall mean annual revenue of 10 million United States dollars ($10,000,000) or more.
34
+
35
+ 2. Grant of Copyright License. Subject to the terms and conditions of this License, including the Commercial Use limitation set forth in Section 5, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
36
+
37
+ 3. Grant of Patent License. Subject to the terms and conditions of this License, including the Commercial Use limitation set forth in Section 5, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
38
+
39
+ 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
40
+
41
+ (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
42
+
43
+ (b) You must cause any modified files to carry prominent notices stating that You changed the files; and
44
+
45
+ (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
46
+
47
+ (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
48
+
49
+ You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
50
+
51
+ 5. Commercial Use Limitation.
52
+
53
+ (a) The rights granted under this License for Commercial Use are conditioned upon You or Your Legal Entity not exceeding the Threshold.
54
+
55
+ (b) Any Commercial Use of the Work or a Derivative Work by a Legal Entity that exceeds the Threshold is not licensed under this Agreement.
56
+
57
+ (c) The Threshold shall not apply to a Qualified Non-Profit Organization's use of the Work or a Derivative Work for Non-Commercial or Research Purposes.
58
+
59
+ 6. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
60
+
61
+ 7. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except for the reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
62
+
63
+ 8. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
64
+
65
+ 9. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
66
+
67
+ 10. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
68
+
69
+ 11. Termination. This License will terminate automatically and immediately if You fail to comply with any of its terms and conditions. Upon termination, You must cease all use of the Work and any Derivative Works and delete all copies in Your possession.
70
+
71
+ END OF TERMS AND CONDITIONS
README.md ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: other
3
+ license_name: lfm-open-license-v1.0
4
+ license_link: https://huggingface.co/LiquidAI/LFM2.5-Encoder-350M/blob/main/LICENSE
5
+ library_name: transformers
6
+ pipeline_tag: text-classification
7
+ tags:
8
+ - betterwright
9
+ - accessibility
10
+ - browser-agent
11
+ - reranking
12
+ - long-context
13
+ base_model: LiquidAI/LFM2.5-Encoder-350M
14
+ ---
15
+
16
+ # BetterWright Encoder 350M
17
+
18
+ A task-conditioned accessibility-tree relevance encoder for reducing browser
19
+ agent context while preserving action targets and evidence. It is trained from
20
+ `LiquidAI/LFM2.5-Encoder-350M` in bfloat16.
21
+
22
+ All 355,011,331 parameters are trained; this checkpoint does not use LoRA,
23
+ adapters, or a frozen backbone. The model has three outputs: chunk relevance,
24
+ token/node relevance, and a confidence signal for deterministic fallback.
25
+ BetterWright keeps its original snapshot whenever the confidence gate is not
26
+ met.
27
+
28
+ The training corpus contains 500,000 deduplicated structural examples grounded
29
+ in 5,256 independently generated and audited tasks from 141 real-site domains.
30
+ Domains—not rows—define the split: 110 train, 8 validation, and 23 untouched
31
+ test domains.
32
+ The corpus is primarily BetterWright accessibility trees, with a smaller share
33
+ of alternate accessibility serializations for robustness.
34
+
35
+ ## Input
36
+
37
+ ```text
38
+ [BETTERWRIGHT_TASK]
39
+ <the current browser task or observation query>
40
+ [ACCESSIBILITY_SUBTREE]
41
+ <BetterWright aria tree chunk>
42
+ ```
43
+
44
+ The released checkpoint is progressively trained at 8K, 16K, 32K, and 64K
45
+ sequence lengths. Normal inference should still use hierarchical chunks for
46
+ lower latency; 64K is intended for unusually large dumps and packed tabs.
47
+
48
+ ## Quick start
49
+
50
+ ```python
51
+ import torch
52
+ from transformers import AutoModel, AutoTokenizer
53
+
54
+ model_id = "ProCreations/betterwright-encoder-350m"
55
+ tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
56
+ model = AutoModel.from_pretrained(
57
+ model_id,
58
+ trust_remote_code=True,
59
+ torch_dtype=torch.bfloat16,
60
+ ).eval()
61
+ batch = tokenizer(
62
+ "[BETTERWRIGHT_TASK]\nOpen pricing\n[ACCESSIBILITY_SUBTREE]\n"
63
+ '- link "Pricing" [ref=e12]',
64
+ return_tensors="pt",
65
+ )
66
+ with torch.inference_mode():
67
+ output = model(**batch)
68
+ relevance = torch.sigmoid(output.logits)
69
+ confidence = torch.sigmoid(output.uncertainty_logits)
70
+ token_relevance = torch.sigmoid(output.token_logits)
71
+ ```
72
+
73
+ Production pruning should use the validated thresholds in
74
+ `relevance_config.json`, deterministic must-retain rules, and exact full-tree
75
+ fallback. A raw relevance score alone is not a safe deletion decision.
76
+
77
+ ## Training
78
+
79
+ - 500,000 unique pairs: 77.7% BetterWright trees, 13.1% alternate ARIA trees,
80
+ and 9.1% compact accessibility outlines.
81
+ - 391,777 train, 25,891 validation, and 82,332 untouched-test pairs, split by
82
+ domain before structural expansion.
83
+ - Full-parameter BF16 AdamW training with global batch 128, a cosine schedule,
84
+ and a class weight derived from the exact training distribution.
85
+ - A balanced positive/negative packed-tree curriculum at 8K, 16K, 32K, and
86
+ 64K tokens, with exact required-node span supervision.
87
+
88
+ ## Evaluation policy
89
+
90
+ Fallback thresholds are selected only on validation domains. The public test
91
+ report measures exact target/evidence-node recall, complete-task node recall,
92
+ fallback rate, and tokenizer-measured savings on the untouched test domains.
93
+ The report and production threshold file are published after the checkpoint's
94
+ post-training quality gate; claims are not inferred from training loss.
95
+
96
+ ## Safety and limitations
97
+
98
+ This is a relevance model, not an autonomous browser agent. It must not be the
99
+ only path for security decisions. Snapshot text is untrusted data. Consumers
100
+ should keep deterministic must-retain rules and fall back to the full tree on
101
+ model errors, timeouts, low confidence, or insufficient retained context.
config.json ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "BetterWrightEncoder"
4
+ ],
5
+ "auto_map": {
6
+ "AutoModel": "modeling_betterwright.BetterWrightEncoder",
7
+ "AutoModelForSequenceClassification": "modeling_betterwright.BetterWrightEncoder"
8
+ },
9
+ "betterwright_max_trained_context": 65536,
10
+ "betterwright_positive_weight": 2.0649241938259824,
11
+ "betterwright_schema": "task-tree-relevance-v1",
12
+ "betterwright_token_positive_weight": 20.0,
13
+ "block_auto_adjust_ff_dim": true,
14
+ "block_dim": 1024,
15
+ "block_ffn_dim_multiplier": 1.0,
16
+ "block_mlp_init_scale": 1.0,
17
+ "block_multiple_of": 256,
18
+ "block_norm_eps": 1e-05,
19
+ "block_out_init_scale": 1.0,
20
+ "block_use_swiglu": true,
21
+ "block_use_xavier_init": true,
22
+ "bos_token_id": 1,
23
+ "conv_L_cache": 3,
24
+ "conv_bias": false,
25
+ "conv_dim": 1024,
26
+ "conv_dim_out": 1024,
27
+ "conv_use_xavier_init": true,
28
+ "dtype": "bfloat16",
29
+ "eos_token_id": 7,
30
+ "hidden_size": 1024,
31
+ "initializer_range": 0.02,
32
+ "intermediate_size": 6656,
33
+ "layer_types": [
34
+ "conv",
35
+ "conv",
36
+ "full_attention",
37
+ "conv",
38
+ "conv",
39
+ "full_attention",
40
+ "conv",
41
+ "conv",
42
+ "full_attention",
43
+ "conv",
44
+ "full_attention",
45
+ "conv",
46
+ "full_attention",
47
+ "conv",
48
+ "full_attention",
49
+ "conv"
50
+ ],
51
+ "max_position_embeddings": 128000,
52
+ "model_type": "lfm2",
53
+ "norm_eps": 1e-05,
54
+ "num_attention_heads": 16,
55
+ "num_heads": 16,
56
+ "num_hidden_layers": 16,
57
+ "num_key_value_heads": 8,
58
+ "pad_token_id": 0,
59
+ "rope_parameters": {
60
+ "rope_theta": 1000000.0,
61
+ "rope_type": "default"
62
+ },
63
+ "tie_word_embeddings": true,
64
+ "transformers_version": "5.1.0",
65
+ "use_cache": false,
66
+ "use_pos_enc": true,
67
+ "vocab_size": 65536
68
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:26ff52b2d0935f248a87dcccc4cffa84854c8fda6f21eb65d8529a4282039cda
3
+ size 710039782
modeling_betterwright.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """BetterWright task-conditioned relevance heads on LFM2.5 Encoder."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from typing import Optional
7
+
8
+ import torch
9
+ import torch.nn as nn
10
+ import torch.nn.functional as F
11
+ from transformers.modeling_outputs import ModelOutput
12
+ from transformers.models.lfm2.configuration_lfm2 import Lfm2Config
13
+ from transformers.models.lfm2.modeling_lfm2 import Lfm2PreTrainedModel
14
+
15
+ from modeling_lfm2_bidirectional import Lfm2BidirectionalModel, _install_patches
16
+
17
+
18
+ @dataclass
19
+ class BetterWrightEncoderOutput(ModelOutput):
20
+ loss: Optional[torch.Tensor] = None
21
+ logits: Optional[torch.Tensor] = None
22
+ token_logits: Optional[torch.Tensor] = None
23
+ uncertainty_logits: Optional[torch.Tensor] = None
24
+ last_hidden_state: Optional[torch.Tensor] = None
25
+
26
+
27
+ class BetterWrightEncoder(Lfm2PreTrainedModel):
28
+ """Cross-encoder chunk scorer plus per-token relevance and fallback heads."""
29
+
30
+ config_class = Lfm2Config
31
+ base_model_prefix = "lfm2"
32
+
33
+ def __init__(self, config: Lfm2Config):
34
+ _install_patches()
35
+ config.use_cache = False
36
+ super().__init__(config)
37
+ self.lfm2 = Lfm2BidirectionalModel(config)
38
+ self.relevance_head = nn.Sequential(
39
+ nn.Linear(config.hidden_size, config.hidden_size // 2),
40
+ nn.SiLU(),
41
+ nn.Dropout(0.05),
42
+ nn.Linear(config.hidden_size // 2, 1),
43
+ )
44
+ self.token_head = nn.Linear(config.hidden_size, 1)
45
+ self.uncertainty_head = nn.Linear(config.hidden_size, 1)
46
+ self.post_init()
47
+
48
+ def get_input_embeddings(self):
49
+ return self.lfm2.embed_tokens
50
+
51
+ def set_input_embeddings(self, value):
52
+ self.lfm2.embed_tokens = value
53
+
54
+ def forward(
55
+ self,
56
+ input_ids: Optional[torch.LongTensor] = None,
57
+ attention_mask: Optional[torch.Tensor] = None,
58
+ position_ids: Optional[torch.LongTensor] = None,
59
+ inputs_embeds: Optional[torch.FloatTensor] = None,
60
+ labels: Optional[torch.Tensor] = None,
61
+ token_labels: Optional[torch.Tensor] = None,
62
+ return_dict: bool = True,
63
+ **kwargs,
64
+ ) -> BetterWrightEncoderOutput | tuple:
65
+ outputs = self.lfm2(
66
+ input_ids=input_ids,
67
+ attention_mask=attention_mask,
68
+ position_ids=position_ids,
69
+ inputs_embeds=inputs_embeds,
70
+ use_cache=False,
71
+ return_dict=True,
72
+ **kwargs,
73
+ )
74
+ hidden = outputs.last_hidden_state
75
+ token_logits = self.token_head(hidden).squeeze(-1)
76
+ if attention_mask is None:
77
+ pooling_weights = torch.softmax(token_logits, dim=1).unsqueeze(-1)
78
+ else:
79
+ masked_pool_logits = token_logits.masked_fill(attention_mask == 0, -1e4)
80
+ pooling_weights = torch.softmax(masked_pool_logits, dim=1).unsqueeze(-1)
81
+ # Learned token pooling lets pair-level relevance supervision teach the
82
+ # token head where evidence lives before the exact-span curriculum.
83
+ pooled = (hidden * pooling_weights.to(hidden.dtype)).sum(dim=1)
84
+ logits = self.relevance_head(pooled).squeeze(-1)
85
+ uncertainty_logits = self.uncertainty_head(pooled).squeeze(-1)
86
+ loss = None
87
+ if labels is not None:
88
+ labels = labels.to(logits.dtype)
89
+ positive_weight = float(getattr(self.config, "betterwright_positive_weight", 3.0))
90
+ relevance_loss = F.binary_cross_entropy_with_logits(
91
+ logits,
92
+ labels,
93
+ pos_weight=torch.tensor(positive_weight, device=logits.device, dtype=logits.dtype),
94
+ )
95
+ # Predict disagreement/ambiguity most strongly around the decision boundary.
96
+ uncertainty_target = 1.0 - (labels - torch.sigmoid(logits).detach()).abs()
97
+ uncertainty_loss = F.binary_cross_entropy_with_logits(
98
+ uncertainty_logits, uncertainty_target.clamp(0, 1)
99
+ )
100
+ loss = relevance_loss + 0.08 * uncertainty_loss
101
+ if token_labels is not None:
102
+ valid = token_labels >= 0
103
+ if valid.any():
104
+ valid_labels = token_labels[valid]
105
+ positive_count = (valid_labels == 1).sum()
106
+ negative_count = (valid_labels == 0).sum()
107
+ if positive_count:
108
+ # Required lines are exceptionally sparse in a 64K tree.
109
+ # Batch-adaptive weighting prevents the all-negative token
110
+ # solution while remaining capped for stable BF16 updates.
111
+ token_positive_weight = float(
112
+ (negative_count / positive_count).clamp(20, 512)
113
+ )
114
+ else:
115
+ token_positive_weight = 1.0
116
+ token_loss = F.binary_cross_entropy_with_logits(
117
+ token_logits[valid],
118
+ valid_labels.to(token_logits.dtype),
119
+ pos_weight=torch.tensor(
120
+ token_positive_weight,
121
+ device=token_logits.device,
122
+ dtype=token_logits.dtype,
123
+ ),
124
+ )
125
+ loss = token_loss if loss is None else loss + 0.35 * token_loss
126
+ result = BetterWrightEncoderOutput(
127
+ loss=loss,
128
+ logits=logits,
129
+ token_logits=token_logits,
130
+ uncertainty_logits=uncertainty_logits,
131
+ last_hidden_state=hidden,
132
+ )
133
+ return result if return_dict else tuple(result.values())
modeling_lfm2_bidirectional.py ADDED
@@ -0,0 +1,211 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """LFM2 backbone with bidirectional attention + non-causal short-conv.
2
+
3
+ Wired into the HF repo via `auto_map` in config.json so that
4
+
5
+ AutoModel.from_pretrained(repo, trust_remote_code=True)
6
+ AutoModelForMaskedLM.from_pretrained(repo, trust_remote_code=True)
7
+
8
+ both return a model with the encoder-style patches already applied.
9
+
10
+ Supports `attn_implementation` in {"eager", "sdpa", "flash_attention_2"}:
11
+
12
+ eager/sdpa consume a 4D additive pad-only mask and reproduce the exact
13
+ training-time behavior; flash_attention_2 receives the 2D padding mask (or
14
+ None) and runs the kernel non-causally via `Lfm2Attention.is_causal = False`,
15
+ yielding outputs equivalent to the unpadded forward.
16
+ """
17
+
18
+ from typing import Optional
19
+
20
+ import torch
21
+ import torch.nn as nn
22
+ import torch.nn.functional as F
23
+ from transformers.configuration_utils import PretrainedConfig
24
+ from transformers.modeling_outputs import BaseModelOutput, MaskedLMOutput
25
+ from transformers.modeling_utils import PreTrainedModel
26
+ from transformers.models.lfm2 import modeling_lfm2 as _lfm2_mod
27
+ from transformers.models.lfm2.configuration_lfm2 import Lfm2Config
28
+ from transformers.models.lfm2.modeling_lfm2 import (
29
+ Lfm2Attention,
30
+ Lfm2Model,
31
+ Lfm2PreTrainedModel,
32
+ Lfm2ShortConv,
33
+ apply_mask_to_padding_states,
34
+ )
35
+
36
+
37
+ def _bidirectional_mask(
38
+ config,
39
+ input_embeds: torch.Tensor = None,
40
+ attention_mask: Optional[torch.Tensor] = None,
41
+ cache_position: Optional[torch.LongTensor] = None,
42
+ past_key_values=None,
43
+ position_ids: Optional[torch.LongTensor] = None,
44
+ **kwargs,
45
+ ) -> Optional[torch.Tensor]:
46
+ # transformers has renamed the embeds kwarg across versions
47
+ # (input_embeds <-> inputs_embeds); accept either to stay forward-compatible.
48
+ if input_embeds is None:
49
+ input_embeds = kwargs.get("inputs_embeds")
50
+
51
+ if config._attn_implementation == "flash_attention_2":
52
+ # FA2 only uses the 2D padding mask to unpad sequences; causality is
53
+ # controlled by `Lfm2Attention.is_causal` (set to False below).
54
+ if attention_mask is not None and not attention_mask.all():
55
+ return attention_mask
56
+ return None
57
+
58
+ device = input_embeds.device
59
+ dtype = input_embeds.dtype
60
+ bsz, q_len = input_embeds.shape[:2]
61
+ past = past_key_values.get_seq_length() if past_key_values is not None else 0
62
+ kv_len = past + q_len
63
+
64
+ mask = torch.zeros((bsz, 1, q_len, kv_len), device=device, dtype=dtype)
65
+ if attention_mask is not None:
66
+ cur_len = attention_mask.size(-1)
67
+ key_pad_flags = (attention_mask == 0).to(device=device, dtype=torch.float32)
68
+ pad_vec = torch.zeros((bsz, kv_len), device=device, dtype=torch.float32)
69
+ if cur_len > 0:
70
+ pad_vec[:, past:past + cur_len] = key_pad_flags * -1e9
71
+ mask = mask + pad_vec.to(dtype)[:, None, None, :]
72
+ return mask
73
+
74
+
75
+ def _noncausal_shortconv_forward(
76
+ self,
77
+ hidden_states: torch.Tensor,
78
+ past_key_values=None,
79
+ cache_position=None,
80
+ attention_mask: Optional[torch.Tensor] = None,
81
+ **kwargs,
82
+ ) -> torch.Tensor:
83
+ x = apply_mask_to_padding_states(hidden_states, attention_mask)
84
+
85
+ BCx = self.in_proj(x).transpose(-1, -2)
86
+ B, C, x = BCx.chunk(3, dim=-2)
87
+ Bx = B * x
88
+
89
+ k = self.conv.weight.shape[-1]
90
+ pad = k // 2
91
+ conv_out = F.conv1d(
92
+ Bx, weight=self.conv.weight, bias=self.conv.bias,
93
+ stride=1, padding=pad, dilation=1, groups=Bx.shape[1],
94
+ )
95
+ if conv_out.shape[-1] > Bx.shape[-1]:
96
+ conv_out = conv_out[..., :Bx.shape[-1]]
97
+ elif conv_out.shape[-1] < Bx.shape[-1]:
98
+ conv_out = F.pad(conv_out, (0, Bx.shape[-1] - conv_out.shape[-1]))
99
+
100
+ y = C * conv_out
101
+ y = y.transpose(-1, -2).contiguous()
102
+ return self.out_proj(y)
103
+
104
+
105
+ def _shortconv_forward(self, *args, **kwargs):
106
+ return self.slow_forward(*args, **kwargs)
107
+
108
+
109
+ _PATCHED = False
110
+
111
+
112
+ def _install_patches() -> None:
113
+ global _PATCHED
114
+ if _PATCHED:
115
+ return
116
+ _lfm2_mod.create_causal_mask = _bidirectional_mask
117
+ Lfm2ShortConv.slow_forward = _noncausal_shortconv_forward
118
+ Lfm2ShortConv.forward = _shortconv_forward
119
+ _PATCHED = True
120
+
121
+
122
+ _install_patches()
123
+
124
+
125
+ def _set_attention_noncausal(model) -> None:
126
+ for module in model.modules():
127
+ if isinstance(module, Lfm2Attention):
128
+ module.is_causal = False
129
+
130
+
131
+ class Lfm2BidirectionalModel(Lfm2Model):
132
+ """LFM2 patched for encoder-style use:
133
+ full bidirectional attention + non-causal short-conv."""
134
+
135
+ def __init__(self, config):
136
+ _install_patches()
137
+ super().__init__(config)
138
+ _set_attention_noncausal(self)
139
+
140
+
141
+ class Lfm2BidirectionalForMaskedLM(Lfm2PreTrainedModel):
142
+ """LFM2 bidirectional encoder with a tied masked-LM head."""
143
+
144
+ config_class = Lfm2Config
145
+ base_model_prefix = "lfm2"
146
+ _tied_weights_keys = {"lm_head.weight": "lfm2.embed_tokens.weight"}
147
+
148
+ def __init__(self, config: Lfm2Config):
149
+ _install_patches()
150
+ config = type(config).from_dict({**config.to_dict(), "use_cache": False})
151
+ super().__init__(config)
152
+ self.lfm2 = Lfm2BidirectionalModel(config)
153
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
154
+ self.post_init()
155
+ self.lm_head.weight = self.lfm2.embed_tokens.weight
156
+
157
+ def get_input_embeddings(self):
158
+ return self.lfm2.embed_tokens
159
+
160
+ def set_input_embeddings(self, value):
161
+ self.lfm2.embed_tokens = value
162
+
163
+ def get_output_embeddings(self):
164
+ return self.lm_head
165
+
166
+ def set_output_embeddings(self, new_embeddings):
167
+ self.lm_head = new_embeddings
168
+
169
+ def forward(
170
+ self,
171
+ input_ids: Optional[torch.LongTensor] = None,
172
+ attention_mask: Optional[torch.Tensor] = None,
173
+ position_ids: Optional[torch.LongTensor] = None,
174
+ inputs_embeds: Optional[torch.FloatTensor] = None,
175
+ labels: Optional[torch.LongTensor] = None,
176
+ output_hidden_states: Optional[bool] = None,
177
+ output_attentions: Optional[bool] = None,
178
+ return_dict: Optional[bool] = None,
179
+ **kwargs,
180
+ ) -> MaskedLMOutput:
181
+ return_dict = True if return_dict is None else return_dict
182
+ outputs = self.lfm2(
183
+ input_ids=input_ids,
184
+ attention_mask=attention_mask,
185
+ position_ids=position_ids,
186
+ inputs_embeds=inputs_embeds,
187
+ use_cache=False,
188
+ output_attentions=output_attentions,
189
+ output_hidden_states=output_hidden_states,
190
+ return_dict=True,
191
+ )
192
+ hidden = outputs.last_hidden_state
193
+ logits = self.lm_head(hidden)
194
+
195
+ loss = None
196
+ if labels is not None:
197
+ loss = F.cross_entropy(
198
+ logits.view(-1, self.config.vocab_size),
199
+ labels.view(-1),
200
+ ignore_index=-100,
201
+ )
202
+
203
+ if not return_dict:
204
+ out = (logits,) + outputs[1:]
205
+ return ((loss,) + out) if loss is not None else out
206
+ return MaskedLMOutput(
207
+ loss=loss,
208
+ logits=logits,
209
+ hidden_states=outputs.hidden_states,
210
+ attentions=outputs.attentions,
211
+ )
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "backend": "tokenizers",
3
+ "bos_token": "<|startoftext|>",
4
+ "clean_up_tokenization_spaces": false,
5
+ "eos_token": "<|im_end|>",
6
+ "is_local": false,
7
+ "mask_token": "<|mask|>",
8
+ "model_max_length": 1000000000000000019884624838656,
9
+ "pad_token": "<|pad|>",
10
+ "tokenizer_class": "TokenizersBackend"
11
+ }
training_metrics.json ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "validation_pairs": 25891,
3
+ "accuracy_at_0.5": 0.7068865895271301,
4
+ "positive_recall_at_0.5": 0.8010137677192688,
5
+ "negative_specificity_at_0.5": 0.661017894744873,
6
+ "mean_positive_score": 0.6922709345817566,
7
+ "mean_negative_score": 0.3838270902633667
8
+ }