MCPcopy Create free account
hub / github.com/FusionBrainLab/SONAR-LLM / collate_and_encode

Function collate_and_encode

sonar_encoding.py:48–87  ·  view source on GitHub ↗

Tokenize each text into sentences, batch the sentences through Sonar, and regroup them per text. Returns a list of dicts, each dict has: { "original_text": str, "sentences": [str, ...], "embeddings": [ [float, ..., float], ... ] # 1024-D }

(batch_texts, sonar_model)

Source from the content-addressed store, hash-verified

46
47
48def collate_and_encode(batch_texts, sonar_model):
49 """
50 Tokenize each text into sentences, batch the sentences through Sonar,
51 and regroup them per text.
52 Returns a list of dicts, each dict has:
53 {
54 "original_text": str,
55 "sentences": [str, ...],
56 "embeddings": [ [float, ..., float], ... ] # 1024-D
57 }
58 """
59 batch_sentences = []
60 batch_map = []
61
62 for i, txt in enumerate(batch_texts):
63 sents = sent_tokenize(txt)
64 sents = [s.strip() for s in sents if s.strip()]
65 for j, s in enumerate(sents):
66 batch_sentences.append(s)
67 batch_map.append((i, j))
68
69 if len(batch_sentences) > 0:
70 with torch.no_grad():
71 emb_tensors = sonar_model.predict(batch_sentences, source_lang="eng_Latn")
72 all_embeddings = emb_tensors.cpu().tolist()
73 else:
74 all_embeddings = []
75
76 results = [
77 {"original_text": batch_texts[i], "sentences": [], "embeddings": []}
78 for i in range(len(batch_texts))
79 ]
80
81 idx_in_sentences = 0
82 for (text_i, _), emb_vec in zip(batch_map, all_embeddings):
83 results[text_i]["sentences"].append(batch_sentences[idx_in_sentences])
84 results[text_i]["embeddings"].append(emb_vec)
85 idx_in_sentences += 1
86
87 return results
88
89
90def ddp_main():

Callers 1

ddp_mainFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected