benjamintli commited on
Commit
8c327e1
·
verified ·
1 Parent(s): 3d0959d

End of training

Browse files
1_Pooling/config.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "word_embedding_dimension": 768,
3
+ "pooling_mode_cls_token": false,
4
+ "pooling_mode_mean_tokens": true,
5
+ "pooling_mode_max_tokens": false,
6
+ "pooling_mode_mean_sqrt_len_tokens": false,
7
+ "pooling_mode_weightedmean_tokens": false,
8
+ "pooling_mode_lasttoken": false,
9
+ "include_prompt": true
10
+ }
README.md ADDED
@@ -0,0 +1,631 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ tags:
3
+ - sentence-transformers
4
+ - sentence-similarity
5
+ - feature-extraction
6
+ - dense
7
+ - generated_from_trainer
8
+ - dataset_size:283621
9
+ - loss:CachedMultipleNegativesRankingLoss
10
+ base_model: answerdotai/ModernBERT-base
11
+ widget:
12
+ - source_sentence: '// Uint is a helper routine that allocates a new uint value to
13
+ store v and
14
+
15
+ // returns a pointer to it. This is useful when assigning optional parameters.'
16
+ sentences:
17
+ - "func (c *Animation) GetCurrentTimeWithParams(v *AnimationGetCurrentTimeParams)\
18
+ \ (float64, error) {\n\tresp, err := gcdmessage.SendCustomReturn(c.target, c.target.GetSendCh(),\
19
+ \ &gcdmessage.ParamRequest{Id: c.target.GetId(), Method: \"Animation.getCurrentTime\"\
20
+ , Params: v})\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tvar chromeData struct\
21
+ \ {\n\t\tResult struct {\n\t\t\tCurrentTime float64\n\t\t}\n\t}\n\n\tif resp ==\
22
+ \ nil {\n\t\treturn 0, &gcdmessage.ChromeEmptyResponseErr{}\n\t}\n\n\t// test\
23
+ \ if error first\n\tcerr := &gcdmessage.ChromeErrorResponse{}\n\tjson.Unmarshal(resp.Data,\
24
+ \ cerr)\n\tif cerr != nil && cerr.Error != nil {\n\t\treturn 0, &gcdmessage.ChromeRequestErr{Resp:\
25
+ \ cerr}\n\t}\n\n\tif err := json.Unmarshal(resp.Data, &chromeData); err != nil\
26
+ \ {\n\t\treturn 0, err\n\t}\n\n\treturn chromeData.Result.CurrentTime, nil\n}"
27
+ - "func Uint(v uint) *uint {\n\tp := new(uint)\n\t*p = v\n\treturn p\n}"
28
+ - "def after_init_app(self, app: FlaskUnchained):\n \"\"\"\n Configure\
29
+ \ the JSON encoder for Flask to be able to serialize Enums,\n LocalProxy\
30
+ \ objects, and SQLAlchemy models.\n \"\"\"\n self.set_json_encoder(app)\n\
31
+ \ app.before_first_request(self.register_model_resources)"
32
+ - source_sentence: 'Returns a template for the parent of this template.
33
+
34
+
35
+ @throws ValidationException if the template has no parent.'
36
+ sentences:
37
+ - "func BodyContainsOr(values ...string) ResponseCondition {\n\treturn func(res\
38
+ \ *http.Response) error {\n\t\tbody, err := ioutil.ReadAll(res.Body)\n\t\tif err\
39
+ \ != nil {\n\t\t\treturn fmt.Errorf(\"failed to read response body: %s\", err)\n\
40
+ \t\t}\n\n\t\tfor _, value := range values {\n\t\t\tif strings.Contains(string(body),\
41
+ \ value) {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t\treturn fmt.Errorf(\"could\
42
+ \ not find '%v' in body '%s'\", values, string(body))\n\t}\n}"
43
+ - "protected function after_update($result) {\n global $DB;\n\n if\
44
+ \ (!$result) {\n $this->beforeupdate = null;\n return;\n\
45
+ \ }\n\n // The parent ID has changed, we need to fix all the paths\
46
+ \ of the children.\n if ($this->beforeupdate->get('parentid') != $this->get('parentid'))\
47
+ \ {\n $beforepath = $this->beforeupdate->get('path') . $this->get('id')\
48
+ \ . '/';\n\n $like = $DB->sql_like('path', '?');\n $likesearch\
49
+ \ = $DB->sql_like_escape($beforepath) . '%';\n\n $table = '{' . self::TABLE\
50
+ \ . '}';\n $sql = \"UPDATE $table SET path = REPLACE(path, ?, ?) WHERE\
51
+ \ \" . $like;\n $DB->execute($sql, array(\n $beforepath,\n\
52
+ \ $this->get('path') . $this->get('id') . '/',\n \
53
+ \ $likesearch\n ));\n\n // Resolving sortorder holes left\
54
+ \ after changing parent.\n $table = '{' . self::TABLE . '}';\n \
55
+ \ $sql = \"UPDATE $table SET sortorder = sortorder -1 \"\n \
56
+ \ . \" WHERE competencyframeworkid = ? AND parentid = ? AND sortorder\
57
+ \ > ?\";\n $DB->execute($sql, array($this->get('competencyframeworkid'),\n\
58
+ \ $this->beforeupdate->get('parentid'),\n\
59
+ \ $this->beforeupdate->get('sortorder')\n\
60
+ \ ));\n }\n\n $this->beforeupdate\
61
+ \ = null;\n }"
62
+ - "public PathTemplate parentTemplate() {\n int i = segments.size();\n Segment\
63
+ \ seg = segments.get(--i);\n if (seg.kind() == SegmentKind.END_BINDING) {\n\
64
+ \ while (i > 0 && segments.get(--i).kind() != SegmentKind.BINDING) {}\n \
65
+ \ }\n if (i == 0) {\n throw new ValidationException(\"template does\
66
+ \ not have a parent\");\n }\n return new PathTemplate(segments.subList(0,\
67
+ \ i), urlEncoding);\n }"
68
+ - source_sentence: 'Build a potentially nested fieldgroup
69
+
70
+
71
+ @param mixed $valueOrGroup Value of item, or title of group
72
+
73
+ @param string|array $titleOrOptions Title of item, or options in grouip
74
+
75
+ @return ArrayData Data for this item'
76
+ sentences:
77
+ - "protected function getFieldOption($valueOrGroup, $titleOrOptions)\n {\n \
78
+ \ // Return flat option\n if (!is_array($titleOrOptions)) {\n \
79
+ \ return parent::getFieldOption($valueOrGroup, $titleOrOptions);\n \
80
+ \ }\n\n // Build children from options list\n $options = new\
81
+ \ ArrayList();\n foreach ($titleOrOptions as $childValue => $childTitle)\
82
+ \ {\n $options->push($this->getFieldOption($childValue, $childTitle));\n\
83
+ \ }\n\n return new ArrayData(array(\n 'Title' => $valueOrGroup,\n\
84
+ \ 'Options' => $options\n ));\n }"
85
+ - "public static function minify($content, array $options = [])\n {\n \
86
+ \ $min = preg_replace(['/[\\n\\r]/', '/\\>[^\\S ]+/s', '/[^\\S ]+\\</s', '/(\\\
87
+ s)+/s', ], ['', '>', '<', '\\\\1'], trim($content));\n $min = str_replace(['>\
88
+ \ <'], ['><'], $min);\n \n if (ArrayHelper::getValue($options, 'comments',\
89
+ \ false)) {\n $min = preg_replace('/<!--(.*)-->/Uis', '', $min);\n\
90
+ \ }\n \n return $min;\n }"
91
+ - "private function loadXInclude(XInclude $xinclude, $filePath){\n //load\
92
+ \ DOMDocument\n $xml = new DOMDocument();\n $loadSuccess = $xml->load($filePath);\n\
93
+ \ $node = $xml->documentElement;\n if($loadSuccess && !is_null($node)){\n\
94
+ \ //parse the href content\n $parser = new ParserFactory($xml);\n\
95
+ \ $parser->loadContainerStatic($node, $xinclude->getBody());\n \
96
+ \ }else{\n throw new XIncludeException('Cannot load the XInclude\
97
+ \ DOM XML', $xinclude);\n }\n }"
98
+ - source_sentence: "Check for new unread messages and send them to the custom api\n\
99
+ \n @param client_id: ID of client user"
100
+ sentences:
101
+ - "public function getLatMap()\n {\n if (null === $this->latMap) {\n \
102
+ \ $this->latMap = $this->getTransliterationMap(Settings::ALPHABET_LAT);\n\
103
+ \ }\n\n return $this->latMap;\n }"
104
+ - "def check_new_messages(client_id):\n \"\"\"Check for new unread messages and\
105
+ \ send them to the custom api\n\n @param client_id: ID of client user\n \
106
+ \ \"\"\"\n # Return if driver is not defined or if whatsapp is not logged in.\n\
107
+ \ # Stop the timer as well\n if client_id not in drivers or not drivers[client_id]\
108
+ \ or not drivers[client_id].is_logged_in():\n timers[client_id].stop()\n\
109
+ \ return\n\n # Acquire a lock on thread\n if not acquire_semaphore(client_id,\
110
+ \ True):\n return\n\n try:\n # Get all unread messages\n \
111
+ \ res = drivers[client_id].get_unread()\n # Mark all of them as seen\n\
112
+ \ for message_group in res:\n message_group.chat.send_seen()\n\
113
+ \ # Release thread lock\n release_semaphore(client_id)\n \
114
+ \ # If we have new messages, do something with it\n if res:\n \
115
+ \ print(res)\n except:\n pass\n finally:\n # Release lock\
116
+ \ anyway, safekeeping\n release_semaphore(client_id)"
117
+ - "def get_uppermost_library_root_state(self):\n \"\"\"Find state_copy of\
118
+ \ uppermost LibraryState\n\n Method checks if there is a parent library\
119
+ \ root state and assigns it to be the current library root state till\n \
120
+ \ there is no further parent library root state.\n \"\"\"\n\n library_root_state\
121
+ \ = self.get_next_upper_library_root_state()\n parent_library_root_state\
122
+ \ = library_root_state\n # initial a library root state has to be found\
123
+ \ and if there is no further parent root state\n # parent_library_root_state\
124
+ \ and library_root_state are no more identical\n while parent_library_root_state\
125
+ \ and library_root_state is parent_library_root_state:\n if library_root_state:\n\
126
+ \ parent_library_root_state = library_root_state.parent.get_next_upper_library_root_state()\n\
127
+ \n if parent_library_root_state:\n library_root_state\
128
+ \ = parent_library_root_state\n\n return library_root_state"
129
+ - source_sentence: If MultiTenantMiddleware is used, filter queryset by request.site_id
130
+ sentences:
131
+ - "def reduce_ticks(ax, which, maxticks=3):\n \"\"\"Given a pyplot axis, resamples\
132
+ \ its `which`-axis ticks such that are at most\n `maxticks` left.\n\n Parameters\n\
133
+ \ ----------\n ax : axis\n The axis to adjust.\n which : {'x'\
134
+ \ | 'y'}\n Which axis to adjust.\n maxticks : {3, int}\n Maximum\
135
+ \ number of ticks to use.\n\n Returns\n -------\n array\n An array\
136
+ \ of the selected ticks.\n \"\"\"\n ticks = getattr(ax, 'get_{}ticks'.format(which))()\n\
137
+ \ if len(ticks) > maxticks:\n # make sure the left/right value is not\
138
+ \ at the edge\n minax, maxax = getattr(ax, 'get_{}lim'.format(which))()\n\
139
+ \ dw = abs(maxax-minax)/10.\n start_idx, end_idx = 0, len(ticks)\n\
140
+ \ if ticks[0] < minax + dw:\n start_idx += 1\n if ticks[-1]\
141
+ \ > maxax - dw:\n end_idx -= 1\n # get reduction factor\n \
142
+ \ fac = int(len(ticks) / maxticks)\n ticks = ticks[start_idx:end_idx:fac]\n\
143
+ \ return ticks"
144
+ - "function (isPublic, name, data, ttl, published_at, coreid) {\n var rawFn\
145
+ \ = function (msg) {\n try {\n msg.setMaxAge(parseInt((ttl\
146
+ \ && (ttl >= 0)) ? ttl : 60));\n if (published_at) {\n \
147
+ \ msg.setTimestamp(moment(published_at).toDate());\n \
148
+ \ }\n }\n catch (ex) {\n logger.error(\"\
149
+ onCoreHeard - \" + ex);\n }\n return msg;\n };\n\n\
150
+ \ var msgName = (isPublic) ? \"PublicEvent\" : \"PrivateEvent\";\n \
151
+ \ var userID = (this.userID || \"\").toLowerCase() + \"/\";\n name =\
152
+ \ (name) ? name.toString() : name;\n if (name && name.indexOf && (name.indexOf(userID)\
153
+ \ == 0)) {\n name = name.substring(userID.length);\n }\n\n \
154
+ \ data = (data) ? data.toString() : data;\n this.sendNONTypeMessage(msgName,\
155
+ \ { event_name: name, _raw: rawFn }, data);\n }"
156
+ - "def get_queryset(self):\n '''\n If MultiTenantMiddleware is used,\
157
+ \ filter queryset by request.site_id\n '''\n queryset = super(PageList,\
158
+ \ self).get_queryset()\n if hasattr(self.request, 'site_id'):\n \
159
+ \ queryset = queryset.filter(site_id=self.request.site_id)\n return\
160
+ \ queryset"
161
+ datasets:
162
+ - benjamintli/code-retrieval-combined-v2
163
+ pipeline_tag: sentence-similarity
164
+ library_name: sentence-transformers
165
+ metrics:
166
+ - cosine_accuracy@1
167
+ - cosine_accuracy@3
168
+ - cosine_accuracy@5
169
+ - cosine_accuracy@10
170
+ - cosine_precision@1
171
+ - cosine_precision@3
172
+ - cosine_precision@5
173
+ - cosine_precision@10
174
+ - cosine_recall@1
175
+ - cosine_recall@3
176
+ - cosine_recall@5
177
+ - cosine_recall@10
178
+ - cosine_ndcg@10
179
+ - cosine_mrr@10
180
+ - cosine_map@100
181
+ model-index:
182
+ - name: SentenceTransformer based on answerdotai/ModernBERT-base
183
+ results:
184
+ - task:
185
+ type: information-retrieval
186
+ name: Information Retrieval
187
+ dataset:
188
+ name: eval
189
+ type: eval
190
+ metrics:
191
+ - type: cosine_accuracy@1
192
+ value: 0.873
193
+ name: Cosine Accuracy@1
194
+ - type: cosine_accuracy@3
195
+ value: 0.9366666666666666
196
+ name: Cosine Accuracy@3
197
+ - type: cosine_accuracy@5
198
+ value: 0.9543333333333334
199
+ name: Cosine Accuracy@5
200
+ - type: cosine_accuracy@10
201
+ value: 0.973
202
+ name: Cosine Accuracy@10
203
+ - type: cosine_precision@1
204
+ value: 0.873
205
+ name: Cosine Precision@1
206
+ - type: cosine_precision@3
207
+ value: 0.31222222222222223
208
+ name: Cosine Precision@3
209
+ - type: cosine_precision@5
210
+ value: 0.19086666666666663
211
+ name: Cosine Precision@5
212
+ - type: cosine_precision@10
213
+ value: 0.0973
214
+ name: Cosine Precision@10
215
+ - type: cosine_recall@1
216
+ value: 0.873
217
+ name: Cosine Recall@1
218
+ - type: cosine_recall@3
219
+ value: 0.9366666666666666
220
+ name: Cosine Recall@3
221
+ - type: cosine_recall@5
222
+ value: 0.9543333333333334
223
+ name: Cosine Recall@5
224
+ - type: cosine_recall@10
225
+ value: 0.973
226
+ name: Cosine Recall@10
227
+ - type: cosine_ndcg@10
228
+ value: 0.9240732170821061
229
+ name: Cosine Ndcg@10
230
+ - type: cosine_mrr@10
231
+ value: 0.9082900793650796
232
+ name: Cosine Mrr@10
233
+ - type: cosine_map@100
234
+ value: 0.9093847853022148
235
+ name: Cosine Map@100
236
+ ---
237
+
238
+ # SentenceTransformer based on answerdotai/ModernBERT-base
239
+
240
+ This is a [sentence-transformers](https://www.SBERT.net) model finetuned from [answerdotai/ModernBERT-base](https://huggingface.co/answerdotai/ModernBERT-base) on the [code-retrieval-combined-v2](https://huggingface.co/datasets/benjamintli/code-retrieval-combined-v2) dataset. It maps sentences & paragraphs to a 768-dimensional dense vector space and can be used for semantic textual similarity, semantic search, paraphrase mining, text classification, clustering, and more.
241
+
242
+ ## Model Details
243
+
244
+ ### Model Description
245
+ - **Model Type:** Sentence Transformer
246
+ - **Base model:** [answerdotai/ModernBERT-base](https://huggingface.co/answerdotai/ModernBERT-base) <!-- at revision 8949b909ec900327062f0ebf497f51aef5e6f0c8 -->
247
+ - **Maximum Sequence Length:** 1024 tokens
248
+ - **Output Dimensionality:** 768 dimensions
249
+ - **Similarity Function:** Cosine Similarity
250
+ - **Training Dataset:**
251
+ - [code-retrieval-combined-v2](https://huggingface.co/datasets/benjamintli/code-retrieval-combined-v2)
252
+ <!-- - **Language:** Unknown -->
253
+ <!-- - **License:** Unknown -->
254
+
255
+ ### Model Sources
256
+
257
+ - **Documentation:** [Sentence Transformers Documentation](https://sbert.net)
258
+ - **Repository:** [Sentence Transformers on GitHub](https://github.com/huggingface/sentence-transformers)
259
+ - **Hugging Face:** [Sentence Transformers on Hugging Face](https://huggingface.co/models?library=sentence-transformers)
260
+
261
+ ### Full Model Architecture
262
+
263
+ ```
264
+ SentenceTransformer(
265
+ (0): Transformer({'max_seq_length': 1024, 'do_lower_case': False, 'architecture': 'OptimizedModule'})
266
+ (1): Pooling({'word_embedding_dimension': 768, 'pooling_mode_cls_token': False, 'pooling_mode_mean_tokens': True, 'pooling_mode_max_tokens': False, 'pooling_mode_mean_sqrt_len_tokens': False, 'pooling_mode_weightedmean_tokens': False, 'pooling_mode_lasttoken': False, 'include_prompt': True})
267
+ )
268
+ ```
269
+
270
+ ## Usage
271
+
272
+ ### Direct Usage (Sentence Transformers)
273
+
274
+ First install the Sentence Transformers library:
275
+
276
+ ```bash
277
+ pip install -U sentence-transformers
278
+ ```
279
+
280
+ Then you can load this model and run inference.
281
+ ```python
282
+ from sentence_transformers import SentenceTransformer
283
+
284
+ # Download from the 🤗 Hub
285
+ model = SentenceTransformer("modernbert-code-v2")
286
+ # Run inference
287
+ queries = [
288
+ "If MultiTenantMiddleware is used, filter queryset by request.site_id",
289
+ ]
290
+ documents = [
291
+ "def get_queryset(self):\n '''\n If MultiTenantMiddleware is used, filter queryset by request.site_id\n '''\n queryset = super(PageList, self).get_queryset()\n if hasattr(self.request, 'site_id'):\n queryset = queryset.filter(site_id=self.request.site_id)\n return queryset",
292
+ 'def reduce_ticks(ax, which, maxticks=3):\n """Given a pyplot axis, resamples its `which`-axis ticks such that are at most\n `maxticks` left.\n\n Parameters\n ----------\n ax : axis\n The axis to adjust.\n which : {\'x\' | \'y\'}\n Which axis to adjust.\n maxticks : {3, int}\n Maximum number of ticks to use.\n\n Returns\n -------\n array\n An array of the selected ticks.\n """\n ticks = getattr(ax, \'get_{}ticks\'.format(which))()\n if len(ticks) > maxticks:\n # make sure the left/right value is not at the edge\n minax, maxax = getattr(ax, \'get_{}lim\'.format(which))()\n dw = abs(maxax-minax)/10.\n start_idx, end_idx = 0, len(ticks)\n if ticks[0] < minax + dw:\n start_idx += 1\n if ticks[-1] > maxax - dw:\n end_idx -= 1\n # get reduction factor\n fac = int(len(ticks) / maxticks)\n ticks = ticks[start_idx:end_idx:fac]\n return ticks',
293
+ 'function (isPublic, name, data, ttl, published_at, coreid) {\n var rawFn = function (msg) {\n try {\n msg.setMaxAge(parseInt((ttl && (ttl >= 0)) ? ttl : 60));\n if (published_at) {\n msg.setTimestamp(moment(published_at).toDate());\n }\n }\n catch (ex) {\n logger.error("onCoreHeard - " + ex);\n }\n return msg;\n };\n\n var msgName = (isPublic) ? "PublicEvent" : "PrivateEvent";\n var userID = (this.userID || "").toLowerCase() + "/";\n name = (name) ? name.toString() : name;\n if (name && name.indexOf && (name.indexOf(userID) == 0)) {\n name = name.substring(userID.length);\n }\n\n data = (data) ? data.toString() : data;\n this.sendNONTypeMessage(msgName, { event_name: name, _raw: rawFn }, data);\n }',
294
+ ]
295
+ query_embeddings = model.encode_query(queries)
296
+ document_embeddings = model.encode_document(documents)
297
+ print(query_embeddings.shape, document_embeddings.shape)
298
+ # [1, 768] [3, 768]
299
+
300
+ # Get the similarity scores for the embeddings
301
+ similarities = model.similarity(query_embeddings, document_embeddings)
302
+ print(similarities)
303
+ # tensor([[ 0.9183, -0.0231, -0.0561]])
304
+ ```
305
+
306
+ <!--
307
+ ### Direct Usage (Transformers)
308
+
309
+ <details><summary>Click to see the direct usage in Transformers</summary>
310
+
311
+ </details>
312
+ -->
313
+
314
+ <!--
315
+ ### Downstream Usage (Sentence Transformers)
316
+
317
+ You can finetune this model on your own dataset.
318
+
319
+ <details><summary>Click to expand</summary>
320
+
321
+ </details>
322
+ -->
323
+
324
+ <!--
325
+ ### Out-of-Scope Use
326
+
327
+ *List how the model may foreseeably be misused and address what users ought not to do with the model.*
328
+ -->
329
+
330
+ ## Evaluation
331
+
332
+ ### Metrics
333
+
334
+ #### Information Retrieval
335
+
336
+ * Dataset: `eval`
337
+ * Evaluated with [<code>InformationRetrievalEvaluator</code>](https://sbert.net/docs/package_reference/sentence_transformer/evaluation.html#sentence_transformers.evaluation.InformationRetrievalEvaluator)
338
+
339
+ | Metric | Value |
340
+ |:--------------------|:-----------|
341
+ | cosine_accuracy@1 | 0.873 |
342
+ | cosine_accuracy@3 | 0.9367 |
343
+ | cosine_accuracy@5 | 0.9543 |
344
+ | cosine_accuracy@10 | 0.973 |
345
+ | cosine_precision@1 | 0.873 |
346
+ | cosine_precision@3 | 0.3122 |
347
+ | cosine_precision@5 | 0.1909 |
348
+ | cosine_precision@10 | 0.0973 |
349
+ | cosine_recall@1 | 0.873 |
350
+ | cosine_recall@3 | 0.9367 |
351
+ | cosine_recall@5 | 0.9543 |
352
+ | cosine_recall@10 | 0.973 |
353
+ | **cosine_ndcg@10** | **0.9241** |
354
+ | cosine_mrr@10 | 0.9083 |
355
+ | cosine_map@100 | 0.9094 |
356
+
357
+ <!--
358
+ ## Bias, Risks and Limitations
359
+
360
+ *What are the known or foreseeable issues stemming from this model? You could also flag here known failure cases or weaknesses of the model.*
361
+ -->
362
+
363
+ <!--
364
+ ### Recommendations
365
+
366
+ *What are recommendations with respect to the foreseeable issues? For example, filtering explicit content.*
367
+ -->
368
+
369
+ ## Training Details
370
+
371
+ ### Training Dataset
372
+
373
+ #### code-retrieval-combined-v2
374
+
375
+ * Dataset: [code-retrieval-combined-v2](https://huggingface.co/datasets/benjamintli/code-retrieval-combined-v2) at [2b971a6](https://huggingface.co/datasets/benjamintli/code-retrieval-combined-v2/tree/2b971a6d597823ab7ff10b898ae6f3c0fdbbfa23)
376
+ * Size: 283,621 training samples
377
+ * Columns: <code>query</code> and <code>positive</code>
378
+ * Approximate statistics based on the first 1000 samples:
379
+ | | query | positive |
380
+ |:--------|:-----------------------------------------------------------------------------------|:-------------------------------------------------------------------------------------|
381
+ | type | string | string |
382
+ | details | <ul><li>min: 5 tokens</li><li>mean: 44.94 tokens</li><li>max: 856 tokens</li></ul> | <ul><li>min: 30 tokens</li><li>mean: 181.2 tokens</li><li>max: 1024 tokens</li></ul> |
383
+ * Samples:
384
+ | query | positive |
385
+ |:---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|:---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
386
+ | <code>Start the asyncio event loop and runs the application.</code> | <code>def main():<br> """Start the asyncio event loop and runs the application."""<br> # Helper method so that the coroutine exits cleanly if an exception<br> # happens (which would leave resources dangling)<br> async def _run_application(loop):<br> try:<br> return await cli_handler(loop)<br><br> except KeyboardInterrupt:<br> pass # User pressed Ctrl+C, just ignore it<br><br> except SystemExit:<br> pass # sys.exit() was used - do nothing<br><br> except: # pylint: disable=bare-except # noqa<br> import traceback<br><br> traceback.print_exc(file=sys.stderr)<br> sys.stderr.writelines(<br> '\n>>> An error occurred, full stack trace above\n')<br><br> return 1<br><br> try:<br> loop = asyncio.get_event_loop()<br> return loop.run_until_complete(_run_application(loop))<br> except KeyboardInterrupt:<br> pass<br><br> return 1</code> |
387
+ | <code>Initialize the pool manager with the number of pools, the entry sizes for each<br>pool, and the maximum depth of the free pool.<br><br>@param bufferEntrySizes the memory sizes of each entry in the pools<br>@param bufferEntryDepths the maximum number of entries in the free pool</code> | <code>public void initialize(int[] bufferEntrySizes, int[] bufferEntryDepths) {<br> if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {<br> Tr.entry(tc, "initialize");<br> }<br><br> // order both lists from smallest to largest, based only on Entry Sizes<br> int len = bufferEntrySizes.length;<br> int[] bSizes = new int[len];<br> int[] bDepths = new int[len];<br> int sizeCompare;<br> int depth;<br> int sizeSort;<br> int j;<br><br> for (int i = 0; i < len; i++) {<br> sizeCompare = bufferEntrySizes[i];<br> depth = bufferEntryDepths[i];<br> // go backwards, for speed, since first Array List is<br> // probably already ordered small to large<br> for (j = i - 1; j >= 0; j--) {<br> sizeSort = bSizes[j];<br> if (sizeCompare > sizeSort) {<br> // add the bigger one after the smaller one<br> bSizes[j + 1] = sizeCompare;<br> bDepths[j ...</code> |
388
+ | <code>// List lists all of the documents in an index. The documents are returned in<br>// increasing ID order.</code> | <code>func (x *Index) List(c context.Context, opts *ListOptions) *Iterator {<br> t := &Iterator{<br> c: c,<br> index: x,<br> count: -1,<br> listInclusive: true,<br> more: moreList,<br> limit: -1,<br> }<br> if opts != nil {<br> t.listStartID = opts.StartID<br> if opts.Limit > 0 {<br> t.limit = opts.Limit<br> }<br> t.idsOnly = opts.IDsOnly<br> }<br> return t<br>}</code> |
389
+ * Loss: [<code>CachedMultipleNegativesRankingLoss</code>](https://sbert.net/docs/package_reference/sentence_transformer/losses.html#cachedmultiplenegativesrankingloss) with these parameters:
390
+ ```json
391
+ {
392
+ "scale": 20.0,
393
+ "similarity_fct": "cos_sim",
394
+ "mini_batch_size": 128,
395
+ "gather_across_devices": false,
396
+ "directions": [
397
+ "query_to_doc"
398
+ ],
399
+ "partition_mode": "joint",
400
+ "hardness_mode": null,
401
+ "hardness_strength": 0.0
402
+ }
403
+ ```
404
+
405
+ ### Evaluation Dataset
406
+
407
+ #### code-retrieval-combined-v2
408
+
409
+ * Dataset: [code-retrieval-combined-v2](https://huggingface.co/datasets/benjamintli/code-retrieval-combined-v2) at [2b971a6](https://huggingface.co/datasets/benjamintli/code-retrieval-combined-v2/tree/2b971a6d597823ab7ff10b898ae6f3c0fdbbfa23)
410
+ * Size: 31,516 evaluation samples
411
+ * Columns: <code>query</code> and <code>positive</code>
412
+ * Approximate statistics based on the first 1000 samples:
413
+ | | query | positive |
414
+ |:--------|:-----------------------------------------------------------------------------------|:--------------------------------------------------------------------------------------|
415
+ | type | string | string |
416
+ | details | <ul><li>min: 5 tokens</li><li>mean: 42.73 tokens</li><li>max: 834 tokens</li></ul> | <ul><li>min: 30 tokens</li><li>mean: 180.42 tokens</li><li>max: 1024 tokens</li></ul> |
417
+ * Samples:
418
+ | query | positive |
419
+ |:---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|:---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
420
+ | <code>This gets the version of OpenALPR<br><br> :return: Version information</code> | <code>def get_version(self):<br> """<br> This gets the version of OpenALPR<br><br> :return: Version information<br> """<br><br> ptr = self._get_version_func(self.alpr_pointer)<br> version_number = ctypes.cast(ptr, ctypes.c_char_p).value<br> version_number = _convert_from_charp(version_number)<br> self._free_json_mem_func(ctypes.c_void_p(ptr))<br> return version_number</code> |
421
+ | <code>Remove all unnecessary comments from a lexer or parser file</code> | <code>public String stripUnnecessaryComments(String javaContent, AntlrOptions options) {<br> if (!options.isOptimizeCodeQuality()) {<br> return javaContent;<br> }<br> javaContent = stripMachineDependentPaths(javaContent);<br> if (options.isStripAllComments()) {<br> javaContent = stripAllComments(javaContent);<br> }<br> return javaContent;<br> }</code> |
422
+ | <code>Serialize reply to array or JSON.<br><br>@param {Object} packet<br>@param {String} packet.method "get", "search", "post", "put", "delete", "sub", "unsub".<br>@param {String} packet.resource<br>@param {String} packet.id<br>@param {*} packet.body<br>@param {Number} [packet.status]<br>@param {Number\|String} [packet.date]<br>@param {Object} [packet.headers]<br>@param {Boolean} [json] true to generate JSON instead of array.<br>@returns {Array\|String\|null}</code> | <code>function reply(packet, json) {<br> return _create(packet, packet.status \|\| 500, (METHODS[packet.method] \|\| '') + packet.resource, json);<br>}</code> |
423
+ * Loss: [<code>CachedMultipleNegativesRankingLoss</code>](https://sbert.net/docs/package_reference/sentence_transformer/losses.html#cachedmultiplenegativesrankingloss) with these parameters:
424
+ ```json
425
+ {
426
+ "scale": 20.0,
427
+ "similarity_fct": "cos_sim",
428
+ "mini_batch_size": 128,
429
+ "gather_across_devices": false,
430
+ "directions": [
431
+ "query_to_doc"
432
+ ],
433
+ "partition_mode": "joint",
434
+ "hardness_mode": null,
435
+ "hardness_strength": 0.0
436
+ }
437
+ ```
438
+
439
+ ### Training Hyperparameters
440
+ #### Non-Default Hyperparameters
441
+
442
+ - `eval_strategy`: steps
443
+ - `per_device_train_batch_size`: 1024
444
+ - `per_device_eval_batch_size`: 1024
445
+ - `learning_rate`: 8e-05
446
+ - `num_train_epochs`: 1
447
+ - `warmup_steps`: 0.05
448
+ - `bf16`: True
449
+ - `dataloader_num_workers`: 4
450
+ - `load_best_model_at_end`: True
451
+ - `push_to_hub`: True
452
+ - `hub_model_id`: modernbert-code-v2
453
+ - `batch_sampler`: no_duplicates
454
+
455
+ #### All Hyperparameters
456
+ <details><summary>Click to expand</summary>
457
+
458
+ - `do_predict`: False
459
+ - `eval_strategy`: steps
460
+ - `prediction_loss_only`: True
461
+ - `per_device_train_batch_size`: 1024
462
+ - `per_device_eval_batch_size`: 1024
463
+ - `gradient_accumulation_steps`: 1
464
+ - `eval_accumulation_steps`: None
465
+ - `torch_empty_cache_steps`: None
466
+ - `learning_rate`: 8e-05
467
+ - `weight_decay`: 0.0
468
+ - `adam_beta1`: 0.9
469
+ - `adam_beta2`: 0.999
470
+ - `adam_epsilon`: 1e-08
471
+ - `max_grad_norm`: 1.0
472
+ - `num_train_epochs`: 1
473
+ - `max_steps`: -1
474
+ - `lr_scheduler_type`: linear
475
+ - `lr_scheduler_kwargs`: None
476
+ - `warmup_ratio`: None
477
+ - `warmup_steps`: 0.05
478
+ - `log_level`: passive
479
+ - `log_level_replica`: warning
480
+ - `log_on_each_node`: True
481
+ - `logging_nan_inf_filter`: True
482
+ - `enable_jit_checkpoint`: False
483
+ - `save_on_each_node`: False
484
+ - `save_only_model`: False
485
+ - `restore_callback_states_from_checkpoint`: False
486
+ - `use_cpu`: False
487
+ - `seed`: 42
488
+ - `data_seed`: None
489
+ - `bf16`: True
490
+ - `fp16`: False
491
+ - `bf16_full_eval`: False
492
+ - `fp16_full_eval`: False
493
+ - `tf32`: None
494
+ - `local_rank`: -1
495
+ - `ddp_backend`: None
496
+ - `debug`: []
497
+ - `dataloader_drop_last`: False
498
+ - `dataloader_num_workers`: 4
499
+ - `dataloader_prefetch_factor`: None
500
+ - `disable_tqdm`: False
501
+ - `remove_unused_columns`: True
502
+ - `label_names`: None
503
+ - `load_best_model_at_end`: True
504
+ - `ignore_data_skip`: False
505
+ - `fsdp`: []
506
+ - `fsdp_config`: {'min_num_params': 0, 'xla': False, 'xla_fsdp_v2': False, 'xla_fsdp_grad_ckpt': False}
507
+ - `accelerator_config`: {'split_batches': False, 'dispatch_batches': None, 'even_batches': True, 'use_seedable_sampler': True, 'non_blocking': False, 'gradient_accumulation_kwargs': None}
508
+ - `parallelism_config`: None
509
+ - `deepspeed`: None
510
+ - `label_smoothing_factor`: 0.0
511
+ - `optim`: adamw_torch_fused
512
+ - `optim_args`: None
513
+ - `group_by_length`: False
514
+ - `length_column_name`: length
515
+ - `project`: huggingface
516
+ - `trackio_space_id`: trackio
517
+ - `ddp_find_unused_parameters`: None
518
+ - `ddp_bucket_cap_mb`: None
519
+ - `ddp_broadcast_buffers`: False
520
+ - `dataloader_pin_memory`: True
521
+ - `dataloader_persistent_workers`: False
522
+ - `skip_memory_metrics`: True
523
+ - `push_to_hub`: True
524
+ - `resume_from_checkpoint`: None
525
+ - `hub_model_id`: modernbert-code-v2
526
+ - `hub_strategy`: every_save
527
+ - `hub_private_repo`: None
528
+ - `hub_always_push`: False
529
+ - `hub_revision`: None
530
+ - `gradient_checkpointing`: False
531
+ - `gradient_checkpointing_kwargs`: None
532
+ - `include_for_metrics`: []
533
+ - `eval_do_concat_batches`: True
534
+ - `auto_find_batch_size`: False
535
+ - `full_determinism`: False
536
+ - `ddp_timeout`: 1800
537
+ - `torch_compile`: False
538
+ - `torch_compile_backend`: None
539
+ - `torch_compile_mode`: None
540
+ - `include_num_input_tokens_seen`: no
541
+ - `neftune_noise_alpha`: None
542
+ - `optim_target_modules`: None
543
+ - `batch_eval_metrics`: False
544
+ - `eval_on_start`: False
545
+ - `use_liger_kernel`: False
546
+ - `liger_kernel_config`: None
547
+ - `eval_use_gather_object`: False
548
+ - `average_tokens_across_devices`: True
549
+ - `use_cache`: False
550
+ - `prompts`: None
551
+ - `batch_sampler`: no_duplicates
552
+ - `multi_dataset_batch_sampler`: proportional
553
+ - `router_mapping`: {}
554
+ - `learning_rate_mapping`: {}
555
+
556
+ </details>
557
+
558
+ ### Training Logs
559
+ | Epoch | Step | Training Loss | Validation Loss | eval_cosine_ndcg@10 |
560
+ |:----------:|:-------:|:-------------:|:---------------:|:-------------------:|
561
+ | 0.0722 | 20 | 3.9983 | 1.3745 | 0.7545 |
562
+ | 0.1444 | 40 | 1.0297 | 0.7864 | 0.8493 |
563
+ | 0.2166 | 60 | 0.6830 | 0.5917 | 0.8833 |
564
+ | 0.2888 | 80 | 0.5476 | 0.5128 | 0.8973 |
565
+ | 0.3610 | 100 | 0.4891 | 0.4641 | 0.9028 |
566
+ | 0.4332 | 120 | 0.4436 | 0.4370 | 0.9098 |
567
+ | 0.5054 | 140 | 0.4304 | 0.4151 | 0.9154 |
568
+ | 0.5776 | 160 | 0.4101 | 0.3948 | 0.9161 |
569
+ | 0.6498 | 180 | 0.3910 | 0.3829 | 0.9190 |
570
+ | 0.7220 | 200 | 0.3794 | 0.3729 | 0.9188 |
571
+ | 0.7942 | 220 | 0.3668 | 0.3650 | 0.9207 |
572
+ | 0.8664 | 240 | 0.3683 | 0.3573 | 0.9230 |
573
+ | **0.9386** | **260** | **0.359** | **0.3534** | **0.9241** |
574
+
575
+ * The bold row denotes the saved checkpoint.
576
+
577
+ ### Framework Versions
578
+ - Python: 3.12.12
579
+ - Sentence Transformers: 5.3.0
580
+ - Transformers: 5.0.0
581
+ - PyTorch: 2.10.0+cu128
582
+ - Accelerate: 1.13.0
583
+ - Datasets: 4.0.0
584
+ - Tokenizers: 0.22.2
585
+
586
+ ## Citation
587
+
588
+ ### BibTeX
589
+
590
+ #### Sentence Transformers
591
+ ```bibtex
592
+ @inproceedings{reimers-2019-sentence-bert,
593
+ title = "Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks",
594
+ author = "Reimers, Nils and Gurevych, Iryna",
595
+ booktitle = "Proceedings of the 2019 Conference on Empirical Methods in Natural Language Processing",
596
+ month = "11",
597
+ year = "2019",
598
+ publisher = "Association for Computational Linguistics",
599
+ url = "https://arxiv.org/abs/1908.10084",
600
+ }
601
+ ```
602
+
603
+ #### CachedMultipleNegativesRankingLoss
604
+ ```bibtex
605
+ @misc{gao2021scaling,
606
+ title={Scaling Deep Contrastive Learning Batch Size under Memory Limited Setup},
607
+ author={Luyu Gao and Yunyi Zhang and Jiawei Han and Jamie Callan},
608
+ year={2021},
609
+ eprint={2101.06983},
610
+ archivePrefix={arXiv},
611
+ primaryClass={cs.LG}
612
+ }
613
+ ```
614
+
615
+ <!--
616
+ ## Glossary
617
+
618
+ *Clearly define terms in order to be accessible across audiences.*
619
+ -->
620
+
621
+ <!--
622
+ ## Model Card Authors
623
+
624
+ *Lists the people who create the model card, providing recognition and accountability for the detailed work that goes into its construction.*
625
+ -->
626
+
627
+ <!--
628
+ ## Model Card Contact
629
+
630
+ *Provides a way for people who have updates to the Model Card, suggestions, or questions, to contact the Model Card authors.*
631
+ -->
config_sentence_transformers.json ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model_type": "SentenceTransformer",
3
+ "__version__": {
4
+ "sentence_transformers": "5.3.0",
5
+ "transformers": "5.0.0",
6
+ "pytorch": "2.10.0+cu128"
7
+ },
8
+ "prompts": {
9
+ "query": "",
10
+ "document": ""
11
+ },
12
+ "default_prompt_name": null,
13
+ "similarity_fn_name": "cosine"
14
+ }
modules.json ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "idx": 0,
4
+ "name": "0",
5
+ "path": "",
6
+ "type": "sentence_transformers.models.Transformer"
7
+ },
8
+ {
9
+ "idx": 1,
10
+ "name": "1",
11
+ "path": "1_Pooling",
12
+ "type": "sentence_transformers.models.Pooling"
13
+ }
14
+ ]
sentence_bert_config.json ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {
2
+ "max_seq_length": 1024,
3
+ "do_lower_case": false
4
+ }