Views
No views yet
pip install torch transformers>=4.53.0MiA-Emb-4B is initialized fromQwen3-Embedding-4B.
1import torch
2import torch.nn.functional as F
3from transformers import AutoTokenizer, AutoModel
4
5# Configuration
6
7device = "cuda" if torch.cuda.is_available() else "cpu"
8
9# Inference Parameters
10residual = True # Enable residual connection logic
11residual_factor = 0.5 # Balance between local and global
12node_delimiter = "<|repo_name|>" # Special token for Node tasks
13
14# Load Tokenizer (base)
15tokenizer = AutoTokenizer.from_pretrained(
16 "Qwen/Qwen3-Embedding-4B",
17 trust_remote_code=True,
18 padding_side="left"
19)
20
21# Load Model
22model = AutoModel.from_pretrained(
23 "MindscapeRAG/MiA-Emb-4B",
24 trust_remote_code=True,
25 torch_dtype=torch.bfloat16,
26 attn_implementation="flash_attention_2",
27 device_map={"": 0}
28)1def get_query_prompt(query, summary="", residual=False):
2 """Construct input prompt with global summary (Eq. 5 in paper)."""
3 task_desc = "Given a search query with the book's summary, retrieve relevant chunks or helpful entities summaries from the given context that answer the query"
4 summary_prefix = "\n\nHere is the summary providing possibly useful global information. Please encode the query based on the summary:\n"
5
6 # Insert PAD token to capture residual embedding before the summary
7 middle_token = tokenizer.pad_token if residual else ""
8
9 return (
10 f"Instruct: {task_desc}\n"
11 f"Query: {query}{middle_token}{summary_prefix}{summary}{node_delimiter}"
12 )
13
14def encode_chunk(texts, is_query=False, residual=False):
15 batch = tokenizer(
16 texts,
17 max_length=4096,
18 padding=True,
19 truncation=True,
20 return_tensors="pt"
21 ).to(model.device)
22
23 outputs = model(**batch)
24
25 # 1) Main Embedding (Last Token)
26 emb_main = last_token_pool(outputs.last_hidden_state, batch["attention_mask"])
27
28 # 2) Residual Embedding (PAD Token)
29 emb_res = None
30 if residual and is_query:
31 emb_res = extract_residual_token(outputs, batch, tokenizer.pad_token_id)
32
33 emb_main = F.normalize(emb_main, p=2, dim=-1)
34 emb_res = F.normalize(emb_res, p=2, dim=-1) if emb_res is not None else None
35 return emb_main, emb_res
36
37
38# --- Example ---
39query = "Who is the protagonist?"
40global_summ = "A summary of the entire book..."
41chunk = "Harry looked at the scar on his forehead."
42
43# Encode
44q_emb, q_res = encode_chunk(
45 [get_query_prompt(query, global_summ, residual=True)],
46 is_query=True,
47 residual=True
48)
49c_emb, _ = encode_chunk([chunk], is_query=False)
50
51# Score Fusion
52score = q_emb @ c_emb.T
53if q_res is not None:
54 score = (1 - residual_factor) * score + residual_factor * (q_res @ c_emb.T)
55
56print(f"Chunk Similarity: {score.item():.4f}")<|repo_name|> token position.Entity Name : Entity DescriptionMary Campbell Smith : Mary Campbell Smith is mentioned as the translator...1def encode_node_query(texts, residual=True, node_delimiter="<|repo_name|>"):
2 batch = tokenizer(texts, padding=True, return_tensors="pt").to(model.device)
3 outputs = model(**batch)
4
5 # 1) Node Main Embedding: extract from <|repo_name|> position
6 node_id = tokenizer.encode(node_delimiter, add_special_tokens=False)[0]
7 q_emb_node = extract_specific_token(outputs, batch, node_id)
8
9 # 2) Residual Embedding: extract from [PAD] position
10 q_emb_res = extract_residual_token(outputs, batch, tokenizer.pad_token_id) if residual else None
11
12 q_emb_node = F.normalize(q_emb_node, p=2, dim=-1)
13 q_emb_res = F.normalize(q_emb_res, p=2, dim=-1) if q_emb_res is not None else None
14 return q_emb_node, q_emb_res
15
16
17# --- Example ---
18query = "Who is the protagonist?"
19global_summ = "A summary of the entire book..."
20
21# 1) Encode Query (Node Token)
22q_emb_node, q_emb_res = encode_node_query(
23 [get_query_prompt(query, global_summ, residual=True)],
24 residual=True
25)
26
27# 2) Encode Entity Candidate
28entity_text = "Harry Potter : The main protagonist of the series..."
29n_emb, _ = encode_chunk([entity_text], is_query=False)
30
31# 3) Score Fusion
32final_score = (1 - residual_factor) * (q_emb_node @ n_emb.T)
33if q_emb_res is not None:
34 final_score = final_score + residual_factor * (q_emb_res @ n_emb.T)
35
36print(f"Node Similarity: {final_score.item():.4f}")1@misc{li2025mindscapeawareretrievalaugmentedgeneration,
2 title={Mindscape-Aware Retrieval Augmented Generation for Improved Long Context Understanding},
3 author={Yuqing Li and Jiangnan Li and Zheng Lin and Ziyan Zhou and Junjie Wu and Weiping Wang and Jie Zhou and Mo Yu},
4 year={2025},
5 eprint={2512.17220},
6 archivePrefix={arXiv},
7 primaryClass={cs.CL},
8 url={https://arxiv.org/abs/2512.17220},
9}