Views
No views yet
SentenceTransformer(
(0): Transformer({'max_seq_length': 512, 'do_lower_case': False, 'architecture': 'OptimizedModule'})
(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})
)pip install -U sentence-transformers1from sentence_transformers import SentenceTransformer
2
3# Download from the 🤗 Hub
4model = SentenceTransformer("modernbert-codesearchnet")
5# Run inference
6queries = [
7 "Split the data object along a given expression, in units.\n\n Parameters\n ----------\n expression : int or str\n The expression to split along. If given as an integer, the axis at that index\n is used.\n positions : number-type or 1D array-type\n The position(s) to split at, in units.\n units : str (optional)\n The units of the given positions. Default is same, which assumes\n input units are identical to first variable units.\n parent : WrightTools.Collection (optional)\n The parent collection in which to place the \u0027split\u0027 collection.\n Default is a new Collection.\n verbose : bool (optional)\n Toggle talkback. Default is True.\n\n Returns\n -------\n WrightTools.collection.Collection\n A Collection of data objects.\n The order of the objects is such that the axis points retain their original order.\n\n See Also\n --------\n chop\n Divide the dataset into its lower-dimensionality components.\n collapse\n Collapse the dataset along one axis.",
8]
9documents = [
10 'def split(\n self, expression, positions, *, units=None, parent=None, verbose=True\n ) -> wt_collection.Collection:\n """\n Split the data object along a given expression, in units.\n\n Parameters\n ----------\n expression : int or str\n The expression to split along. If given as an integer, the axis at that index\n is used.\n positions : number-type or 1D array-type\n The position(s) to split at, in units.\n units : str (optional)\n The units of the given positions. Default is same, which assumes\n input units are identical to first variable units.\n parent : WrightTools.Collection (optional)\n The parent collection in which to place the \'split\' collection.\n Default is a new Collection.\n verbose : bool (optional)\n Toggle talkback. Default is True.\n\n Returns\n -------\n WrightTools.collection.Collection\n A Collection of data objects.\n The order of the objects is such that the axis points retain their original order.\n\n See Also\n --------\n chop\n Divide the dataset into its lower-dimensionality components.\n collapse\n Collapse the dataset along one axis.\n """\n # axis ------------------------------------------------------------------------------------\n old_expr = self.axis_expressions\n old_units = self.units\n out = wt_collection.Collection(name="split", parent=parent)\n if isinstance(expression, int):\n if units is None:\n units = self._axes[expression].units\n expression = self._axes[expression].expression\n elif isinstance(expression, str):\n pass\n else:\n raise TypeError("expression: expected {int, str}, got %s" % type(expression))\n\n self.transform(expression)\n if units:\n self.convert(units)\n\n try:\n positions = [-np.inf] + sorted(list(positions)) + [np.inf]\n except TypeError:\n positions = [-np.inf, positions, np.inf]\n\n values = self._axes[0].full\n masks = [(values >= lo) & (values < hi) for lo, hi in wt_kit.pairwise(positions)]\n omasks = []\n cuts = []\n for mask in masks:\n try:\n omasks.append(wt_kit.mask_reduce(mask))\n cuts.append([i == 1 for i in omasks[-1].shape])\n # Ensure at least one axis is kept\n if np.all(cuts[-1]):\n cuts[-1][0] = False\n except ValueError:\n omasks.append(None)\n cuts.append(None)\n for i in range(len(positions) - 1):\n out.create_data("split%03i" % i)\n\n for var in self.variables:\n for i, (imask, omask, cut) in enumerate(zip(masks, omasks, cuts)):\n if omask is None:\n # Zero length split\n continue\n omask = wt_kit.enforce_mask_shape(omask, var.shape)\n omask.shape = tuple([s for s, c in zip(omask.shape, cut) if not c])\n out_arr = np.full(omask.shape, np.nan)\n imask = wt_kit.enforce_mask_shape(imask, var.shape)\n out_arr[omask] = var[:][imask]\n out[i].create_variable(values=out_arr, **var.attrs)\n\n for ch in self.channels:\n for i, (imask, omask, cut) in enumerate(zip(masks, omasks, cuts)):\n if omask is None:\n # Zero length split\n continue\n omask = wt_kit.enforce_mask_shape(omask, ch.shape)\n omask.shape = tuple([s for s, c in zip(omask.shape, cut) if not c])\n out_arr = np.full(omask.shape, np.nan)\n imask = wt_kit.enforce_mask_shape(imask, ch.shape)\n out_arr[omask] = ch[:][imask]\n out[i].create_channel(values=out_arr, **ch.attrs)\n\n if verbose:\n for d in out.values():\n try:\n d.transform(expression)\n except IndexError:\n continue\n\n print("split data into {0} pieces along <{1}>:".format(len(positions) - 1, expression))\n for i, (lo, hi) in enumerate(wt_kit.pairwise(positions)):\n new_data = out[i]\n if new_data.shape == ():\n print(" {0} : None".format(i))\n else:\n new_axis = new_data.axes[0]\n print(\n " {0} : {1:0.2f} to {2:0.2f} {3} {4}".format(\n i, lo, hi, new_axis.units, new_axis.shape\n )\n )\n\n for d in out.values():\n try:\n d.transform(*old_expr)\n keep = []\n keep_units = []\n for ax in d.axes:\n if ax.size > 1:\n keep.append(ax.expression)\n keep_units.append(ax.units)\n else:\n d.create_constant(ax.expression, verbose=False)\n d.transform(*keep)\n for ax, u in zip(d.axes, keep_units):\n ax.convert(u)\n except IndexError:\n continue\n tempax = Axis(d, expression)\n if all(\n np.all(\n np.sum(~np.isnan(tempax.masked), axis=tuple(set(range(tempax.ndim)) - {j}))\n <= 1\n )\n for j in range(tempax.ndim)\n ):\n d.create_constant(expression, verbose=False)\n self.transform(*old_expr)\n for ax, u in zip(self.axes, old_units):\n ax.convert(u)\n\n return out',
11 'def add_item(self, title, key, synonyms=None, description=None, img_url=None):\n """Adds item to a list or carousel card.\n\n A list must contain at least 2 items, each requiring a title and object key.\n\n Arguments:\n title {str} -- Name of the item object\n key {str} -- Key refering to the item.\n This string will be used to send a query to your app if selected\n\n Keyword Arguments:\n synonyms {list} -- Words and phrases the user may send to select the item\n (default: {None})\n description {str} -- A description of the item (default: {None})\n img_url {str} -- URL of the image to represent the item (default: {None})\n """\n item = build_item(title, key, synonyms, description, img_url)\n self._items.append(item)\n return self',
12 'def compare(a, b):\n """Compares two timestamps.\n\n ``a`` and ``b`` must be the same type, in addition to normal\n representations of timestamps that order naturally, they can be rfc3339\n formatted strings.\n\n Args:\n a (string|object): a timestamp\n b (string|object): another timestamp\n\n Returns:\n int: -1 if a < b, 0 if a == b or 1 if a > b\n\n Raises:\n ValueError: if a or b are not the same type\n ValueError: if a or b strings but not in valid rfc3339 format\n\n """\n a_is_text = isinstance(a, basestring)\n b_is_text = isinstance(b, basestring)\n if type(a) != type(b) and not (a_is_text and b_is_text):\n _logger.error(u\'Cannot compare %s to %s, types differ %s!=%s\',\n a, b, type(a), type(b))\n raise ValueError(u\'cannot compare inputs of differing types\')\n\n if a_is_text:\n a = from_rfc3339(a, with_nanos=True)\n b = from_rfc3339(b, with_nanos=True)\n\n if a < b:\n return -1\n elif a > b:\n return 1\n else:\n return 0',
13]
14query_embeddings = model.encode_query(queries)
15document_embeddings = model.encode_document(documents)
16print(query_embeddings.shape, document_embeddings.shape)
17# [1, 768] [3, 768]
18
19# Get the similarity scores for the embeddings
20similarities = model.similarity(query_embeddings, document_embeddings)
21print(similarities)
22# tensor([[0.9188, 0.1817, 0.1583]])evalInformationRetrievalEvaluator| Metric | Value |
|---|---|
| cosine_accuracy@1 | 0.9481 |
| cosine_accuracy@3 | 0.9703 |
| cosine_accuracy@5 | 0.9752 |
| cosine_accuracy@10 | 0.9807 |
| cosine_precision@1 | 0.9481 |
| cosine_precision@3 | 0.3234 |
| cosine_precision@5 | 0.195 |
| cosine_precision@10 | 0.0981 |
| cosine_recall@1 | 0.9481 |
| cosine_recall@3 | 0.9703 |
| cosine_recall@5 | 0.9752 |
| cosine_recall@10 | 0.9807 |
| cosine_ndcg@10 | 0.9652 |
| cosine_mrr@10 | 0.9602 |
| cosine_map@100 | 0.9606 |
query and positive| query | positive | |
|---|---|---|
| type | string | string |
| details |
|
|
| query | positive |
|---|---|
Returns group object for datacenter root group.[object Object][object Object] >>> clc.v2.Datacenter().RootGroup()[object Object] <clc.APIv2.group.Group object at 0x105feacd0>[object Object] >>> print _[object Object] WA1 Hardware | def RootGroup(self):[object Object] """Returns group object for datacenter root group.[object Object][object Object] >>> clc.v2.Datacenter().RootGroup()[object Object] <clc.APIv2.group.Group object at 0x105feacd0>[object Object] >>> print _[object Object] WA1 Hardware[object Object][object Object] """[object Object][object Object] return(clc.v2.Group(id=self.root_group_id,alias=self.alias,session=self.session)) |
Calculate the euclidean distance of all array positions in "matchArr".[object Object][object Object] :param matchArr: a dictionary of [object Object] containing at least two[object Object] entries that are treated as cartesian coordinates.[object Object] :param tKey: #TODO: docstring[object Object] :param mKey: #TODO: docstring[object Object][object Object] :returns: #TODO: docstring[object Object][object Object] {'eucDist': numpy.array([eucDistance, eucDistance, ...]),[object Object] 'posPairs': numpy.array([[pos1, pos2], [pos1, pos2], ...])[object Object] } | def calcDistMatchArr(matchArr, tKey, mKey):[object Object] """Calculate the euclidean distance of all array positions in "matchArr".[object Object][object Object] :param matchArr: a dictionary of [object Object] containing at least two[object Object] entries that are treated as cartesian coordinates.[object Object] :param tKey: #TODO: docstring[object Object] :param mKey: #TODO: docstring[object Object][object Object] :returns: #TODO: docstring[object Object][object Object] {'eucDist': numpy.array([eucDistance, eucDistance, ...]),[object Object] 'posPairs': numpy.array([[pos1, pos2], [pos1, pos2], ...])[object Object] }[object Object] """[object Object] #Calculate all sorted list of all eucledian feature distances[object Object] matchArrSize = listvalues(matchArr)[0].size[object Object][object Object] distInfo = {'posPairs': list(), 'eucDist': list()}[object Object] _matrix = numpy.swapaxes(numpy.array([matchArr[tKey], matchArr[mKey]]), 0, 1)[object Object][object Object] for pos1 in range(matchArrSize-1):[object Object] for pos2 in range(pos1+1, matchArrSize):[object Object] distInfo['posPairs'].append((pos1, pos2))[object Object] distInfo['posPairs'] = numpy.array(distInfo['posPairs'])[object Object] distInfo['eucD... |
Format this verifier[object Object][object Object] Returns:[object Object] string: A formatted string | def format(self, indent_level, indent_size=4):[object Object] """Format this verifier[object Object][object Object] Returns:[object Object] string: A formatted string[object Object] """[object Object][object Object] name = self.format_name('Literal', indent_size)[object Object][object Object] if self.long_desc is not None:[object Object] name += '\n'[object Object][object Object] name += self.wrap_lines('value: %s\n' % str(self._literal), 1, indent_size)[object Object][object Object] return self.wrap_lines(name, indent_level, indent_size) |
CachedMultipleNegativesRankingLoss with these parameters:
1{
2 "scale": 20.0,
3 "similarity_fct": "cos_sim",
4 "mini_batch_size": 64,
5 "gather_across_devices": false,
6 "directions": [
7 "query_to_doc"
8 ],
9 "partition_mode": "joint",
10 "hardness_mode": null,
11 "hardness_strength": 0.0
12}query and positive| query | positive | |
|---|---|---|
| type | string | string |
| details |
|
|
| query | positive |
|---|---|
Create a new ParticipantInstance[object Object][object Object] :param unicode attributes: An optional string metadata field you can use to store any data you wish.[object Object] :param unicode twilio_address: The address of the Twilio phone number that the participant is in contact with.[object Object] :param datetime date_created: The date that this resource was created.[object Object] :param datetime date_updated: The date that this resource was last updated.[object Object] :param unicode identity: A unique string identifier for the session participant as Chat User.[object Object] :param unicode user_address: The address of the participant's device.[object Object][object Object] :returns: Newly created ParticipantInstance[object Object] :rtype: twilio.rest.messaging.v1.session.participant.ParticipantInstance | def create(self, attributes=values.unset, twilio_address=values.unset,[object Object] date_created=values.unset, date_updated=values.unset,[object Object] identity=values.unset, user_address=values.unset):[object Object] """[object Object] Create a new ParticipantInstance[object Object][object Object] :param unicode attributes: An optional string metadata field you can use to store any data you wish.[object Object] :param unicode twilio_address: The address of the Twilio phone number that the participant is in contact with.[object Object] :param datetime date_created: The date that this resource was created.[object Object] :param datetime date_updated: The date that this resource was last updated.[object Object] :param unicode identity: A unique string identifier for the session participant as Chat User.[object Object] :param unicode user_address: The address of the participant's device.[object Object][object Object] :returns: Newly created ParticipantInstance[object Object] :rtype: twilio.rest.messaging.v1.session.participant.ParticipantInstance[object Object] """[object Object] data = values.o... |
It returns absolute url defined by node related to this page | def get_absolute_url(self):[object Object] """[object Object] It returns absolute url defined by node related to this page[object Object] """[object Object] try:[object Object] node = Node.objects.select_related().filter(page=self)[0][object Object] return node.get_absolute_url()[object Object] except Exception, e:[object Object] raise ValueError(u"Error in {0}.{1}: {2}".format(self.[object Object], self.[object Object].[object Object], e))[object Object] return u"" |
Return the current scaled font.[object Object][object Object] :return:[object Object] A new :class:[object Object] object,[object Object] wrapping an existing cairo object. | def get_scaled_font(self):[object Object] """Return the current scaled font.[object Object][object Object] :return:[object Object] A new :class:[object Object] object,[object Object] wrapping an existing cairo object.[object Object][object Object] """[object Object] return ScaledFont._from_pointer([object Object] cairo.cairo_get_scaled_font(self._pointer), incref=True) |
CachedMultipleNegativesRankingLoss with these parameters:
1{
2 "scale": 20.0,
3 "similarity_fct": "cos_sim",
4 "mini_batch_size": 64,
5 "gather_across_devices": false,
6 "directions": [
7 "query_to_doc"
8 ],
9 "partition_mode": "joint",
10 "hardness_mode": null,
11 "hardness_strength": 0.0
12}per_device_train_batch_size: 8192num_train_epochs: 1learning_rate: 2e-06warmup_steps: 0.1bf16: Trueeval_strategy: epochper_device_eval_batch_size: 8192push_to_hub: Truehub_model_id: modernbert-codesearchnetload_best_model_at_end: Truedataloader_num_workers: 4batch_sampler: no_duplicatesper_device_train_batch_size: 8192num_train_epochs: 1max_steps: -1learning_rate: 2e-06lr_scheduler_type: linearlr_scheduler_kwargs: Nonewarmup_steps: 0.1optim: adamw_torch_fusedoptim_args: Noneweight_decay: 0.0adam_beta1: 0.9adam_beta2: 0.999adam_epsilon: 1e-08optim_target_modules: Nonegradient_accumulation_steps: 1average_tokens_across_devices: Truemax_grad_norm: 1.0label_smoothing_factor: 0.0bf16: Truefp16: Falsebf16_full_eval: Falsefp16_full_eval: Falsetf32: Nonegradient_checkpointing: Falsegradient_checkpointing_kwargs: Nonetorch_compile: Falsetorch_compile_backend: Nonetorch_compile_mode: Noneuse_liger_kernel: Falseliger_kernel_config: Noneuse_cache: Falseneftune_noise_alpha: Nonetorch_empty_cache_steps: Noneauto_find_batch_size: Falselog_on_each_node: Truelogging_nan_inf_filter: Trueinclude_num_input_tokens_seen: nolog_level: passivelog_level_replica: warningdisable_tqdm: Falseproject: huggingfacetrackio_space_id: trackioeval_strategy: epochper_device_eval_batch_size: 8192prediction_loss_only: Trueeval_on_start: Falseeval_do_concat_batches: Trueeval_use_gather_object: Falseeval_accumulation_steps: Noneinclude_for_metrics: []batch_eval_metrics: Falsesave_only_model: Falsesave_on_each_node: Falseenable_jit_checkpoint: Falsepush_to_hub: Truehub_private_repo: Nonehub_model_id: modernbert-codesearchnethub_strategy: every_savehub_always_push: Falsehub_revision: Noneload_best_model_at_end: Trueignore_data_skip: Falserestore_callback_states_from_checkpoint: Falsefull_determinism: Falseseed: 42data_seed: Noneuse_cpu: Falseaccelerator_config: {'split_batches': False, 'dispatch_batches': None, 'even_batches': True, 'use_seedable_sampler': True, 'non_blocking': False, 'gradient_accumulation_kwargs': None}parallelism_config: Nonedataloader_drop_last: Falsedataloader_num_workers: 4dataloader_pin_memory: Truedataloader_persistent_workers: Falsedataloader_prefetch_factor: Noneremove_unused_columns: Truelabel_names: Nonetrain_sampling_strategy: randomlength_column_name: lengthddp_find_unused_parameters: Noneddp_bucket_cap_mb: Noneddp_broadcast_buffers: Falseddp_backend: Noneddp_timeout: 1800fsdp: []fsdp_config: {'min_num_params': 0, 'xla': False, 'xla_fsdp_v2': False, 'xla_fsdp_grad_ckpt': False}deepspeed: Nonedebug: []skip_memory_metrics: Truedo_predict: Falseresume_from_checkpoint: Nonewarmup_ratio: Nonelocal_rank: -1prompts: Nonebatch_sampler: no_duplicatesmulti_dataset_batch_sampler: proportionalrouter_mapping: {}learning_rate_mapping: {}| Epoch | Step | Training Loss | Validation Loss | eval_cosine_ndcg@10 |
|---|---|---|---|---|
| 0.2174 | 10 | 0.9210 | - | - |
| 0.4348 | 20 | 0.6679 | - | - |
| 0.6522 | 30 | 0.5007 | - | - |
| 0.8696 | 40 | 0.4181 | - | - |
| 1.0 | 46 | - | 0.0328 | 0.9652 |
1@inproceedings{reimers-2019-sentence-bert,
2 title = "Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks",
3 author = "Reimers, Nils and Gurevych, Iryna",
4 booktitle = "Proceedings of the 2019 Conference on Empirical Methods in Natural Language Processing",
5 month = "11",
6 year = "2019",
7 publisher = "Association for Computational Linguistics",
8 url = "https://arxiv.org/abs/1908.10084",
9}1@misc{gao2021scaling,
2 title={Scaling Deep Contrastive Learning Batch Size under Memory Limited Setup},
3 author={Luyu Gao and Yunyi Zhang and Jiawei Han and Jamie Callan},
4 year={2021},
5 eprint={2101.06983},
6 archivePrefix={arXiv},
7 primaryClass={cs.LG}
8}