Views
No views yet
pip install torch transformers>=4.53.0SFT-Emb-8B is initialized fromQwen3-Embedding-8B.
1import torch
2import torch.nn.functional as F
3from transformers import AutoTokenizer, AutoModel
4
5# Configuration
6device = "cuda" if torch.cuda.is_available() else "cpu"
7
8# Inference Parameters
9node_delimiter = "<|repo_name|>" # Special token for Node tasks
10
11# Load Tokenizer (base)
12tokenizer = AutoTokenizer.from_pretrained(
13 "Qwen/Qwen3-Embedding-8B",
14 trust_remote_code=True,
15 padding_side="left"
16)
17
18# Load Model
19model = AutoModel.from_pretrained(
20 "MindscapeRAG/SFT-Emb-8B",
21 trust_remote_code=True,
22 torch_dtype=torch.bfloat16,
23 attn_implementation="flash_attention_2",
24 device_map={"": 0}
25)1def get_query_prompt(query):
2 """Construct input prompt (query-only, no summary)."""
3 task_desc = "Given a search query, retrieve relevant chunks or helpful entities summaries from the given context that answer the query"
4 return (
5 f"Instruct: {task_desc}\n"
6 f"Query: {query}{node_delimiter}"
7 )
8
9def last_token_pool(last_hidden_states, attention_mask):
10 """Extract the last non-padding token embedding."""
11 left_padding = attention_mask[:, -1].sum() == attention_mask.shape[0]
12 if left_padding:
13 return last_hidden_states[:, -1]
14 sequence_lengths = attention_mask.sum(dim=1) - 1
15 batch_size = last_hidden_states.shape[0]
16 return last_hidden_states[torch.arange(batch_size, device=last_hidden_states.device), sequence_lengths]
17
18def encode_chunk(texts):
19 batch = tokenizer(
20 texts,
21 max_length=4096,
22 padding=True,
23 truncation=True,
24 return_tensors="pt"
25 ).to(model.device)
26
27 outputs = model(**batch)
28
29 # Embedding (Last Token)
30 emb = last_token_pool(outputs.last_hidden_state, batch["attention_mask"])
31 emb = F.normalize(emb, p=2, dim=-1)
32 return emb
33
34
35# --- Example ---
36query = "Who is the protagonist?"
37chunk = "Harry looked at the scar on his forehead."
38
39# Encode
40q_emb = encode_chunk([get_query_prompt(query)])
41c_emb = encode_chunk([chunk])
42
43# Score
44score = q_emb @ c_emb.T
45print(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 extract_specific_token(outputs, batch, token_id):
2 """Extract embedding at the position of a specific token."""
3 input_ids = batch["input_ids"]
4 hidden = outputs.last_hidden_state
5 mask = (input_ids == token_id)
6 # Take the last occurrence of the token for each sample
7 positions = mask.long().cumsum(dim=1).eq(mask.long().sum(dim=1, keepdim=True)) & mask
8 return hidden[positions]
9
10def encode_node_query(texts, node_delimiter="<|repo_name|>"):
11 batch = tokenizer(texts, padding=True, return_tensors="pt").to(model.device)
12 outputs = model(**batch)
13
14 # Node Main Embedding: extract from <|repo_name|> position
15 node_id = tokenizer.encode(node_delimiter, add_special_tokens=False)[0]
16 q_emb_node = extract_specific_token(outputs, batch, node_id)
17 q_emb_node = F.normalize(q_emb_node, p=2, dim=-1)
18 return q_emb_node
19
20
21# --- Example ---
22query = "Who is the protagonist?"
23
24# 1) Encode Query (Node Token)
25q_emb_node = encode_node_query([get_query_prompt(query)])
26
27# 2) Encode Entity Candidate
28entity_text = "Harry Potter : The main protagonist of the series..."
29n_emb = encode_chunk([entity_text])
30
31# 3) Score
32score = q_emb_node @ n_emb.T
33print(f"Node Similarity: {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}