doannv commited on
Commit
9830017
·
verified ·
1 Parent(s): fddf29f

Upload folder using huggingface_hub

Browse files
.gitignore ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ checkpoints/
2
+ *.pt
3
+ *.pth
4
+ __pycache__/
5
+ *.pyc
6
+ venv/
7
+ .venv/
8
+ *.log
9
+ .DS_Store
10
+ *.pt
11
+ venv/
12
+ data_*/
13
+ __pycache__/
14
+ latex/
.python-version ADDED
@@ -0,0 +1 @@
 
 
1
+ 3.11
LICENSE ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
10
+
11
+ "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
12
+
13
+ "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.
14
+
15
+ "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
16
+
17
+ "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
18
+
19
+ "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.
20
+
21
+ "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 (an example is provided in the Appendix below).
22
+
23
+ "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.
24
+
25
+ "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."
26
+
27
+ "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.
28
+
29
+ 2. Grant of Copyright License. Subject to the terms and conditions of this License, 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.
30
+
31
+ 3. Grant of Patent License. Subject to the terms and conditions of this License, 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.
32
+
33
+ 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:
34
+
35
+ (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
36
+
37
+ (b) You must cause any modified files to carry prominent notices stating that You changed the files; and
38
+
39
+ (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
40
+
41
+ (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.
42
+
43
+ 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.
44
+
45
+ 5. 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.
46
+
47
+ 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
48
+
49
+ 7. 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.
50
+
51
+ 8. 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.
52
+
53
+ 9. 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.
54
+
55
+ END OF TERMS AND CONDITIONS
56
+
57
+ APPENDIX: How to apply the Apache License to your work.
58
+
59
+ To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
60
+
61
+ Copyright [yyyy] [name of copyright owner]
62
+
63
+ Licensed under the Apache License, Version 2.0 (the "License");
64
+ you may not use this file except in compliance with the License.
65
+ You may obtain a copy of the License at
66
+
67
+ http://www.apache.org/licenses/LICENSE-2.0
68
+
69
+ Unless required by applicable law or agreed to in writing, software
70
+ distributed under the License is distributed on an "AS IS" BASIS,
71
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
72
+ See the License for the specific language governing permissions and
73
+ limitations under the License.
configs/ablation_12layers.yaml ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Ablation: 12 layers (vs baseline 8)
2
+ # Everything else same as v1 baseline
3
+ model:
4
+ vocab_size: 250002
5
+ max_seq_len: 32
6
+ hidden_dim: 768
7
+ num_layers: 12
8
+ num_heads: 12
9
+ ff_dim: 3072
10
+ dropout: 0.1
11
+ embedding_cond_dim: 1024
12
+ mask_token_id: 250001
13
+
14
+ training:
15
+ batch_size: 600
16
+ grad_accum: 4
17
+ max_steps: 20000
18
+ lr: 0.00046875
19
+ min_lr_ratio: 0.0
20
+ weight_decay: 0.01
21
+ warmup_steps: 2000
22
+ max_grad_norm: 1.0
23
+ log_every: 1
24
+ eval_every: 500
25
+ num_workers: 4
26
+ mixed_precision: true
27
+ ema_decay: 0.9999
28
+
29
+ data:
30
+ data_dir: data
31
+ val_split: 0.01
32
+
33
+ evaluation:
34
+ num_denoise_steps: 50
35
+ num_samples: 1000
36
+ jina_model: jinaai/jina-embeddings-v3
configs/ablation_dropout005.yaml ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Ablation: dropout 0.05 (vs baseline 0.1)
2
+ # Everything else same as v1 baseline
3
+ model:
4
+ vocab_size: 250002
5
+ max_seq_len: 32
6
+ hidden_dim: 768
7
+ num_layers: 8
8
+ num_heads: 12
9
+ ff_dim: 3072
10
+ dropout: 0.05
11
+ embedding_cond_dim: 1024
12
+ mask_token_id: 250001
13
+
14
+ training:
15
+ batch_size: 600
16
+ grad_accum: 4
17
+ max_steps: 20000
18
+ lr: 0.00046875
19
+ min_lr_ratio: 0.0
20
+ weight_decay: 0.01
21
+ warmup_steps: 2000
22
+ max_grad_norm: 1.0
23
+ log_every: 1
24
+ eval_every: 500
25
+ num_workers: 4
26
+ mixed_precision: true
27
+ ema_decay: 0.9999
28
+
29
+ data:
30
+ data_dir: data
31
+ val_split: 0.01
32
+
33
+ evaluation:
34
+ num_denoise_steps: 50
35
+ num_samples: 1000
36
+ jina_model: jinaai/jina-embeddings-v3
configs/ablation_minlr01.yaml ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Ablation: min_lr_ratio=0.1 (vs baseline 0.0)
2
+ # Cosine schedule floors at 10% of max lr instead of 0
3
+ model:
4
+ vocab_size: 250002
5
+ max_seq_len: 32
6
+ hidden_dim: 768
7
+ num_layers: 8
8
+ num_heads: 12
9
+ ff_dim: 3072
10
+ dropout: 0.1
11
+ embedding_cond_dim: 1024
12
+ mask_token_id: 250001
13
+
14
+ training:
15
+ batch_size: 600
16
+ grad_accum: 4
17
+ max_steps: 20000
18
+ lr: 0.00046875
19
+ min_lr_ratio: 0.1
20
+ weight_decay: 0.01
21
+ warmup_steps: 2000
22
+ max_grad_norm: 1.0
23
+ log_every: 1
24
+ eval_every: 500
25
+ num_workers: 4
26
+ mixed_precision: true
27
+ ema_decay: 0.9999
28
+
29
+ data:
30
+ data_dir: data
31
+ val_split: 0.01
32
+
33
+ evaluation:
34
+ num_denoise_steps: 50
35
+ num_samples: 1000
36
+ jina_model: jinaai/jina-embeddings-v3
configs/default.yaml ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Conditional MDLM for Embedding Inversion
2
+ model:
3
+ vocab_size: 250002
4
+ max_seq_len: 32
5
+ hidden_dim: 768
6
+ num_layers: 8
7
+ num_heads: 12
8
+ ff_dim: 3072
9
+ dropout: 0.1
10
+ embedding_cond_dim: 1024 # jina-embeddings-v3 output dim
11
+ mask_token_id: 250001
12
+
13
+ training:
14
+ batch_size: 128
15
+ grad_accum: 4
16
+ max_steps: 50000
17
+ lr: 0.0001
18
+ weight_decay: 0.01
19
+ warmup_steps: 2000
20
+ max_grad_norm: 1.0
21
+ log_every: 1
22
+ eval_every: 500
23
+ num_workers: 2
24
+ mixed_precision: true
25
+
26
+ data:
27
+ data_dir: data
28
+ val_split: 0.01
29
+
30
+ evaluation:
31
+ num_denoise_steps: 50
32
+ num_samples: 1000
33
+ jina_model: jinaai/jina-embeddings-v3
configs/v2.yaml ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ model:
2
+ vocab_size: 250002
3
+ max_seq_len: 128
4
+ hidden_dim: 768
5
+ num_layers: 12
6
+ num_heads: 12
7
+ ff_dim: 3072
8
+ dropout: 0.05
9
+ embedding_cond_dim: 1024
10
+ mask_token_id: 250001
11
+
12
+ training:
13
+ batch_size: 200
14
+ grad_accum: 8
15
+ max_steps: 200000
16
+ lr: 0.0003125
17
+ min_lr_ratio: 0.1
18
+ weight_decay: 0.01
19
+ warmup_steps: 3000
20
+ max_grad_norm: 1.0
21
+ log_every: 1
22
+ eval_every: 500
23
+ num_workers: 4
24
+ mixed_precision: true
25
+ ema_decay: 0.9999
26
+
27
+ data:
28
+ data_dir: data_v2
29
+ val_split: 0.01
30
+
31
+ evaluation:
32
+ num_denoise_steps: 50
33
+ num_samples: 1000
34
+ jina_model: jinaai/jina-embeddings-v3
configs/v2_gemma.yaml ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ model:
2
+ vocab_size: 262145
3
+ max_seq_len: 32
4
+ hidden_dim: 768
5
+ num_layers: 8
6
+ num_heads: 12
7
+ ff_dim: 3072
8
+ dropout: 0.0
9
+ embedding_cond_dim: 768
10
+ mask_token_id: 262144 # vocab_size - 1
11
+ encoder_model: unsloth/embeddinggemma-300m
12
+ decoder_tokenizer: unsloth/embeddinggemma-300m
13
+
14
+ training:
15
+ batch_size: 400
16
+ grad_accum: 4
17
+ max_steps: 200000
18
+ lr: 0.0001
19
+ min_lr_ratio: 0.1
20
+ weight_decay: 0.01
21
+ warmup_steps: 2000
22
+ max_grad_norm: 1.0
23
+ log_every: 1
24
+ eval_every: 500
25
+ num_workers: 4
26
+ mixed_precision: true
27
+ ema_decay: 0.9999
28
+
29
+ data:
30
+ data_dir: data_gemma
31
+ val_split: 0.01
configs/v2_jinav3.yaml ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ model:
2
+ vocab_size: 250002
3
+ max_seq_len: 32
4
+ hidden_dim: 768
5
+ num_layers: 8
6
+ num_heads: 12
7
+ ff_dim: 3072
8
+ dropout: 0.0
9
+ embedding_cond_dim: 1024
10
+ mask_token_id: 250001
11
+ encoder_model: jinaai/jina-embeddings-v3
12
+ decoder_tokenizer: xlm-roberta-base
13
+
14
+ training:
15
+ batch_size: 400
16
+ grad_accum: 4
17
+ max_steps: 200000
18
+ lr: 0.0001
19
+ min_lr_ratio: 0.1
20
+ weight_decay: 0.01
21
+ warmup_steps: 2000
22
+ max_grad_norm: 1.0
23
+ log_every: 1
24
+ eval_every: 500
25
+ num_workers: 4
26
+ mixed_precision: true
27
+ ema_decay: 0.9999
28
+
29
+ data:
30
+ data_dir: data_jinav3
31
+ val_split: 0.01
configs/v2_qwen3.yaml ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ model:
2
+ vocab_size: 151669
3
+ max_seq_len: 32
4
+ pretrained_token_embeddings: "Qwen/Qwen3-Embedding-0.6B"
5
+ hidden_dim: 1024
6
+ num_layers: 8
7
+ num_heads: 12
8
+ ff_dim: 3072
9
+ dropout: 0.0
10
+ embedding_cond_dim: 1024
11
+ mask_token_id: 151668 # vocab_size - 1
12
+ encoder_model: Qwen/Qwen3-Embedding-0.6B
13
+ decoder_tokenizer: Qwen/Qwen3-Embedding-0.6B
14
+
15
+ training:
16
+ batch_size: 400
17
+ grad_accum: 4
18
+ max_steps: 200000
19
+ lr: 0.0001
20
+ min_lr_ratio: 0.1
21
+ weight_decay: 0.01
22
+ warmup_steps: 2000
23
+ max_grad_norm: 1.0
24
+ log_every: 1
25
+ eval_every: 500
26
+ num_workers: 4
27
+ mixed_precision: true
28
+ ema_decay: 0.9999
29
+
30
+ data:
31
+ data_dir: /kaggle/embedding-inversion-demo/omega_books_500k_32.pt
32
+ val_split: 0.01
configs/v3_mmbert_jinav3.yaml ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # v3: mmBERT-base backbone with AdaLN-Zero conditioning + jina-v3 encoder
2
+ # Full pretrained mmBERT (22 layers, 768d) with conditioning on jina-embeddings-v3
3
+ model:
4
+ vocab_size: 256001 # mmBERT vocab (256000) + 1 mask token
5
+ max_seq_len: 32
6
+ hidden_dim: 768 # mmBERT hidden size
7
+ num_layers: 22 # mmBERT num layers (loaded from pretrained)
8
+ num_heads: 12 # mmBERT num attention heads
9
+ ff_dim: 1152 # mmBERT intermediate size (not used, loaded from pretrained)
10
+ dropout: 0.0
11
+ embedding_cond_dim: 1024 # jina-embeddings-v3 output dim
12
+ mask_token_id: 256000 # vocab_size - 1
13
+ encoder_model: jinaai/jina-embeddings-v3
14
+ decoder_tokenizer: jhu-clsp/mmBERT-base
15
+ pretrained_token_embeddings: jhu-clsp/mmBERT-base
16
+ freeze_token_embeddings: true
17
+ tie_weights: false # output_proj independent from frozen token_embed
18
+
19
+ training:
20
+ batch_size: 400
21
+ grad_accum: 4
22
+ max_steps: 200000
23
+ lr: 0.0001
24
+ min_lr_ratio: 0.1
25
+ weight_decay: 0.01
26
+ warmup_steps: 2000
27
+ max_grad_norm: 1.0
28
+ log_every: 1
29
+ eval_every: 500
30
+ num_workers: 4
31
+ mixed_precision: true
32
+ ema_decay: 0.9999
33
+ early_stop_patience: 5000
34
+
35
+ data:
36
+ data_dir: data_mmbert_jinav3
37
+ val_split: 0.01
dataset.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Dataset for embedding inversion training.
3
+ Reads pre-converted numpy .npy files for instant loading.
4
+ """
5
+
6
+ import os
7
+ import glob
8
+ import bisect
9
+ import json
10
+ import numpy as np
11
+ import torch
12
+ from torch.utils.data import Dataset, DataLoader
13
+ from transformers import AutoTokenizer
14
+
15
+ class EmbeddingInversionDataset(Dataset):
16
+ """
17
+ Dataset đọc dữ liệu từ file .pt đã được preprocess.
18
+ """
19
+ def __init__(self, pt_file_path, tokenizer, max_seq_len=32, val=False, val_split=0.01):
20
+ self.tokenizer = tokenizer
21
+ self.max_seq_len = max_seq_len
22
+
23
+ # Load dữ liệu từ file .pt
24
+ print(f"Loading data from {pt_file_path}...")
25
+ self.raw_data = torch.load(pt_file_path) # List[Dict]
26
+
27
+ # Tạo mapping để truy cập chunk theo index phẳng (flat index)
28
+ # Vì mỗi cuốn sách có số lượng chunk khác nhau
29
+ self.flat_indices = []
30
+ for book_idx, book in enumerate(self.raw_data):
31
+ num_chunks = len(book["chunks_text"])
32
+ for chunk_idx in range(num_chunks):
33
+ self.flat_indices.append((book_idx, chunk_idx))
34
+
35
+ self.total_rows = len(self.flat_indices)
36
+
37
+ # Chia Train/Val
38
+ val_count = int(self.total_rows * val_split)
39
+ if val:
40
+ self.start_idx = self.total_rows - val_count
41
+ self.length = val_count
42
+ else:
43
+ self.start_idx = 0
44
+ self.length = self.total_rows - val_count
45
+
46
+ def __len__(self):
47
+ return self.length
48
+
49
+ def __getitem__(self, idx):
50
+ global_idx = self.start_idx + idx
51
+ book_idx, chunk_in_book_idx = self.flat_indices[global_idx]
52
+
53
+ # Lấy dữ liệu
54
+ book_data = self.raw_data[book_idx]
55
+ text = book_data["chunks_text"][chunk_in_book_idx]
56
+ embedding = book_data["embeddings"][chunk_in_book_idx] # Tensor đã có sẵn
57
+
58
+ # Tokenize lại text để lấy token_ids (vì file .pt chỉ lưu text)
59
+ encoding = self.tokenizer(
60
+ text,
61
+ max_length=self.max_seq_len,
62
+ padding="max_length",
63
+ truncation=True,
64
+ return_tensors="pt"
65
+ )
66
+
67
+ token_ids = encoding["input_ids"].squeeze(0) # (max_seq_len)
68
+
69
+ # Tạo padding mask
70
+ # Thông thường 0 hoặc 1 tùy model, Qwen thường dùng padding_mask từ tokenizer
71
+ padding_mask = (token_ids == self.tokenizer.pad_token_id)
72
+
73
+ return {
74
+ "token_ids": token_ids.long(),
75
+ "embedding": embedding.float(),
76
+ "padding_mask": padding_mask,
77
+ }
78
+
79
+ # /kaggle/embedding-inversion-demo/dataset.py
80
+
81
+ def create_dataloaders(config):
82
+ dc = config["data"]
83
+ tc = config["training"]
84
+ mc = config["model"]
85
+
86
+ # Sửa lỗi KeyError: Thử lấy 'encoder_model', nếu không có thì lấy 'encoder_model_name'
87
+ model_name = mc.get("encoder_model") or mc.get("encoder_model_name")
88
+
89
+ if not model_name:
90
+ raise KeyError("Config file thiếu key 'encoder_model' hoặc 'encoder_model_name' trong phần 'model'")
91
+
92
+ print(f"Initializing tokenizer from: {model_name}")
93
+ tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
94
+
95
+ if tokenizer.pad_token is None:
96
+ tokenizer.pad_token = tokenizer.eos_token
97
+
98
+ pt_path = dc["data_dir"]
99
+
100
+ train_ds = EmbeddingInversionDataset(
101
+ pt_path, tokenizer,
102
+ max_seq_len=mc["max_seq_len"],
103
+ val=False, val_split=dc["val_split"]
104
+ )
105
+ val_ds = EmbeddingInversionDataset(
106
+ pt_path, tokenizer,
107
+ max_seq_len=mc["max_seq_len"],
108
+ val=True, val_split=dc["val_split"]
109
+ )
110
+
111
+ train_loader = DataLoader(
112
+ train_ds, batch_size=tc["batch_size"], shuffle=True,
113
+ num_workers=tc["num_workers"], pin_memory=True, drop_last=True
114
+ )
115
+ val_loader = DataLoader(
116
+ val_ds, batch_size=tc["batch_size"], shuffle=False,
117
+ num_workers=tc["num_workers"], pin_memory=True
118
+ )
119
+
120
+ return train_loader, val_loader
demo/apple-touch-icon.png ADDED

Git LFS Details

  • SHA256: d58c99dd6ccc154c416ce9ecb6dc65017e44eb2ec9f245586ea473b706828bbe
  • Pointer size: 130 Bytes
  • Size of remote file: 37.4 kB
demo/favicon-32.png ADDED

Git LFS Details

  • SHA256: bdce7b20c4a2ea803f764f62d2819f2fb41ee9c7b83496d4e199420b19989c18
  • Pointer size: 129 Bytes
  • Size of remote file: 2.05 kB
demo/index.html ADDED
@@ -0,0 +1,464 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <link rel="icon" type="image/png" href="/favicon-32.png">
7
+ <meta property="og:type" content="website">
8
+ <meta property="og:title" content="Embedding Inversion via Conditional Masked Diffusion">
9
+ <meta property="og:description" content="Reconstruct original text from embedding vectors using conditional masked diffusion. Live interactive demo.">
10
+ <meta property="og:image" content="https://embedding-inversion-demo.jina.ai/og-image.png">
11
+ <meta property="og:url" content="https://embedding-inversion-demo.jina.ai">
12
+ <meta name="twitter:card" content="summary_large_image">
13
+ <meta name="twitter:title" content="Embedding Inversion via Conditional Masked Diffusion">
14
+ <meta name="twitter:description" content="Reconstruct original text from embedding vectors using conditional masked diffusion. Live interactive demo.">
15
+ <meta name="twitter:image" content="https://embedding-inversion-demo.jina.ai/og-image.png">
16
+ <meta name="twitter:creator" content="@hxiao">
17
+ <title>Embedding Inversion via Conditional Masked Diffusion</title>
18
+ <style>
19
+ *,*::before,*::after{margin:0;padding:0;box-sizing:border-box}
20
+ :root{
21
+ --bg:#fafafa;--surface:#fff;--border:#d8d8d8;
22
+ --text:#1a1a2e;--dim:#666;--accent:#e17055;
23
+ --green:#00b894;--mask:#c0c0c0;
24
+ --mono:"Berkeley Mono","JetBrains Mono","Fira Code",monospace;
25
+ --radius:4px;
26
+ }
27
+ html{font-size:15px}
28
+ body{font-family:var(--mono);background:var(--bg);color:var(--text);min-height:100vh;line-height:1.5}
29
+ ::selection{background:var(--accent);color:#fff}
30
+
31
+ .wrap{max-width:760px;margin:0 auto;padding:2.5rem 1.5rem 3rem}
32
+
33
+ header{text-align:center;margin-bottom:2.5rem}
34
+ h1{font-size:1.6rem;font-weight:600;letter-spacing:-0.01em;color:var(--text)}
35
+ .sub{color:var(--dim);font-size:.8rem;margin-top:.4rem}
36
+ .sub a{color:var(--dim);text-decoration:underline;transition:color .2s}
37
+ .sub a:hover{color:var(--accent)}
38
+
39
+ /* Fieldsets - TurboPuffer style */
40
+ fieldset{
41
+ background:var(--surface);
42
+ border:2px dashed var(--border);
43
+ border-radius:var(--radius);
44
+ padding:1.5rem;
45
+ margin-bottom:1.5rem;
46
+ }
47
+ legend{
48
+ font-size:.65rem;
49
+ text-transform:uppercase;
50
+ letter-spacing:.12em;
51
+ color:var(--dim);
52
+ font-weight:600;
53
+ padding:0 .5rem;
54
+ }
55
+
56
+ /* Model selector - tabs style */
57
+ .model-selector{
58
+ display:inline-flex;gap:0;margin-bottom:1.2rem;
59
+ border:1.5px solid var(--border);border-radius:var(--radius);
60
+ overflow:hidden;
61
+ }
62
+ .model-btn{
63
+ padding:.5rem 1.2rem;
64
+ background:transparent;color:var(--text);
65
+ border:none;border-right:1.5px solid var(--border);
66
+ font-family:var(--mono);font-size:.75rem;font-weight:600;
67
+ cursor:pointer;transition:all .2s;text-align:center;
68
+ letter-spacing:.02em;
69
+ }
70
+ .model-btn:last-child{border-right:none}
71
+ .model-btn:hover{background:#f5f5f5}
72
+ .model-btn.active{
73
+ background:var(--accent);color:#fff;
74
+ }
75
+
76
+ /* input area */
77
+ .input-row{position:relative;display:flex;align-items:center}
78
+ .input-row input{
79
+ width:100%;padding:.65rem 2.5rem .65rem .8rem;
80
+ border:1.5px solid var(--border);border-radius:var(--radius);
81
+ font-family:var(--mono);font-size:.85rem;
82
+ background:var(--surface);color:var(--text);outline:none;
83
+ transition:border-color .2s;
84
+ }
85
+ .input-row input:focus{border-color:var(--accent)}
86
+ .input-row input::placeholder{color:#aaa;font-style:italic}
87
+ .dice{
88
+ position:absolute;right:8px;top:50%;transform:translateY(-50%);
89
+ background:none;border:none;cursor:pointer;font-size:1.1rem;
90
+ opacity:.4;transition:opacity .15s;
91
+ }
92
+ .dice:hover{opacity:.8}
93
+
94
+ /* buttons - outlined style */
95
+ .btn{
96
+ display:inline-block;padding:.55rem 1.4rem;
97
+ background:transparent;color:var(--accent);
98
+ border:1.5px solid var(--accent);border-radius:var(--radius);
99
+ font-family:var(--mono);font-size:.8rem;font-weight:600;
100
+ cursor:pointer;transition:all .15s;margin-top:.8rem;
101
+ letter-spacing:.02em;
102
+ }
103
+ .btn:hover{background:var(--accent);color:#fff}
104
+ .btn:disabled{opacity:.3;cursor:not-allowed}
105
+ .btn.btn-primary{
106
+ background:var(--accent);color:#fff;
107
+ }
108
+ .btn.btn-primary:hover{background:#c0543d}
109
+
110
+ /* embedding viz */
111
+ #embed-result{display:none}
112
+ .stats-row{
113
+ display:flex;gap:1.5rem;font-size:.75rem;
114
+ color:var(--dim);margin-bottom:.8rem;flex-wrap:wrap;
115
+ }
116
+ .stats-row span{white-space:nowrap}
117
+ .stats-row .val{color:var(--text);font-weight:600;margin-left:.3rem}
118
+
119
+ canvas#histogram{width:100%;height:110px;border-radius:var(--radius);background:var(--surface);border:1.5px solid var(--border)}
120
+
121
+ /* invert section */
122
+ #invert-section{display:none}
123
+ #invert-result{display:none}
124
+
125
+ /* token grid */
126
+ .token-grid{
127
+ display:flex;flex-wrap:wrap;gap:5px;
128
+ font-size:.8rem;
129
+ margin-top:.8rem;
130
+ }
131
+ .token{
132
+ padding:3px 7px;border-radius:3px;
133
+ transition:all .25s ease;
134
+ border:1px solid transparent;
135
+ }
136
+ .token.masked{background:#f0f0f0;color:var(--mask);border-color:var(--border)}
137
+ .token.revealed{background:var(--surface);color:var(--text);font-weight:600;border-color:var(--border)}
138
+ .token.just-changed{
139
+ background:#fde8e2;color:var(--accent);font-weight:700;
140
+ border-color:var(--accent);
141
+ animation:pop .3s ease;
142
+ }
143
+ @keyframes pop{0%{transform:scale(1.12)}100%{transform:scale(1)}}
144
+
145
+ /* comparison */
146
+ .compare{margin-top:1.2rem;font-size:.8rem}
147
+ .compare-row{display:flex;gap:.6rem;margin-bottom:.5rem;align-items:baseline}
148
+ .compare-label{font-size:.65rem;text-transform:uppercase;letter-spacing:.1em;color:var(--dim);width:85px;flex-shrink:0;font-weight:600}
149
+ .compare-text{color:var(--text)}
150
+
151
+ .metric{
152
+ display:inline-flex;align-items:center;gap:.4rem;
153
+ font-size:.75rem;color:var(--dim);
154
+ margin-top:.6rem;
155
+ }
156
+ .metric .val{color:var(--green);font-weight:700;font-size:.9rem}
157
+
158
+ .step-info{font-size:.7rem;color:var(--dim);margin-top:.6rem}
159
+
160
+ /* progress */
161
+ .progress-bar{height:2px;background:#e5e5e5;border-radius:1px;margin-top:.6rem;overflow:hidden}
162
+ .progress-fill{height:100%;background:var(--accent);border-radius:1px;transition:width .15s;width:0%}
163
+
164
+ footer{text-align:center;margin-top:2.5rem;font-size:.7rem;color:var(--dim);border-top:1px solid var(--border);padding-top:1.5rem}
165
+ footer a{color:var(--dim);text-decoration:underline}
166
+ footer a:hover{color:var(--accent)}
167
+ </style>
168
+ </head>
169
+ <body>
170
+ <div class="wrap">
171
+
172
+ <header>
173
+ <h1>Embedding Inversion via Conditional Masked Diffusion <a href="https://github.com/jina-ai/embedding-inversion-demo" target="_blank" title="GitHub" style="color:var(--dim);transition:color .2s;text-decoration:none;vertical-align:middle;margin-left:.2rem" onmouseover="this.style.color='var(--accent)'" onmouseout="this.style.color='var(--dim)'"><svg width="18" height="18" viewBox="0 0 16 16" fill="currentColor" style="vertical-align:middle;position:relative;top:-2px"><path d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0016 8c0-4.42-3.58-8-8-8z"/></svg></a><a href="https://github.com/jina-ai/embedding-inversion-demo/blob/main/technical-report.pdf" target="_blank" title="Paper" style="color:var(--dim);transition:color .2s;text-decoration:none;vertical-align:middle;margin-left:.3rem" onmouseover="this.style.color='var(--accent)'" onmouseout="this.style.color='var(--dim)'"><svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor" style="vertical-align:middle;position:relative;top:-2px"><path d="M14 2H6c-1.1 0-2 .9-2 2v16c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V8l-6-6zm4 18H6V4h7v5h5v11zM9 13h6v2H9v-2zm0 4h6v2H9v-2zm0-8h3v2H9V9z"/></svg></a></h1>
174
+ </header>
175
+
176
+ <!-- Step 1: Input & Embed -->
177
+ <fieldset>
178
+ <legend>Input</legend>
179
+
180
+ <!-- Model selector -->
181
+ <div class="model-selector">
182
+ <button class="model-btn active" onclick="selectModel('qwen3')">Qwen3-Embedding</button>
183
+ <button class="model-btn" onclick="selectModel('gemma')">EmbeddingGemma</button>
184
+ </div>
185
+
186
+ <div class="input-row">
187
+ <input type="text" id="input-text" placeholder="Enter a sentence..." maxlength="1000" />
188
+ <button class="dice" onclick="randomSentence()" title="Random sentence">&#x1F3B2;</button>
189
+ </div>
190
+ <button class="btn btn-primary" id="btn-embed" onclick="doEmbed()">Embed</button>
191
+ </fieldset>
192
+
193
+ <!-- Embedding Result -->
194
+ <fieldset id="embed-result">
195
+ <legend>Embedding</legend>
196
+ <div class="stats-row">
197
+ <span>dim <span class="val" id="stat-dim">-</span></span>
198
+ <span>min <span class="val" id="stat-min">-</span></span>
199
+ <span>max <span class="val" id="stat-max">-</span></span>
200
+ <span>norm <span class="val" id="stat-norm">-</span></span>
201
+ <span>entropy <span class="val" id="stat-entropy">-</span></span>
202
+ </div>
203
+ <canvas id="histogram"></canvas>
204
+ </fieldset>
205
+
206
+ <!-- Step 2: Invert -->
207
+ <div id="invert-section">
208
+ <fieldset>
209
+ <legend>Diffusion Decoding</legend>
210
+ <button class="btn" id="btn-invert" onclick="doInvert()">Invert</button>
211
+ <div class="progress-bar" id="progress-bar"><div class="progress-fill" id="progress-fill"></div></div>
212
+ <div class="step-info" id="step-info"></div>
213
+
214
+ <div id="invert-result">
215
+ <div class="token-grid" id="token-grid"></div>
216
+
217
+ <div class="compare">
218
+ <div class="compare-row">
219
+ <span class="compare-label">Original</span>
220
+ <span class="compare-text" id="original-text"></span>
221
+ </div>
222
+ <div class="compare-row">
223
+ <span class="compare-label">Recovered</span>
224
+ <span class="compare-text" id="recovered-text"></span>
225
+ </div>
226
+ </div>
227
+
228
+ <div class="metric">
229
+ cosine similarity <span class="val" id="cosine-sim">-</span>
230
+ </div>
231
+ </div>
232
+ </fieldset>
233
+ </div>
234
+
235
+
236
+
237
+ </div>
238
+
239
+ <script>
240
+ let currentEmbedding = null;
241
+ let currentText = '';
242
+ let selectedModel = 'qwen3';
243
+ let diceClicks = 0;
244
+
245
+ const MODEL_NAMES = {
246
+ 'qwen3': 'Qwen3-Embedding',
247
+ 'gemma': 'EmbeddingGemma'
248
+ };
249
+
250
+ function selectModel(model) {
251
+ selectedModel = model;
252
+
253
+ // Update button states
254
+ document.querySelectorAll('.model-btn').forEach(btn => {
255
+ btn.classList.remove('active');
256
+ });
257
+ event.target.classList.add('active');
258
+
259
+ // Update subtitle
260
+ document.getElementById('header-sub').textContent = MODEL_NAMES[model] + ' | Conditional Masked Diffusion';
261
+
262
+ // Reset state if user switches models
263
+ currentEmbedding = null;
264
+ document.getElementById('embed-result').style.display = 'none';
265
+ document.getElementById('invert-section').style.display = 'none';
266
+ }
267
+
268
+ async function randomSentence() {
269
+ diceClicks++;
270
+ const hard = diceClicks > 1 ? '&hard=true' : '';
271
+ const r = await fetch('/random?model=' + selectedModel + hard);
272
+ const d = await r.json();
273
+ document.getElementById('input-text').value = d.text;
274
+ }
275
+
276
+ async function doEmbed() {
277
+ const text = document.getElementById('input-text').value.trim();
278
+ if (!text) return;
279
+ currentText = text;
280
+
281
+ const btn = document.getElementById('btn-embed');
282
+ btn.disabled = true;
283
+ btn.textContent = 'Encoding...';
284
+
285
+ try {
286
+ const r = await fetch('/encode', {
287
+ method: 'POST',
288
+ headers: {'Content-Type': 'application/json'},
289
+ body: JSON.stringify({text, model: selectedModel})
290
+ });
291
+ const d = await r.json();
292
+ currentEmbedding = d.embedding;
293
+
294
+ // Stats
295
+ const arr = d.embedding;
296
+ const min = Math.min(...arr);
297
+ const max = Math.max(...arr);
298
+ const norm = Math.sqrt(arr.reduce((s,v) => s + v*v, 0));
299
+ document.getElementById('stat-dim').textContent = arr.length;
300
+ document.getElementById('stat-min').textContent = min.toFixed(3);
301
+ document.getElementById('stat-max').textContent = max.toFixed(3);
302
+ document.getElementById('stat-norm').textContent = norm.toFixed(2);
303
+ // Shannon entropy of embedding distribution
304
+ const nbins = 50;
305
+ const emin = Math.min(...arr); const emax = Math.max(...arr);
306
+ const bw = (emax - emin) / nbins || 1;
307
+ const bins = new Array(nbins).fill(0);
308
+ arr.forEach(v => { const b = Math.min(nbins-1, Math.floor((v - emin) / bw)); bins[b]++; });
309
+ const n = arr.length;
310
+ const entropy = -bins.filter(b=>b>0).reduce((s,b) => s + (b/n)*Math.log2(b/n), 0);
311
+ document.getElementById('stat-entropy').textContent = entropy.toFixed(2);
312
+
313
+ document.getElementById('embed-result').style.display = 'block';
314
+
315
+ // Histogram (draw after element is visible so getBoundingClientRect works)
316
+ requestAnimationFrame(() => drawHistogram(arr));
317
+ document.getElementById('invert-section').style.display = 'block';
318
+
319
+ // Reset invert state
320
+ document.getElementById('invert-result').style.display = 'none';
321
+ document.getElementById('progress-fill').style.width = '0%';
322
+ document.getElementById('step-info').textContent = '';
323
+ document.getElementById('btn-invert').disabled = false;
324
+ } catch(e) {
325
+ console.error(e);
326
+ } finally {
327
+ btn.disabled = false;
328
+ btn.textContent = 'Embed';
329
+ }
330
+ }
331
+
332
+ function drawHistogram(arr) {
333
+ const canvas = document.getElementById('histogram');
334
+ const dpr = window.devicePixelRatio || 1;
335
+ const rect = canvas.getBoundingClientRect();
336
+ canvas.width = rect.width * dpr;
337
+ canvas.height = rect.height * dpr;
338
+ const ctx = canvas.getContext('2d');
339
+ ctx.scale(dpr, dpr);
340
+ const W = rect.width, H = rect.height;
341
+
342
+ ctx.clearRect(0, 0, W, H);
343
+
344
+ const nBins = 50;
345
+ const min = Math.min(...arr), max = Math.max(...arr);
346
+ const range = max - min || 1;
347
+ const bins = new Array(nBins).fill(0);
348
+ for (const v of arr) {
349
+ const i = Math.min(Math.floor((v - min) / range * nBins), nBins - 1);
350
+ bins[i]++;
351
+ }
352
+ const maxBin = Math.max(...bins);
353
+
354
+ const pad = {l:0, r:0, t:8, b:0};
355
+ const pw = (W - pad.l - pad.r) / nBins;
356
+
357
+ for (let i = 0; i < nBins; i++) {
358
+ const h = (bins[i] / maxBin) * (H - pad.t - pad.b);
359
+ const x = pad.l + i * pw;
360
+ const y = H - pad.b - h;
361
+
362
+ const t = i / nBins;
363
+ const r2 = Math.round(225 + t * 20);
364
+ const g = Math.round(100 + t * 30);
365
+ const b = Math.round(65 + t * 20);
366
+ ctx.fillStyle = `rgb(${r2},${g},${b})`;
367
+ ctx.fillRect(x, y, pw - 1, h);
368
+ }
369
+ }
370
+
371
+ async function doInvert() {
372
+ if (!currentEmbedding) return;
373
+
374
+ const btn = document.getElementById('btn-invert');
375
+ btn.disabled = true;
376
+ btn.textContent = 'Inverting...';
377
+ document.getElementById('invert-result').style.display = 'block';
378
+ document.getElementById('original-text').textContent = currentText;
379
+ document.getElementById('cosine-sim').textContent = '-';
380
+
381
+ const grid = document.getElementById('token-grid');
382
+ grid.innerHTML = '';
383
+
384
+ let prevTokens = [];
385
+
386
+ try {
387
+ const r = await fetch('/decode', {
388
+ method: 'POST',
389
+ headers: {'Content-Type': 'application/json'},
390
+ body: JSON.stringify({embedding: currentEmbedding, steps: 32, model: selectedModel})
391
+ });
392
+
393
+ const reader = r.body.getReader();
394
+ const decoder = new TextDecoder();
395
+ let buffer = '';
396
+ let totalSteps = 32;
397
+ let stepCount = 0;
398
+
399
+ while (true) {
400
+ const {done, value} = await reader.read();
401
+ if (done) break;
402
+ buffer += decoder.decode(value, {stream: true});
403
+
404
+ const lines = buffer.split('\n');
405
+ buffer = lines.pop();
406
+
407
+ for (const line of lines) {
408
+ if (!line.startsWith('data: ')) continue;
409
+ const raw = line.slice(6).trim();
410
+ if (raw === '[DONE]') continue;
411
+
412
+ try {
413
+ const d = JSON.parse(raw);
414
+ stepCount++;
415
+
416
+ if (d.total) totalSteps = d.total;
417
+ if (d.total_steps) totalSteps = d.total_steps;
418
+ const pct = d.progress ? d.progress * 100 : Math.min(100, (stepCount / totalSteps) * 100);
419
+ document.getElementById('progress-fill').style.width = pct + '%';
420
+ document.getElementById('step-info').textContent = `step ${d.step !== undefined ? d.step + 1 : stepCount}/${totalSteps}`;
421
+
422
+ const tokens = d.tokens || [];
423
+ grid.innerHTML = '';
424
+ for (let i = 0; i < tokens.length; i++) {
425
+ const span = document.createElement('span');
426
+ // tokens can be objects {t: text, s: state} or strings
427
+ const tok = typeof tokens[i] === 'object' ? tokens[i] : {t: tokens[i], s: 'u'};
428
+ const text = tok.t || '';
429
+ const isMask = text === '[MASK]' || text === '<mask>' || tok.s === 'm';
430
+ const changed = tok.s === 'c' || (prevTokens[i] && prevTokens[i] !== text && !isMask);
431
+
432
+ span.className = 'token ' + (isMask ? 'masked' : (changed ? 'just-changed' : 'revealed'));
433
+ span.textContent = isMask ? '\u2588' : text;
434
+ grid.appendChild(span);
435
+ }
436
+ prevTokens = tokens.map(t => typeof t === 'object' ? t.t : t);
437
+
438
+ if (d.cosine_similarity !== undefined) {
439
+ document.getElementById('cosine-sim').textContent = d.cosine_similarity.toFixed(4);
440
+ } else if (d.cosine_sim !== undefined) {
441
+ document.getElementById('cosine-sim').textContent = d.cosine_sim.toFixed(4);
442
+ }
443
+ if (d.text) {
444
+ document.getElementById('recovered-text').textContent = d.text;
445
+ }
446
+ } catch(e) {}
447
+ }
448
+ }
449
+
450
+ document.getElementById('progress-fill').style.width = '100%';
451
+ document.getElementById('step-info').textContent = `done (${totalSteps} steps)`;
452
+ } catch(e) {
453
+ console.error(e);
454
+ } finally {
455
+ btn.disabled = false;
456
+ btn.textContent = 'Invert';
457
+ }
458
+ }
459
+
460
+ // Auto-load random on page load
461
+ window.addEventListener('load', randomSentence);
462
+ </script>
463
+ </body>
464
+ </html>
demo/og-image.png ADDED

Git LFS Details

  • SHA256: 1aa1678842fc446e0dd687283d3605d0ca3d734433c73a19c61c4e65f045bbc2
  • Pointer size: 131 Bytes
  • Size of remote file: 900 kB
demo_server.py ADDED
@@ -0,0 +1,602 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Interactive Embedding Inversion Demo Server - Multi-Model Support.
4
+ Runs on port 8080. Serves a TurboPuffer-style dark UI for real-time diffusion visualization.
5
+
6
+ Supports both Qwen3-Embedding and EmbeddingGemma models.
7
+ """
8
+
9
+ import sys
10
+ import os
11
+ import pickle
12
+ import yaml
13
+ import json
14
+ import math
15
+ import random
16
+ import asyncio
17
+ import time
18
+ from pathlib import Path
19
+
20
+ import torch
21
+ import torch.nn as nn
22
+ import torch.nn.functional as F
23
+ from transformers import AutoModel, AutoTokenizer
24
+ from fastapi import FastAPI, Request
25
+ from fastapi.middleware.cors import CORSMiddleware
26
+ from starlette.responses import JSONResponse
27
+ from fastapi.responses import HTMLResponse, StreamingResponse, FileResponse
28
+ from pydantic import BaseModel
29
+ from typing import List, Optional
30
+
31
+ # ---------------------------------------------------------------------------
32
+ # Model architecture (matches checkpoint state_dict exactly)
33
+ # ---------------------------------------------------------------------------
34
+
35
+ class AdaLN(nn.Module):
36
+ """Adaptive LayerNorm: norm(x) * (1+scale) + shift, conditioned on cond."""
37
+ def __init__(self, hidden_dim, cond_dim):
38
+ super().__init__()
39
+ self.norm = nn.LayerNorm(hidden_dim, elementwise_affine=False)
40
+ self.proj = nn.Linear(cond_dim, 2 * hidden_dim)
41
+
42
+ def forward(self, x, cond):
43
+ # cond: [B, cond_dim] -> [B, 2*hidden]
44
+ params = self.proj(cond).unsqueeze(1) # [B, 1, 2*hidden]
45
+ scale, shift = params.chunk(2, dim=-1)
46
+ return self.norm(x) * (1 + scale) + shift
47
+
48
+
49
+ class Block(nn.Module):
50
+ """Transformer block with AdaLN conditioning."""
51
+ def __init__(self, hidden_dim, num_heads, ff_dim, dropout=0.0):
52
+ super().__init__()
53
+ self.adaln1 = AdaLN(hidden_dim, hidden_dim)
54
+ self.attn = nn.MultiheadAttention(hidden_dim, num_heads, dropout=dropout, batch_first=True)
55
+ self.adaln2 = AdaLN(hidden_dim, hidden_dim)
56
+ self.ff = nn.Sequential(
57
+ nn.Linear(hidden_dim, ff_dim),
58
+ nn.GELU(),
59
+ nn.Dropout(dropout),
60
+ nn.Linear(ff_dim, hidden_dim),
61
+ )
62
+
63
+ def forward(self, x, cond):
64
+ # Self-attention with AdaLN
65
+ normed = self.adaln1(x, cond)
66
+ attn_out, _ = self.attn(normed, normed, normed, need_weights=False)
67
+ x = x + attn_out
68
+ # Feed-forward with AdaLN
69
+ normed = self.adaln2(x, cond)
70
+ x = x + self.ff(normed)
71
+ return x
72
+
73
+
74
+ class ConditionalMDLM(nn.Module):
75
+ """Conditional Masked Diffusion Language Model - matches checkpoint exactly."""
76
+ def __init__(self, config):
77
+ super().__init__()
78
+ mc = config["model"]
79
+ self.vocab_size = mc["vocab_size"]
80
+ self.hidden_dim = mc["hidden_dim"]
81
+ self.max_seq_len = mc["max_seq_len"]
82
+ self.mask_token_id = mc["mask_token_id"]
83
+
84
+ self.token_embed = nn.Embedding(self.vocab_size, self.hidden_dim)
85
+ self.pos_embed = nn.Embedding(self.max_seq_len, self.hidden_dim)
86
+ self.cond_proj = nn.Sequential(
87
+ nn.Linear(mc["embedding_cond_dim"], self.hidden_dim),
88
+ nn.GELU(),
89
+ nn.Linear(self.hidden_dim, self.hidden_dim),
90
+ )
91
+ self.blocks = nn.ModuleList([
92
+ Block(self.hidden_dim, mc["num_heads"], mc["ff_dim"], mc.get("dropout", 0.0))
93
+ for _ in range(mc["num_layers"])
94
+ ])
95
+ self.final_norm = AdaLN(self.hidden_dim, self.hidden_dim)
96
+ self.output_proj = nn.Linear(self.hidden_dim, self.vocab_size, bias=False)
97
+
98
+ def forward(self, input_ids, cond_embedding, padding_mask=None):
99
+ B, L = input_ids.shape
100
+ positions = torch.arange(L, device=input_ids.device).unsqueeze(0)
101
+ x = self.token_embed(input_ids) + self.pos_embed(positions)
102
+ cond = self.cond_proj(cond_embedding)
103
+ for block in self.blocks:
104
+ x = block(x, cond)
105
+ x = self.final_norm(x, cond)
106
+ return self.output_proj(x)
107
+
108
+
109
+ # ---------------------------------------------------------------------------
110
+ # Encoder helper
111
+ # ---------------------------------------------------------------------------
112
+
113
+ def last_token_pool(hidden, attention_mask):
114
+ """Pool using last non-padding token (Qwen3-Embedding style)."""
115
+ left_padding = attention_mask[:, -1].sum() == attention_mask.shape[0]
116
+ if left_padding:
117
+ return hidden[:, -1]
118
+ seq_lens = attention_mask.sum(dim=1) - 1
119
+ return hidden[torch.arange(hidden.shape[0], device=hidden.device), seq_lens]
120
+
121
+
122
+ def mean_pool(hidden, attention_mask):
123
+ m = attention_mask.unsqueeze(-1).expand(hidden.size()).float()
124
+ return (hidden * m).sum(1) / m.sum(1).clamp(min=1e-9)
125
+
126
+ def get_pool_fn(model_name):
127
+ if "qwen" in model_name.lower():
128
+ return last_token_pool
129
+ return mean_pool
130
+
131
+ # ---------------------------------------------------------------------------
132
+ # Globals - Multi-model support + Concurrency Control
133
+ # ---------------------------------------------------------------------------
134
+
135
+ app = FastAPI()
136
+
137
+ # CORS: only allow our domain
138
+ app.add_middleware(
139
+ CORSMiddleware,
140
+ allow_origins=["https://embedding-inversion-demo.jina.ai"],
141
+ allow_methods=["GET", "POST"],
142
+ allow_headers=["Content-Type"],
143
+ )
144
+
145
+ ALLOWED_ORIGINS = {
146
+ "https://embedding-inversion-demo.jina.ai",
147
+ "http://localhost:8080",
148
+ "http://127.0.0.1:8080",
149
+ }
150
+
151
+ @app.middleware("http")
152
+ async def check_browser_request(request: Request, call_next):
153
+ # Skip health/queue checks
154
+ if request.url.path in ("/health", "/queue", "/", "/favicon.ico"):
155
+ return await call_next(request)
156
+
157
+ # Check origin or referer
158
+ origin = request.headers.get("origin", "")
159
+ referer = request.headers.get("referer", "")
160
+
161
+ origin_ok = any(origin.startswith(o) for o in ALLOWED_ORIGINS) if origin else False
162
+ referer_ok = any(referer.startswith(o) for o in ALLOWED_ORIGINS) if referer else False
163
+
164
+ # Also allow requests with no origin/referer (same-origin page load)
165
+ is_page_load = not origin and not referer and request.method == "GET"
166
+
167
+ if not origin_ok and not referer_ok and not is_page_load:
168
+ return JSONResponse(
169
+ status_code=403,
170
+ content={"error": "API access not allowed. Use the web interface."}
171
+ )
172
+
173
+ return await call_next(request)
174
+
175
+ # Each model has its own: MODEL, CONFIG, ENCODER_MODEL, ENCODER_TOK, DECODER_TOK
176
+ MODELS = {} # model_key -> dict with model, config, encoder_model, encoder_tok, decoder_tok
177
+ DEVICE = None
178
+
179
+ # Concurrency control
180
+ ENCODE_SEM = asyncio.Semaphore(8) # encode is fast, allow 4 concurrent
181
+ DECODE_SEM = asyncio.Semaphore(6) # decode has 32 steps, allow 3 concurrent
182
+ ACTIVE_COUNT = 0
183
+ WAITING_COUNT = 0
184
+ count_lock = asyncio.Lock()
185
+
186
+ # Model configurations
187
+ MODEL_CONFIGS = {
188
+ "qwen3": {
189
+ "checkpoint_path": str(Path.home() / "checkpoints" / "qwen3_best.pt"),
190
+ "config_path": "configs/v2_qwen3.yaml",
191
+ },
192
+ "gemma": {
193
+ "checkpoint_path": str(Path.home() / "checkpoints" / "gemma_best.pt"),
194
+ "config_path": "configs/v2_gemma.yaml",
195
+ },
196
+ }
197
+
198
+ SAMPLE_SENTENCES_QWEN3_EASY = [
199
+ "The coldest winter I ever spent was a summer in San Francisco, said Mark Twain",
200
+ "Napoleon marched his Grand Army from Paris to Moscow in the winter of 1812",
201
+ "The Great Wall of China stretches over 13,000 miles from Dandong to Lop Lake",
202
+ "Albert Einstein developed the theory of relativity while working in Bern, Switzerland",
203
+ "The Titanic sank in the North Atlantic Ocean after hitting an iceberg in April 1912",
204
+ "Neil Armstrong landed on the Moon at the Sea of Tranquility on July 20, 1969",
205
+ "The Berlin Wall fell on November 9, 1989, reuniting East and West Germany",
206
+ "Amazon was founded by Jeff Bezos in his garage in Bellevue, Washington in 1994",
207
+ "The Eiffel Tower in Paris was built by Gustave Eiffel for the 1889 World Fair",
208
+ "Marco Polo traveled from Venice to China along the Silk Road in the 13th century",
209
+ "The Panama Canal connects the Atlantic Ocean to the Pacific Ocean across Panama",
210
+ "Steve Jobs unveiled the first iPhone at Moscone Center in San Francisco in 2007",
211
+ "Mount Everest stands at 8,849 meters on the border between Nepal and Tibet",
212
+ "The Treaty of Versailles was signed near Paris, France on June 28, 1919",
213
+ "SpaceX launched its first Falcon 9 rocket from Cape Canaveral, Florida in 2010",
214
+ ]
215
+
216
+ SAMPLE_SENTENCES_QWEN3_HARD = [
217
+ "is this a pigeon? no it is a transformer model",
218
+ "i asked chatgpt to write my resignation letter and it was too polite",
219
+ "my embeddings are not aligned and neither is my sleep schedule",
220
+ "sir this is a vector database not a therapy session",
221
+ "instructions unclear, model started generating poetry",
222
+ "me: i will go to bed early. also me at 3am: reading arxiv papers",
223
+ "nobody: absolutely nobody: AI twitter: we need to talk about scaling laws",
224
+ "OpenAI announces GPT-5 while researchers debate if benchmarks even matter",
225
+ "NVIDIA stock hits new high as demand for H100 GPUs continues to outpace supply",
226
+ "Google DeepMind achieves breakthrough in protein structure prediction",
227
+ "the mitochondria is the powerhouse of the cell and I still remember that",
228
+ "according to all known laws of aviation a bee should not be able to fly",
229
+ "you miss 100 percent of the shots you do not take says Wayne Gretzky",
230
+ "404 meaning of life not found try again after coffee",
231
+ "rm -rf is not a valid debugging strategy no matter what stackoverflow says",
232
+ ]
233
+
234
+ SAMPLE_SENTENCES_GEMMA_EASY = [
235
+ "The coldest winter I ever spent was a summer in San Francisco, said Mark Twain",
236
+ "Napoleon marched his Grand Army from Paris to Moscow in the winter of 1812",
237
+ "The Great Wall of China stretches over 13,000 miles from Dandong to Lop Lake",
238
+ "Albert Einstein developed the theory of relativity while working in Bern, Switzerland",
239
+ "The Titanic sank in the North Atlantic Ocean after hitting an iceberg in April 1912",
240
+ "Neil Armstrong landed on the Moon at the Sea of Tranquility on July 20, 1969",
241
+ "Amazon was founded by Jeff Bezos in his garage in Bellevue, Washington in 1994",
242
+ "The Eiffel Tower in Paris was built by Gustave Eiffel for the 1889 World Fair",
243
+ "Marco Polo traveled from Venice to China along the Silk Road in the 13th century",
244
+ "Mount Everest stands at 8,849 meters on the border between Nepal and Tibet",
245
+ ]
246
+
247
+ SAMPLE_SENTENCES_GEMMA_HARD = [
248
+ "Die Kunst des Maschinenlernens liegt in den Daten",
249
+ "L intelligence artificielle transforme notre quotidien",
250
+ "El aprendizaje profundo revoluciona la medicina moderna",
251
+ "La ricerca scientifica apre nuove frontiere ogni giorno",
252
+ "Yapay zeka gunluk hayatimizi derinden etkiliyor",
253
+ "A inteligencia artificial esta revolucionando a pesquisa",
254
+ "Le traitement du langage naturel permet aux machines de comprendre",
255
+ "Los modelos de lenguaje grandes generan texto sorprendentemente coherente",
256
+ "chatgpt wrote my thesis and my professor did not notice anything wrong",
257
+ "the cake is a lie but the embeddings are real",
258
+ "the voyager 1 spacecraft is still sending data from interstellar space",
259
+ "Ich bin ein Berliner said JFK but the model thinks he said donut",
260
+ "selon toutes les lois connues de l aviation une abeille ne devrait pas voler",
261
+ ]
262
+
263
+ SAMPLE_SENTENCES = SAMPLE_SENTENCES_QWEN3_EASY
264
+
265
+
266
+ def load_model(model_key):
267
+ """Load a specific model (qwen3 or gemma)."""
268
+ global DEVICE
269
+
270
+ if DEVICE is None:
271
+ DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
272
+ print(f"Device: {DEVICE}")
273
+
274
+ cfg = MODEL_CONFIGS[model_key]
275
+ print(f"\n{'='*60}")
276
+ print(f"Loading {model_key.upper()} model")
277
+ print(f"{'='*60}")
278
+
279
+ # Load checkpoint
280
+ ckpt_path = cfg["checkpoint_path"]
281
+ print(f"Loading checkpoint {ckpt_path} ...")
282
+ with open(ckpt_path, "rb") as f:
283
+ ckpt = torch.load(f, map_location=DEVICE, pickle_module=pickle)
284
+ config = ckpt["config"]
285
+ print(f" step={ckpt['step']}, val_loss={ckpt['best_val_loss']:.4f}")
286
+ print(f" config: vocab={config['model']['vocab_size']}, "
287
+ f"seq_len={config['model']['max_seq_len']}, "
288
+ f"layers={config['model']['num_layers']}, "
289
+ f"embedding_cond_dim={config['model']['embedding_cond_dim']}")
290
+
291
+ # Create model
292
+ model = ConditionalMDLM(config).to(DEVICE)
293
+ state = {k: v.float() for k, v in ckpt["ema_state_dict"].items()}
294
+ model.load_state_dict(state, strict=True)
295
+ model.eval()
296
+ print(" Model loaded OK")
297
+ del ckpt
298
+
299
+ # Encoder
300
+ enc_name = config["model"]["encoder_model"]
301
+ print(f"Loading encoder: {enc_name} ...")
302
+ encoder_tok = AutoTokenizer.from_pretrained(enc_name, trust_remote_code=True)
303
+ encoder_model = AutoModel.from_pretrained(enc_name, trust_remote_code=True).to(DEVICE).eval()
304
+ print(" Encoder loaded OK")
305
+
306
+ # Decoder tokenizer
307
+ dec_name = config["model"]["decoder_tokenizer"]
308
+ print(f"Loading decoder tokenizer: {dec_name} ...")
309
+ decoder_tok = AutoTokenizer.from_pretrained(dec_name, trust_remote_code=True)
310
+ print(" Decoder tokenizer loaded OK")
311
+
312
+ MODELS[model_key] = {
313
+ "model": model,
314
+ "config": config,
315
+ "encoder_model": encoder_model,
316
+ "encoder_tok": encoder_tok,
317
+ "decoder_tok": decoder_tok,
318
+ }
319
+ print(f"{model_key.upper()} ready")
320
+
321
+
322
+ def load_models():
323
+ """Load all models on startup."""
324
+ for model_key in MODEL_CONFIGS:
325
+ load_model(model_key)
326
+ print("\n" + "="*60)
327
+ print("=== Ready ===")
328
+ print("="*60 + "\n")
329
+
330
+
331
+ # ---------------------------------------------------------------------------
332
+ # Concurrency helpers
333
+ # ---------------------------------------------------------------------------
334
+
335
+ async def increment_active():
336
+ global ACTIVE_COUNT
337
+ async with count_lock:
338
+ ACTIVE_COUNT += 1
339
+
340
+ async def decrement_active():
341
+ global ACTIVE_COUNT
342
+ async with count_lock:
343
+ ACTIVE_COUNT -= 1
344
+
345
+ async def increment_waiting():
346
+ global WAITING_COUNT
347
+ async with count_lock:
348
+ WAITING_COUNT += 1
349
+
350
+ async def decrement_waiting():
351
+ global WAITING_COUNT
352
+ async with count_lock:
353
+ WAITING_COUNT -= 1
354
+
355
+ async def get_queue_status():
356
+ async with count_lock:
357
+ return {"active": ACTIVE_COUNT, "waiting": WAITING_COUNT}
358
+
359
+ # ---------------------------------------------------------------------------
360
+ # API
361
+ # ---------------------------------------------------------------------------
362
+
363
+ class EncodeRequest(BaseModel):
364
+ text: str
365
+ model: str = "qwen3"
366
+
367
+ class DecodeRequest(BaseModel):
368
+ embedding: List[float]
369
+ steps: int = 32
370
+ model: str = "qwen3"
371
+
372
+ class EncodeResponse(BaseModel):
373
+ embedding: List[float]
374
+ text: str
375
+
376
+
377
+ @app.on_event("startup")
378
+ async def startup():
379
+ load_models()
380
+
381
+
382
+ @app.get("/", response_class=HTMLResponse)
383
+ async def index():
384
+ html_path = Path(__file__).parent / "demo" / "index.html"
385
+ return HTMLResponse(html_path.read_text())
386
+
387
+
388
+
389
+
390
+ @app.get("/og-image.png")
391
+ async def og_image():
392
+ return FileResponse(Path(__file__).parent / "demo" / "og-image.png", media_type="image/png", headers={"Cache-Control": "no-cache, max-age=0"})
393
+
394
+ @app.get("/favicon-32.png")
395
+ async def favicon():
396
+ return FileResponse(Path(__file__).parent / "demo" / "favicon-32.png", media_type="image/png", headers={"Cache-Control": "no-cache, max-age=0"})
397
+
398
+ @app.get("/favicon.ico")
399
+ async def favicon_ico():
400
+ return FileResponse(Path(__file__).parent / "demo" / "favicon-32.png", media_type="image/png")
401
+
402
+ @app.get("/queue")
403
+ async def queue_status():
404
+ """Return current queue status for frontend polling."""
405
+ return await get_queue_status()
406
+
407
+
408
+ @app.post("/encode", response_model=EncodeResponse)
409
+ async def encode(req: EncodeRequest):
410
+ model_key = req.model.lower()
411
+ if model_key not in MODELS:
412
+ return {"error": f"Unknown model: {model_key}"}
413
+
414
+ m = MODELS[model_key]
415
+
416
+ # Track waiting
417
+ await increment_waiting()
418
+ start_wait = time.time()
419
+
420
+ try:
421
+ # Wait for semaphore with timeout
422
+ try:
423
+ async with asyncio.timeout(30):
424
+ async with ENCODE_SEM:
425
+ await decrement_waiting()
426
+ await increment_active()
427
+ try:
428
+ with torch.no_grad():
429
+ inputs = m["encoder_tok"](
430
+ [req.text], return_tensors="pt",
431
+ padding=True, truncation=True, max_length=512
432
+ ).to(DEVICE)
433
+ out = m["encoder_model"](**inputs)
434
+ pool_fn = get_pool_fn(m["config"]["model"]["encoder_model"])
435
+ emb = pool_fn(out.last_hidden_state, inputs["attention_mask"])
436
+ emb = F.normalize(emb, dim=-1)
437
+ return EncodeResponse(embedding=emb[0].cpu().tolist(), text=req.text)
438
+ finally:
439
+ await decrement_active()
440
+ except asyncio.TimeoutError:
441
+ await decrement_waiting()
442
+ raise HTTPException(
443
+ status_code=503,
444
+ detail="Server busy, please try again in a moment"
445
+ )
446
+ except HTTPException:
447
+ raise
448
+ except Exception as e:
449
+ await decrement_waiting()
450
+ raise
451
+
452
+
453
+ @app.post("/decode")
454
+ async def decode(req: DecodeRequest):
455
+ model_key = req.model.lower()
456
+ if model_key not in MODELS:
457
+ return {"error": f"Unknown model: {model_key}"}
458
+
459
+ m = MODELS[model_key]
460
+ model = m["model"]
461
+ config = m["config"]
462
+ encoder_model = m["encoder_model"]
463
+ encoder_tok = m["encoder_tok"]
464
+ decoder_tok = m["decoder_tok"]
465
+
466
+ async def generate():
467
+ # Track waiting
468
+ await increment_waiting()
469
+
470
+ try:
471
+ # Wait for semaphore with timeout
472
+ try:
473
+ async with asyncio.timeout(30):
474
+ async with DECODE_SEM:
475
+ await decrement_waiting()
476
+ await increment_active()
477
+ try:
478
+ embedding = torch.tensor([req.embedding], device=DEVICE, dtype=torch.float32)
479
+ embedding = F.normalize(embedding, dim=-1)
480
+
481
+ L = m["config"]["model"]["max_seq_len"]
482
+ mask_id = m["config"]["model"]["mask_token_id"]
483
+ steps = max(1, min(req.steps, L))
484
+ per_step = max(1, L // steps)
485
+
486
+ ids = torch.full((1, L), mask_id, dtype=torch.long, device=DEVICE)
487
+ unmasked = torch.zeros(L, dtype=torch.bool, device=DEVICE)
488
+
489
+ with torch.no_grad():
490
+ for step in range(steps):
491
+ if unmasked.all():
492
+ break
493
+
494
+ logits = model(ids, embedding)
495
+ probs = F.softmax(logits[0], dim=-1)
496
+ confidence, preds = probs.max(dim=-1)
497
+ confidence[unmasked] = -1.0
498
+
499
+ k = min(per_step, (~unmasked).sum().item())
500
+ if k == 0:
501
+ break
502
+ _, topk = confidence.topk(k)
503
+ topk_set = set(topk.cpu().tolist())
504
+
505
+ ids[0, topk] = preds[topk]
506
+ unmasked[topk] = True
507
+
508
+ # Build per-token info
509
+ tokens = []
510
+ for i in range(L):
511
+ tid = ids[0, i].item()
512
+ if tid == mask_id:
513
+ tokens.append({"t": "[MASK]", "s": "m"}) # masked
514
+ else:
515
+ tok_text = decoder_tok.decode([tid])
516
+ state = "c" if i in topk_set else "u" # changed / unchanged
517
+ tokens.append({"t": tok_text, "s": state})
518
+
519
+ # Decode full text (skip mask tokens)
520
+ clean = [t for t in ids[0].cpu().tolist() if t != mask_id]
521
+ text = decoder_tok.decode(clean, skip_special_tokens=True)
522
+
523
+ evt = {
524
+ "step": step,
525
+ "total": steps,
526
+ "tokens": tokens,
527
+ "text": text,
528
+ "progress": float(unmasked.sum().item()) / L,
529
+ }
530
+ yield f"data: {json.dumps(evt)}\n\n"
531
+ await asyncio.sleep(0.08)
532
+
533
+ # Final: compute cosine similarity by re-encoding decoded text
534
+ clean = [t for t in ids[0].cpu().tolist() if t != mask_id]
535
+ final_text = decoder_tok.decode(clean, skip_special_tokens=True)
536
+
537
+ with torch.no_grad():
538
+ inputs2 = encoder_tok(
539
+ [final_text], return_tensors="pt",
540
+ padding=True, truncation=True, max_length=512
541
+ ).to(DEVICE)
542
+ out2 = encoder_model(**inputs2)
543
+ pool_fn2 = get_pool_fn(m["config"]["model"]["encoder_model"])
544
+ emb2 = pool_fn2(out2.last_hidden_state, inputs2["attention_mask"])
545
+ emb2 = F.normalize(emb2, dim=-1)
546
+ cos_sim = F.cosine_similarity(embedding, emb2).item()
547
+
548
+ # Build final token list
549
+ tokens = []
550
+ for i in range(L):
551
+ tid = ids[0, i].item()
552
+ if tid == mask_id:
553
+ tokens.append({"t": "[MASK]", "s": "m"})
554
+ else:
555
+ tokens.append({"t": decoder_tok.decode([tid]), "s": "u"})
556
+
557
+ evt = {
558
+ "step": steps,
559
+ "total": steps,
560
+ "tokens": tokens,
561
+ "text": final_text,
562
+ "progress": 1.0,
563
+ "cosine_similarity": round(cos_sim, 4),
564
+ "done": True,
565
+ }
566
+ yield f"data: {json.dumps(evt)}\n\n"
567
+ finally:
568
+ await decrement_active()
569
+ except asyncio.TimeoutError:
570
+ await decrement_waiting()
571
+ yield f"data: {json.dumps({'error': 'Server busy, please try again in a moment'})}\n\n"
572
+ return
573
+ except Exception as e:
574
+ await decrement_waiting()
575
+ yield f"data: {json.dumps({'error': str(e)})}\n\n"
576
+
577
+ return StreamingResponse(generate(), media_type="text/event-stream")
578
+
579
+
580
+ @app.get("/random")
581
+ async def get_random(model: str = "qwen3", hard: bool = False):
582
+ if model.lower() == "gemma":
583
+ pool = SAMPLE_SENTENCES_GEMMA_HARD if hard else SAMPLE_SENTENCES_GEMMA_EASY
584
+ else:
585
+ pool = SAMPLE_SENTENCES_QWEN3_HARD if hard else SAMPLE_SENTENCES_QWEN3_EASY
586
+ return {"text": random.choice(pool)}
587
+
588
+
589
+ @app.get("/health")
590
+ async def health():
591
+ queue = await get_queue_status()
592
+ return {
593
+ "status": "ok",
594
+ "device": str(DEVICE),
595
+ "models": list(MODELS.keys()),
596
+ "queue": queue
597
+ }
598
+
599
+
600
+ if __name__ == "__main__":
601
+ import uvicorn
602
+ uvicorn.run(app, host="0.0.0.0", port=8080, log_level="info")
get_model_in_text.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ def export_files_to_txt(file_list, output_file):
4
+ # Các đuôi file văn bản phổ biến
5
+ text_extensions = {'.py', '.txt', '.md', '.json', '.yaml', '.yml', '.c', '.cpp', '.h', '.sql', '.html', '.css', '.js'}
6
+
7
+ with open(output_file, 'w', encoding='utf-8') as outfile:
8
+ for file_path in file_list:
9
+ # Kiểm tra file có tồn tại không
10
+ if not os.path.exists(file_path):
11
+ outfile.write(f"[LỖI] File không tồn tại: {file_path}\n\n")
12
+ continue
13
+
14
+ # Kiểm tra định dạng file
15
+ _, ext = os.path.splitext(file_path)
16
+ if ext.lower() in text_extensions:
17
+ try:
18
+ with open(file_path, 'r', encoding='utf-8') as infile:
19
+ content = infile.read()
20
+
21
+ outfile.write(f"{'='*80}\n")
22
+ outfile.write(f"FILE PATH: {file_path}\n")
23
+ outfile.write(f"{'='*80}\n\n")
24
+ outfile.write(content)
25
+ outfile.write("\n\n")
26
+
27
+ except Exception as e:
28
+ outfile.write(f"[LỖI] Không thể đọc file {file_path}: {e}\n\n")
29
+ else:
30
+ outfile.write(f"[BỎ QUA] Định dạng file không hỗ trợ: {file_path}\n\n")
31
+
32
+ print(f"Xong! Nội dung đã được lưu vào: {output_file}")
33
+
34
+ # --- Cấu hình danh sách file ở đây ---
35
+ files_to_export = [
36
+ '/kaggle/embedding-inversion-demo/dataset.py',
37
+ '/kaggle/embedding-inversion-demo/configs/v2_qwen3.yaml',
38
+ '/kaggle/embedding-inversion-demo/model.py',
39
+ '/kaggle/embedding-inversion-demo/train.py'
40
+ ]
41
+
42
+ file_out = '/kaggle/embedding-inversion-demo/prompt.txt'
43
+ export_files_to_txt(files_to_export, file_out)
hf_data_download.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from huggingface_hub import hf_hub_download
2
+
3
+ # Ví dụ: tải file "metadata.csv" từ dataset "nội_dung_dataset"
4
+ file_path = hf_hub_download(
5
+ repo_id="doannv/omegabook_embs",
6
+ filename="omega_books_500k_32.pt",
7
+ repo_type="dataset",
8
+ local_dir="."
9
+ )
10
+
11
+ print(f"File đã được tải về tại: {file_path}")
hf_download.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from huggingface_hub import snapshot_download
2
+
3
+ # Cấu hình các tham số
4
+ repo_id = "doannv/dmlm_inv"
5
+ local_dir = "/kaggle/embedding-inversion-demo" # Thư mục đích trên Kaggle
6
+
7
+ # Tải toàn bộ repo
8
+ snapshot_download(
9
+ repo_id=repo_id,
10
+ repo_type="dataset",
11
+ local_dir=local_dir,
12
+ max_workers=8 # Tăng số luồng để tải nhanh hơn
13
+ )
14
+
15
+ print(f"Đã tải xong dữ liệu về: {local_dir}")
hf_upload.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ from huggingface_hub import HfApi
2
+
3
+ api = HfApi()
4
+
5
+ api.upload_folder(
6
+ folder_path="/kaggle/embedding-inversion-demo",
7
+ repo_id="doannv/dmlm_inv",
8
+ repo_type="dataset",
9
+ ignore_patterns=[".venv/*", "*/.venv/*"], # Loại bỏ thư mục .venv
10
+ )
invert.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Minimal embedding inversion: embedding vector -> text.
4
+ Only depends on: torch, transformers, yaml.
5
+
6
+ Usage:
7
+ python invert.py "any text to test round-trip"
8
+ python invert.py --embedding path/to/embedding.npy
9
+ """
10
+
11
+ import argparse
12
+ import yaml
13
+ import torch
14
+ import torch.nn.functional as F
15
+ from transformers import AutoModel, AutoTokenizer
16
+ from model import ConditionalMDLM
17
+
18
+ CHECKPOINT = "checkpoints/v1_inference_fp16.pt"
19
+
20
+
21
+ def mean_pool(hidden, mask):
22
+ m = mask.unsqueeze(-1).expand(hidden.size()).float()
23
+ return (hidden * m).sum(1) / m.sum(1).clamp(min=1e-9)
24
+
25
+
26
+ @torch.no_grad()
27
+ def invert(embedding, model, config, steps=50):
28
+ """Invert a [1, 1024] embedding back to token ids."""
29
+ device = embedding.device
30
+ L = config["model"]["max_seq_len"]
31
+ mask_id = config["model"]["mask_token_id"]
32
+
33
+ ids = torch.full((1, L), mask_id, dtype=torch.long, device=device)
34
+ unmasked = torch.zeros(L, dtype=torch.bool, device=device)
35
+ per_step = max(1, L // steps)
36
+
37
+ for step in range(steps):
38
+ if unmasked.all():
39
+ break
40
+ logits = model(ids, embedding)
41
+ probs = F.softmax(logits[0], dim=-1)
42
+ confidence, preds = probs.max(dim=-1)
43
+ confidence[unmasked] = -1
44
+ k = min(per_step, (~unmasked).sum().item())
45
+ _, topk = confidence.topk(k)
46
+ ids[0, topk] = preds[topk]
47
+ unmasked[topk] = True
48
+
49
+ return ids[0]
50
+
51
+
52
+ def main():
53
+ parser = argparse.ArgumentParser(description="Invert embeddings to text")
54
+ parser.add_argument("text", nargs="?", help="Text to embed then invert (round-trip test)")
55
+ parser.add_argument("--embedding", help="Path to .npy embedding file")
56
+ parser.add_argument("--checkpoint", default=CHECKPOINT)
57
+ parser.add_argument("--steps", type=int, default=50)
58
+ args = parser.parse_args()
59
+
60
+ if not args.text and not args.embedding:
61
+ parser.error("Provide text or --embedding")
62
+
63
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
64
+
65
+ # Load model
66
+ if args.checkpoint.endswith(".safetensors"):
67
+ from safetensors.torch import load_file as safetensors_load
68
+ import json as _json
69
+ tensors = safetensors_load(args.checkpoint, device=str(device))
70
+ # Read metadata from safetensors header
71
+ from safetensors import safe_open
72
+ with safe_open(args.checkpoint, framework="pt") as f:
73
+ meta = f.metadata()
74
+ config = _json.loads(meta["config_json"])
75
+ model = ConditionalMDLM(config).to(device).eval()
76
+ state = {k: v.float() for k, v in tensors.items()}
77
+ model.load_state_dict(state)
78
+ print(f"Loaded safetensors (step {meta['step']}, val_loss {meta['best_val_loss']})")
79
+ else:
80
+ ckpt = torch.load(args.checkpoint, map_location=device, weights_only=False)
81
+ config = ckpt["config"]
82
+ model = ConditionalMDLM(config).to(device).eval()
83
+ state = ckpt.get("ema_model", ckpt.get("model"))
84
+ state = {k: v.float() for k, v in state.items()}
85
+ model.load_state_dict(state)
86
+ print(f"Loaded checkpoint (step {ckpt['step']}, val_loss {ckpt['best_val_loss']:.4f})")
87
+
88
+ # Get embedding
89
+ if args.text:
90
+ jina_tok = AutoTokenizer.from_pretrained("jinaai/jina-embeddings-v3",
91
+ trust_remote_code=True)
92
+ jina_model = AutoModel.from_pretrained("jinaai/jina-embeddings-v3",
93
+ trust_remote_code=True).to(device).eval()
94
+ inputs = jina_tok([args.text], return_tensors="pt", padding=True,
95
+ truncation=True, max_length=512).to(device)
96
+ out = jina_model(**inputs)
97
+ emb = mean_pool(out.last_hidden_state, inputs["attention_mask"])
98
+ emb = F.normalize(emb, dim=-1)
99
+ print(f"Input: {args.text}")
100
+ else:
101
+ import numpy as np
102
+ emb = torch.from_numpy(np.load(args.embedding)).to(device)
103
+ if emb.dim() == 1:
104
+ emb = emb.unsqueeze(0)
105
+ emb = F.normalize(emb, dim=-1)
106
+
107
+ # Invert
108
+ pred_ids = invert(emb, model, config, steps=args.steps)
109
+ xlmr_tok = AutoTokenizer.from_pretrained("xlm-roberta-base")
110
+ clean = [t for t in pred_ids.cpu().tolist() if t not in (0, 1, config["model"]["mask_token_id"])]
111
+ text = xlmr_tok.decode(clean, skip_special_tokens=True)
112
+ print(f"Output: {text}")
113
+
114
+ # Cosine similarity if round-trip
115
+ if args.text:
116
+ inputs2 = jina_tok([text], return_tensors="pt", padding=True,
117
+ truncation=True, max_length=512).to(device)
118
+ out2 = jina_model(**inputs2)
119
+ emb2 = mean_pool(out2.last_hidden_state, inputs2["attention_mask"])
120
+ emb2 = F.normalize(emb2, dim=-1)
121
+ cos = F.cosine_similarity(emb, emb2).item()
122
+ print(f"Cosine similarity: {cos:.4f}")
123
+
124
+
125
+ if __name__ == "__main__":
126
+ main()
model.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+ from transformers import AutoModel
5
+
6
+ class AdaLNZero(nn.Module):
7
+ def __init__(self, hidden_dim, cond_dim):
8
+ super().__init__()
9
+ self.norm = nn.LayerNorm(hidden_dim, elementwise_affine=False)
10
+ self.proj = nn.Linear(cond_dim, 3 * hidden_dim)
11
+ nn.init.zeros_(self.proj.weight)
12
+ nn.init.zeros_(self.proj.bias)
13
+
14
+ def forward(self, x, cond):
15
+ params = self.proj(cond).unsqueeze(1)
16
+ scale, shift, alpha = params.chunk(3, dim=-1)
17
+ normalized = self.norm(x) * (1 + scale) + shift
18
+ return normalized, alpha
19
+
20
+ class ModernBertLayerWithAdaLN(nn.Module):
21
+ def __init__(self, pretrained_layer, hidden_dim, cond_dim):
22
+ super().__init__()
23
+ self.pretrained_layer = pretrained_layer
24
+ self.cond_proj = nn.Linear(cond_dim, 6 * hidden_dim)
25
+ nn.init.zeros_(self.cond_proj.weight)
26
+ nn.init.zeros_(self.cond_proj.bias)
27
+
28
+ # Tự động map đúng tên module của Qwen3
29
+ self.attn_module = getattr(pretrained_layer, 'self_attn', getattr(pretrained_layer, 'attn', None))
30
+ self.mlp_module = getattr(pretrained_layer, 'mlp', getattr(pretrained_layer, 'feed_forward', None))
31
+ self.attn_norm = getattr(pretrained_layer, 'input_layernorm', getattr(pretrained_layer, 'attn_norm', nn.Identity()))
32
+ self.mlp_norm = getattr(pretrained_layer, 'post_attention_layernorm', getattr(pretrained_layer, 'mlp_norm', nn.Identity()))
33
+
34
+ def forward(self, hidden_states, cond, position_ids=None, attention_mask=None, position_embeddings=None):
35
+ adaln_params = self.cond_proj(cond).unsqueeze(1)
36
+ scale_attn, shift_attn, alpha_attn, scale_mlp, shift_mlp, alpha_mlp = adaln_params.chunk(6, dim=-1)
37
+
38
+ # --- Attention Block ---
39
+ normed_attn = self.attn_norm(hidden_states) * (1 + scale_attn) + shift_attn
40
+
41
+ # Đóng gói kwargs an toàn để truyền cho Attention
42
+ kwargs = {}
43
+ if attention_mask is not None: kwargs['attention_mask'] = attention_mask
44
+ if position_ids is not None: kwargs['position_ids'] = position_ids
45
+ if position_embeddings is not None: kwargs['position_embeddings'] = position_embeddings
46
+
47
+ attn_out = self.attn_module(normed_attn, **kwargs)
48
+ attn_output = attn_out[0] if isinstance(attn_out, tuple) else attn_out
49
+ hidden_states = hidden_states + (alpha_attn * attn_output)
50
+
51
+ # --- MLP Block ---
52
+ normed_mlp = self.mlp_norm(hidden_states) * (1 + scale_mlp) + shift_mlp
53
+ mlp_out = self.mlp_module(normed_mlp)
54
+ mlp_output = mlp_out[0] if isinstance(mlp_out, tuple) else mlp_out
55
+ hidden_states = hidden_states + (alpha_mlp * mlp_output)
56
+
57
+ return hidden_states
58
+
59
+ class ConditionalMDLM(nn.Module):
60
+ def __init__(self, config):
61
+ super().__init__()
62
+ mc = config["model"]
63
+ self.vocab_size = mc["vocab_size"]
64
+
65
+ print(f"Loading pretrained backbone from {mc['pretrained_token_embeddings']}...")
66
+ self.backbone = AutoModel.from_pretrained(mc["pretrained_token_embeddings"], trust_remote_code=True)
67
+
68
+ # FIX CỐT LÕI: Tự động lấy kích thước chuẩn (1024) từ model gốc, bỏ qua khai báo sai trong yaml
69
+ self.hidden_dim = self.backbone.config.hidden_size
70
+ self.cond_dim = mc["embedding_cond_dim"]
71
+ print(f"Dynamically mapped: hidden_dim={self.hidden_dim}, cond_dim={self.cond_dim}")
72
+
73
+ self.token_embed = self.backbone.get_input_embeddings()
74
+ self.embed_norm = getattr(self.backbone, 'norm', nn.Identity())
75
+
76
+ self.layers = nn.ModuleList([
77
+ ModernBertLayerWithAdaLN(layer, self.hidden_dim, self.cond_dim)
78
+ for layer in self.backbone.layers
79
+ ])
80
+
81
+ self.final_adaln = AdaLNZero(self.hidden_dim, self.cond_dim)
82
+ self.output_proj = nn.Linear(self.hidden_dim, self.vocab_size, bias=False)
83
+
84
+ if mc.get("tie_weights", True):
85
+ self.output_proj.weight = self.token_embed.weight
86
+
87
+ def _forward_impl(self, input_ids, cond_embedding, padding_mask, return_logits=False):
88
+ device = input_ids.device
89
+ batch_size, seq_len = input_ids.shape
90
+
91
+ # 1. Chuẩn bị Attention Mask (Fix lõi SDPA dtype & Ép Bidirectional)
92
+ if padding_mask is not None:
93
+ # Chuyển sang bool: True = Attend (Giữ lại), False = PAD (Bỏ qua)
94
+ attn_mask = (~padding_mask).bool()
95
+ else:
96
+ attn_mask = torch.ones(batch_size, seq_len, dtype=torch.bool, device=device)
97
+
98
+ # Mở rộng chiều thành [Batch, 1, 1, SeqLen] để broadcast với đa Head
99
+ # Phải truyền mask này vào để tắt Causal Mask mặc định của Qwen3
100
+ attn_mask = attn_mask.unsqueeze(1).unsqueeze(2)
101
+
102
+ # 2. Chuẩn bị Position IDs
103
+ pos_ids = torch.arange(seq_len, dtype=torch.long, device=device).unsqueeze(0).expand(batch_size, -1)
104
+
105
+ # 3. Trích xuất RoPE đa năng
106
+ pos_emb = None
107
+ if hasattr(self.backbone, 'rotary_emb'):
108
+ dummy_x = torch.empty(batch_size, seq_len, self.hidden_dim, device=device, dtype=torch.bfloat16)
109
+ try:
110
+ pos_emb = self.backbone.rotary_emb(dummy_x, pos_ids)
111
+ except Exception:
112
+ try:
113
+ pos_emb = self.backbone.rotary_emb(pos_ids)
114
+ except Exception:
115
+ pass
116
+
117
+ # 4. Forward Pass
118
+ x = self.token_embed(input_ids)
119
+ x = self.embed_norm(x)
120
+
121
+ for layer in self.layers:
122
+ # Đã truyền attn_mask chuẩn bool
123
+ x = layer(x, cond_embedding, position_ids=pos_ids, attention_mask=attn_mask, position_embeddings=pos_emb)
124
+
125
+ x, _ = self.final_adaln(x, cond_embedding)
126
+
127
+ if return_logits:
128
+ return self.output_proj(x)
129
+ return x
130
+
131
+ def forward(self, input_ids, cond_embedding, padding_mask=None):
132
+ return self._forward_impl(input_ids, cond_embedding, padding_mask, return_logits=True)
133
+
134
+ def forward_hidden(self, input_ids, cond_embedding, padding_mask=None):
135
+ return self._forward_impl(input_ids, cond_embedding, padding_mask, return_logits=False)
136
+
137
+ def count_params(self):
138
+ total = sum(p.numel() for p in self.parameters())
139
+ trainable = sum(p.numel() for p in self.parameters() if p.requires_grad)
140
+ return total, trainable
141
+
142
+ def apply_mask(token_ids, mask_token_id, padding_mask=None):
143
+ B, L = token_ids.shape
144
+ device = token_ids.device
145
+ u = torch.rand(B, 1, device=device)
146
+ mask_ratio = (1 - (1 - 1e-3)**u).clamp(min=0.1, max=1.0)
147
+ rand_scores = torch.rand(B, L, device=device)
148
+ if padding_mask is not None:
149
+ rand_scores[padding_mask] = 2.0
150
+ target_mask = rand_scores < mask_ratio
151
+ masked_ids = token_ids.clone()
152
+ masked_ids[target_mask] = mask_token_id
153
+ return masked_ids, target_mask, mask_ratio
pyproject.toml ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [project]
2
+ name = "mi-research"
3
+ version = "0.1.0"
4
+ description = "Add your description here"
5
+ readme = "README.md"
6
+ requires-python = ">=3.11"
7
+ dependencies = [
8
+ "datasets>=4.8.4",
9
+ "fastapi>=0.104.0",
10
+ "numpy>=1.24.0",
11
+ "pyyaml>=6.0",
12
+ "torch>=2.0.0",
13
+ "transformers>=4.35.0",
14
+ "uvicorn>=0.24.0",
15
+ ]
train.py ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ import os
3
+ import time
4
+ import argparse
5
+ import json
6
+ import yaml
7
+ import math
8
+ import copy
9
+
10
+ import torch
11
+ import torch.nn as nn
12
+ import torch.nn.functional as F
13
+ from safetensors.torch import save_file as safetensors_save
14
+
15
+ from model import ConditionalMDLM, apply_mask
16
+ from dataset import create_dataloaders
17
+
18
+ def get_lr(step, warmup_steps, max_steps, max_lr, min_lr_ratio=0.0):
19
+ if step < warmup_steps:
20
+ return max_lr * step / warmup_steps
21
+ progress = (step - warmup_steps) / max(1, max_steps - warmup_steps)
22
+ min_lr = max_lr * min_lr_ratio
23
+ return min_lr + (max_lr - min_lr) * 0.5 * (1 + math.cos(math.pi * progress))
24
+
25
+ def _meta(step, best_val_loss, config):
26
+ mc = config.get("model", {})
27
+ return {
28
+ "step": str(step),
29
+ "best_val_loss": f"{best_val_loss:.6f}",
30
+ "encoder_model": str(mc.get("encoder_model", "unknown")),
31
+ "decoder_tokenizer": str(mc.get("decoder_tokenizer", "unknown")),
32
+ "vocab_size": str(mc.get("vocab_size", 0)),
33
+ "hidden_dim": str(mc.get("hidden_dim", 0)),
34
+ "config_json": json.dumps(config, default=str),
35
+ }
36
+
37
+ def save_checkpoint(path, step, best_val_loss, model, ema_model, optimizer, config):
38
+ torch.save({
39
+ "step": step,
40
+ "best_val_loss": best_val_loss,
41
+ "model": model.state_dict(),
42
+ "ema_model": ema_model.state_dict(),
43
+ "optimizer": optimizer.state_dict(),
44
+ "config": config,
45
+ }, path)
46
+
47
+ def save_ema(path, step, best_val_loss, ema_model, config):
48
+ st_path = path.replace(".pt", ".safetensors")
49
+ safetensors_save(ema_model.state_dict(), st_path, metadata=_meta(step, best_val_loss, config))
50
+
51
+ def train(config, resume=False):
52
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
53
+ print(f"Device: {device}\nGPU: {torch.cuda.get_device_name() if device.type == 'cuda' else 'N/A'}")
54
+
55
+ mc, tc = config["model"], config["training"]
56
+
57
+ model = ConditionalMDLM(config).to(device)
58
+ total_params, trainable_params = model.count_params()
59
+ print(f"Model params: {total_params:,} total, {trainable_params:,} trainable")
60
+
61
+ ema_decay = tc.get("ema_decay", 0.9999)
62
+ ema_model = copy.deepcopy(model)
63
+ ema_model.eval()
64
+ for p in ema_model.parameters(): p.requires_grad_(False)
65
+
66
+ batch_size = tc.get("batch_size", 128)
67
+ print(f"Loading data... (Batch size: {batch_size})")
68
+ train_loader, val_loader = create_dataloaders(config)
69
+
70
+ optimizer = torch.optim.AdamW(model.parameters(), lr=tc["lr"], weight_decay=tc["weight_decay"])
71
+
72
+ # KHÔNG DÙNG GradScaler cho bfloat16
73
+ grad_accum = tc.get("grad_accum", 1)
74
+
75
+ ckpt_dir = config.get("_ckpt_dir", "checkpoints")
76
+ os.makedirs(ckpt_dir, exist_ok=True)
77
+ start_step, best_val_loss = 0, float("inf")
78
+
79
+ if resume:
80
+ ckpt_path = f"{ckpt_dir}/latest.pt"
81
+ if not os.path.exists(ckpt_path): ckpt_path = f"{ckpt_dir}/best.pt"
82
+ if os.path.exists(ckpt_path):
83
+ ckpt = torch.load(ckpt_path, map_location=device, weights_only=False)
84
+ model.load_state_dict({k.replace("_orig_mod.", ""): v for k, v in ckpt["model"].items()})
85
+ optimizer.load_state_dict(ckpt["optimizer"])
86
+ start_step, best_val_loss = ckpt["step"], ckpt.get("best_val_loss", float("inf"))
87
+ if "ema_model" in ckpt:
88
+ ema_model.load_state_dict({k.replace("_orig_mod.", ""): v for k, v in ckpt["ema_model"].items()})
89
+
90
+ model.train()
91
+ step = start_step
92
+ max_steps, log_every, eval_every = tc["max_steps"], tc["log_every"], tc.get("eval_every", 500)
93
+ early_stop_patience = tc.get("early_stop_patience", 5000)
94
+
95
+ running_loss, running_acc, running_count, total_samples = 0.0, 0.0, 0, 0
96
+ micro_step = 0
97
+ t0_global = time.time()
98
+ data_iter = iter(train_loader)
99
+
100
+ print(f"\n=== Training started (step {step}/{max_steps}) ===")
101
+
102
+ while step < max_steps:
103
+ try:
104
+ batch = next(data_iter)
105
+ except StopIteration:
106
+ data_iter = iter(train_loader)
107
+ batch = next(data_iter)
108
+
109
+ token_ids = batch["token_ids"].to(device)
110
+ embedding = batch["embedding"].to(device)
111
+ padding_mask = batch["padding_mask"].to(device)
112
+
113
+ masked_ids, target_mask, mask_ratio = apply_mask(token_ids, mc["mask_token_id"], padding_mask)
114
+
115
+ if micro_step == 0:
116
+ lr = get_lr(step, tc["warmup_steps"], max_steps, tc["lr"], tc.get("min_lr_ratio", 0.0))
117
+ for pg in optimizer.param_groups: pg["lr"] = lr
118
+ optimizer.zero_grad()
119
+
120
+ # Dùng bfloat16 siêu việt của H100
121
+ with torch.amp.autocast('cuda', dtype=torch.bfloat16):
122
+ hidden = model.forward_hidden(masked_ids, embedding, padding_mask)
123
+
124
+ mask_flat = target_mask.view(-1)
125
+ pad_flat = padding_mask.view(-1)
126
+ active_mask = mask_flat & (~pad_flat)
127
+ total_active = active_mask.sum().item()
128
+
129
+ chunk_size = 256
130
+ total_positions = hidden.shape[0] * hidden.shape[1]
131
+ hidden_flat = hidden.view(-1, hidden.shape[-1])
132
+ targets_flat = token_ids.view(-1)
133
+
134
+ total_loss = torch.tensor(0.0, device=device)
135
+ total_correct = 0
136
+
137
+ for i in range(0, total_positions, chunk_size):
138
+ end = min(i + chunk_size, total_positions)
139
+ h_chunk = hidden_flat[i:end]
140
+ t_chunk = targets_flat[i:end]
141
+ m_chunk = active_mask[i:end].float()
142
+
143
+ w = model.output_proj.weight
144
+ logits_chunk = F.linear(h_chunk, w)
145
+
146
+ loss_chunk = F.cross_entropy(logits_chunk, t_chunk, reduction="none")
147
+ total_loss = total_loss + (loss_chunk * m_chunk).sum()
148
+
149
+ with torch.no_grad():
150
+ preds_chunk = logits_chunk.argmax(-1)
151
+ total_correct += ((preds_chunk == t_chunk) * m_chunk.bool()).sum().item()
152
+
153
+ loss = total_loss / max(total_active, 1)
154
+ loss_weight = (1.0 / mask_ratio.squeeze(1)).mean()
155
+ loss = (loss * loss_weight) / grad_accum
156
+
157
+ # Gọi backward trực tiếp, không dùng scaler
158
+ loss.backward()
159
+
160
+ running_loss += loss.item() * grad_accum
161
+ running_acc += total_correct / max(total_active, 1)
162
+ running_count += 1
163
+ total_samples += token_ids.shape[0]
164
+ micro_step += 1
165
+
166
+ if micro_step < grad_accum: continue
167
+
168
+ # Bước Optimizer chuẩn: Clip -> Step
169
+ micro_step = 0
170
+ nn.utils.clip_grad_norm_(model.parameters(), tc["max_grad_norm"])
171
+ optimizer.step()
172
+
173
+ with torch.no_grad():
174
+ for ep, mp in zip(ema_model.parameters(), model.parameters()):
175
+ ep.mul_(ema_decay).add_(mp, alpha=1 - ema_decay)
176
+ step += 1
177
+
178
+ if step % log_every == 0:
179
+ avg_loss = running_loss / running_count
180
+ avg_acc = running_acc / running_count
181
+ elapsed = (time.time() - t0_global) / 60
182
+ rate = total_samples / (time.time() - t0_global)
183
+ print(f"step {step} | loss {avg_loss:.4f} | acc {avg_acc:.3f} | lr {lr:.2e} | {rate:.0f} samp/s | {elapsed:.1f}m", flush=True)
184
+ running_loss, running_acc, running_count = 0.0, 0.0, 0
185
+
186
+ def main():
187
+ parser = argparse.ArgumentParser()
188
+ parser.add_argument("--config", default="configs/v2_qwen3.yaml")
189
+ parser.add_argument("--resume", action="store_true")
190
+ args = parser.parse_args()
191
+
192
+ with open(args.config) as f: config = yaml.safe_load(f)
193
+ config["_ckpt_dir"] = f"checkpoints_{os.path.splitext(os.path.basename(args.config))[0]}"
194
+ train(config, resume=args.resume)
195
+
196
+ if __name__ == "__main__":
197
+ main()