SentenceTransformer based on Shuu12121/CodeModernBERT-Owl-4.1
This is a sentence-transformers model finetuned from Shuu12121/CodeModernBERT-Owl-4.1. 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.
Model Details
Model Description
- Model Type: Sentence Transformer
- Base model: Shuu12121/CodeModernBERT-Owl-4.1
- Maximum Sequence Length: 1024 tokens
- Output Dimensionality: 768 dimensions
- Similarity Function: Cosine Similarity
Model Sources
- Documentation: Sentence Transformers Documentation
- Repository: Sentence Transformers on GitHub
- Hugging Face: Sentence Transformers on Hugging Face
Full Model Architecture
SentenceTransformer(
(0): Transformer({'max_seq_length': 1024, 'do_lower_case': False, 'architecture': 'ModernBertModel'})
(1): Pooling({'word_embedding_dimension': 768, 'pooling_mode_cls_token': True, 'pooling_mode_mean_tokens': False, 'pooling_mode_max_tokens': False, 'pooling_mode_mean_sqrt_len_tokens': False, 'pooling_mode_weightedmean_tokens': False, 'pooling_mode_lasttoken': False, 'include_prompt': True})
)
Usage
Direct Usage (Sentence Transformers)
First install the Sentence Transformers library:
pip install -U sentence-transformers
Then you can load this model and run inference.
from sentence_transformers import SentenceTransformer
# Download from the 🤗 Hub
model = SentenceTransformer("sentence_transformers_model_id")
# Run inference
sentences = [
'// reBuild partially rebuilds a site given the filesystem events.\n// It returns whetever the content source was changed.\n// TODO(bep) clean up/rewrite this method.',
'func (s *Site) processPartial(events []fsnotify.Event) (whatChanged, error) {\n\n\tevents = s.filterFileEvents(events)\n\tevents = s.translateFileEvents(events)\n\n\ts.Log.DEBUG.Printf("Rebuild for events %q", events)\n\n\th := s.h\n\n\t// First we need to determine what changed\n\n\tvar (\n\t\tsourceChanged = []fsnotify.Event{}\n\t\tsourceReallyChanged = []fsnotify.Event{}\n\t\tcontentFilesChanged []string\n\t\ttmplChanged = []fsnotify.Event{}\n\t\tdataChanged = []fsnotify.Event{}\n\t\ti18nChanged = []fsnotify.Event{}\n\t\tshortcodesChanged = make(map[string]bool)\n\t\tsourceFilesChanged = make(map[string]bool)\n\n\t\t// prevent spamming the log on changes\n\t\tlogger = helpers.NewDistinctFeedbackLogger()\n\t)\n\n\tcachePartitions := make([]string, len(events))\n\n\tfor i, ev := range events {\n\t\tcachePartitions[i] = resources.ResourceKeyPartition(ev.Name)\n\n\t\tif s.isContentDirEvent(ev) {\n\t\t\tlogger.Println("Source changed", ev)\n\t\t\tsourceChanged = append(sourceChanged, ev)\n\t\t}\n\t\tif s.isLayoutDirEvent(ev) {\n\t\t\tlogger.Println("Template changed", ev)\n\t\t\ttmplChanged = append(tmplChanged, ev)\n\n\t\t\tif strings.Contains(ev.Name, "shortcodes") {\n\t\t\t\tshortcode := filepath.Base(ev.Name)\n\t\t\t\tshortcode = strings.TrimSuffix(shortcode, filepath.Ext(shortcode))\n\t\t\t\tshortcodesChanged[shortcode] = true\n\t\t\t}\n\t\t}\n\t\tif s.isDataDirEvent(ev) {\n\t\t\tlogger.Println("Data changed", ev)\n\t\t\tdataChanged = append(dataChanged, ev)\n\t\t}\n\t\tif s.isI18nEvent(ev) {\n\t\t\tlogger.Println("i18n changed", ev)\n\t\t\ti18nChanged = append(dataChanged, ev)\n\t\t}\n\t}\n\n\t// These in memory resource caches will be rebuilt on demand.\n\tfor _, s := range s.h.Sites {\n\t\ts.ResourceSpec.ResourceCache.DeletePartitions(cachePartitions...)\n\t}\n\n\tif len(tmplChanged) > 0 || len(i18nChanged) > 0 {\n\t\tsites := s.h.Sites\n\t\tfirst := sites[0]\n\n\t\ts.h.init.Reset()\n\n\t\t// TOD(bep) globals clean\n\t\tif err := first.Deps.LoadResources(); err != nil {\n\t\t\treturn whatChanged{}, err\n\t\t}\n\n\t\tfor i := 1; i < len(sites); i++ {\n\t\t\tsite := sites[i]\n\t\t\tvar err error\n\t\t\tdepsCfg := deps.DepsCfg{\n\t\t\t\tLanguage: site.language,\n\t\t\t\tMediaTypes: site.mediaTypesConfig,\n\t\t\t\tOutputFormats: site.outputFormatsConfig,\n\t\t\t}\n\t\t\tsite.Deps, err = first.Deps.ForLanguage(depsCfg, func(d *deps.Deps) error {\n\t\t\t\td.Site = &site.Info\n\t\t\t\treturn nil\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\treturn whatChanged{}, err\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(dataChanged) > 0 {\n\t\ts.h.init.data.Reset()\n\t}\n\n\tfor _, ev := range sourceChanged {\n\t\tremoved := false\n\n\t\tif ev.Op&fsnotify.Remove == fsnotify.Remove {\n\t\t\tremoved = true\n\t\t}\n\n\t\t// Some editors (Vim) sometimes issue only a Rename operation when writing an existing file\n\t\t// Sometimes a rename operation means that file has been renamed other times it means\n\t\t// it\'s been updated\n\t\tif ev.Op&fsnotify.Rename == fsnotify.Rename {\n\t\t\t// If the file is still on disk, it\'s only been updated, if it\'s not, it\'s been moved\n\t\t\tif ex, err := afero.Exists(s.Fs.Source, ev.Name); !ex || err != nil {\n\t\t\t\tremoved = true\n\t\t\t}\n\t\t}\n\t\tif removed && IsContentFile(ev.Name) {\n\t\t\th.removePageByFilename(ev.Name)\n\t\t}\n\n\t\tsourceReallyChanged = append(sourceReallyChanged, ev)\n\t\tsourceFilesChanged[ev.Name] = true\n\t}\n\n\tfor shortcode := range shortcodesChanged {\n\t\t// There are certain scenarios that, when a shortcode changes,\n\t\t// it isn\'t sufficient to just rerender the already parsed shortcode.\n\t\t// One example is if the user adds a new shortcode to the content file first,\n\t\t// and then creates the shortcode on the file system.\n\t\t// To handle these scenarios, we must do a full reprocessing of the\n\t\t// pages that keeps a reference to the changed shortcode.\n\t\tpagesWithShortcode := h.findPagesByShortcode(shortcode)\n\t\tfor _, p := range pagesWithShortcode {\n\t\t\tcontentFilesChanged = append(contentFilesChanged, p.File().Filename())\n\t\t}\n\t}\n\n\tif len(sourceReallyChanged) > 0 || len(contentFilesChanged) > 0 {\n\t\tvar filenamesChanged []string\n\t\tfor _, e := range sourceReallyChanged {\n\t\t\tfilenamesChanged = append(filenamesChanged, e.Name)\n\t\t}\n\t\tif len(contentFilesChanged) > 0 {\n\t\t\tfilenamesChanged = append(filenamesChanged, contentFilesChanged...)\n\t\t}\n\n\t\tfilenamesChanged = helpers.UniqueStrings(filenamesChanged)\n\n\t\tif err := s.readAndProcessContent(filenamesChanged...); err != nil {\n\t\t\treturn whatChanged{}, err\n\t\t}\n\n\t}\n\n\tchanged := whatChanged{\n\t\tsource: len(sourceChanged) > 0 || len(shortcodesChanged) > 0,\n\t\tother: len(tmplChanged) > 0 || len(i18nChanged) > 0 || len(dataChanged) > 0,\n\t\tfiles: sourceFilesChanged,\n\t}\n\n\treturn changed, nil\n\n}',
'func WebPageImageResolver(doc *goquery.Document) ([]candidate, int) {\n\timgs := doc.Find("img")\n\n\tvar candidates []candidate\n\tsignificantSurface := 320 * 200\n\tsignificantSurfaceCount := 0\n\tsrc := ""\n\timgs.Each(func(i int, tag *goquery.Selection) {\n\t\tvar surface int\n\t\tsrc = getImageSrc(tag)\n\t\tif src == "" {\n\t\t\treturn\n\t\t}\n\n\t\twidth, _ := tag.Attr("width")\n\t\theight, _ := tag.Attr("height")\n\t\tif width != "" {\n\t\t\tw, _ := strconv.Atoi(width)\n\t\t\tif height != "" {\n\t\t\t\th, _ := strconv.Atoi(height)\n\t\t\t\tsurface = w * h\n\t\t\t} else {\n\t\t\t\tsurface = w\n\t\t\t}\n\t\t} else {\n\t\t\tif height != "" {\n\t\t\t\tsurface, _ = strconv.Atoi(height)\n\t\t\t} else {\n\t\t\t\tsurface = 0\n\t\t\t}\n\t\t}\n\n\t\tif surface > significantSurface {\n\t\t\tsignificantSurfaceCount++\n\t\t}\n\n\t\ttagscore := score(tag)\n\t\tif tagscore >= 0 {\n\t\t\tc := candidate{\n\t\t\t\turl: src,\n\t\t\t\tsurface: surface,\n\t\t\t\tscore: score(tag),\n\t\t\t}\n\t\t\tcandidates = append(candidates, c)\n\t\t}\n\t})\n\n\tif len(candidates) == 0 {\n\t\treturn nil, 0\n\t}\n\n\treturn candidates, significantSurfaceCount\n\n}',
]
embeddings = model.encode(sentences)
print(embeddings.shape)
# [3, 768]
# Get the similarity scores for the embeddings
similarities = model.similarity(embeddings, embeddings)
print(similarities)
# tensor([[1.0000, 0.6794, 0.2371],
# [0.6794, 1.0000, 0.2193],
# [0.2371, 0.2193, 1.0000]])
Training Details
Training Dataset
Unnamed Dataset
- Size: 58,800 training samples
- Columns:
sentence_0,sentence_1, andlabel - Approximate statistics based on the first 1000 samples:
sentence_0 sentence_1 label type string string float details - min: 3 tokens
- mean: 54.95 tokens
- max: 1001 tokens
- min: 28 tokens
- mean: 177.54 tokens
- max: 1024 tokens
- min: 1.0
- mean: 1.0
- max: 1.0
- Samples:
sentence_0 sentence_1 label // CASNext is a non-callback, loop-based version of CAS method.
//
// Usage is like this:
//
// var state memcached.CASState
// for client.CASNext(vb, key, exp, &state) {
// state.Value = some_mutation(state.Value)
// }
// if state.Err != nil { ... }func (c *Client) CASNext(vb uint16, k string, exp int, state *CASState) bool {
if state.initialized {
if !state.Exists {
// Adding a new key:
if state.Value == nil {
state.Cas = 0
return false // no-op (delete of non-existent value)
}
state.resp, state.Err = c.Add(vb, k, 0, exp, state.Value)
} else {
// Updating / deleting a key:
req := &gomemcached.MCRequest{
Opcode: gomemcached.DELETE,
VBucket: vb,
Key: []byte(k),
Cas: state.Cas}
if state.Value != nil {
req.Opcode = gomemcached.SET
req.Opaque = 0
req.Extras = []byte{0, 0, 0, 0, 0, 0, 0, 0}
req.Body = state.Value
flags := 0
exp := 0 // ??? Should we use initialexp here instead?
binary.BigEndian.PutUint64(req.Extras, uint64(flags)<<32uint64(exp))
}
state.resp, state.Err = c.Send(req)
}
// If the response status is KEY_EEXISTS or NOT_STORED there's a conflict and we'll need to
// get the new value (below). Otherwise, we're done (either ...// RestoreResourcePools restores a bulk of resource pools, usually from a backup.func (f *Facade) RestoreResourcePools(ctx datastore.Context, pools []pool.ResourcePool) error {
defer ctx.Metrics().Stop(ctx.Metrics().Start("Facade.RestoreResourcePools"))
// Do not DFSLock here, ControlPlaneDao does that
var alog audit.Logger
for _, pool := range pools {
alog = f.auditLogger.Message(ctx, "Adding ResourcePool").Action(audit.Add).Entity(&pool)
pool.DatabaseVersion = 0
if err := f.addResourcePool(ctx, &pool); err != nil {
if err == ErrPoolExists {
if err := f.updateResourcePool(ctx, &pool); err != nil {
glog.Errorf("Could not restore resource pool %s via update: %s", pool.ID, err)
return alog.Error(err)
}
} else {
glog.Errorf("Could not restore resource pool %s via add: %s", pool.ID, err)
return alog.Error(err)
}
}
alog.Succeeded()
}
return nil
}1.0// run starts a goroutine to handle client connects and broadcast events.func (s *Streamer) run() {
go func() {
for {
select {
case cl := <-s.connecting:
s.clients[cl] = true
case cl := <-s.disconnecting:
delete(s.clients, cl)
case event := <-s.event:
for cl := range s.clients {
// TODO: non-blocking broadcast
//select {
//case cl <- event: // Try to send event to client
//default:
// fmt.Println("Channel full. Discarding value")
//}
cl <- event
}
}
}
}()
}1.0 - Loss:
MultipleNegativesRankingLosswith these parameters:{ "scale": 20.0, "similarity_fct": "cos_sim" }
Training Hyperparameters
Non-Default Hyperparameters
per_device_train_batch_size: 200per_device_eval_batch_size: 200fp16: Truemulti_dataset_batch_sampler: round_robin
All Hyperparameters
Click to expand
overwrite_output_dir: Falsedo_predict: Falseeval_strategy: noprediction_loss_only: Trueper_device_train_batch_size: 200per_device_eval_batch_size: 200per_gpu_train_batch_size: Noneper_gpu_eval_batch_size: Nonegradient_accumulation_steps: 1eval_accumulation_steps: Nonetorch_empty_cache_steps: Nonelearning_rate: 5e-05weight_decay: 0.0adam_beta1: 0.9adam_beta2: 0.999adam_epsilon: 1e-08max_grad_norm: 1num_train_epochs: 3max_steps: -1lr_scheduler_type: linearlr_scheduler_kwargs: {}warmup_ratio: 0.0warmup_steps: 0log_level: passivelog_level_replica: warninglog_on_each_node: Truelogging_nan_inf_filter: Truesave_safetensors: Truesave_on_each_node: Falsesave_only_model: Falserestore_callback_states_from_checkpoint: Falseno_cuda: Falseuse_cpu: Falseuse_mps_device: Falseseed: 42data_seed: Nonejit_mode_eval: Falseuse_ipex: Falsebf16: Falsefp16: Truefp16_opt_level: O1half_precision_backend: autobf16_full_eval: Falsefp16_full_eval: Falsetf32: Nonelocal_rank: 0ddp_backend: Nonetpu_num_cores: Nonetpu_metrics_debug: Falsedebug: []dataloader_drop_last: Falsedataloader_num_workers: 0dataloader_prefetch_factor: Nonepast_index: -1disable_tqdm: Falseremove_unused_columns: Truelabel_names: Noneload_best_model_at_end: Falseignore_data_skip: Falsefsdp: []fsdp_min_num_params: 0fsdp_config: {'min_num_params': 0, 'xla': False, 'xla_fsdp_v2': False, 'xla_fsdp_grad_ckpt': False}fsdp_transformer_layer_cls_to_wrap: Noneaccelerator_config: {'split_batches': False, 'dispatch_batches': None, 'even_batches': True, 'use_seedable_sampler': True, 'non_blocking': False, 'gradient_accumulation_kwargs': None}deepspeed: Nonelabel_smoothing_factor: 0.0optim: adamw_torchoptim_args: Noneadafactor: Falsegroup_by_length: Falselength_column_name: lengthddp_find_unused_parameters: Noneddp_bucket_cap_mb: Noneddp_broadcast_buffers: Falsedataloader_pin_memory: Truedataloader_persistent_workers: Falseskip_memory_metrics: Trueuse_legacy_prediction_loop: Falsepush_to_hub: Falseresume_from_checkpoint: Nonehub_model_id: Nonehub_strategy: every_savehub_private_repo: Nonehub_always_push: Falsehub_revision: Nonegradient_checkpointing: Falsegradient_checkpointing_kwargs: Noneinclude_inputs_for_metrics: Falseinclude_for_metrics: []eval_do_concat_batches: Truefp16_backend: autopush_to_hub_model_id: Nonepush_to_hub_organization: Nonemp_parameters:auto_find_batch_size: Falsefull_determinism: Falsetorchdynamo: Noneray_scope: lastddp_timeout: 1800torch_compile: Falsetorch_compile_backend: Nonetorch_compile_mode: Noneinclude_tokens_per_second: Falseinclude_num_input_tokens_seen: Falseneftune_noise_alpha: Noneoptim_target_modules: Nonebatch_eval_metrics: Falseeval_on_start: Falseuse_liger_kernel: Falseliger_kernel_config: Noneeval_use_gather_object: Falseaverage_tokens_across_devices: Falseprompts: Nonebatch_sampler: batch_samplermulti_dataset_batch_sampler: round_robinrouter_mapping: {}learning_rate_mapping: {}
Training Logs
| Epoch | Step | Training Loss |
|---|---|---|
| 1.7007 | 500 | 0.2766 |
Framework Versions
- Python: 3.10.12
- Sentence Transformers: 5.0.0
- Transformers: 4.53.1
- PyTorch: 2.7.0+cu128
- Accelerate: 1.7.0
- Datasets: 3.6.0
- Tokenizers: 0.21.2
Citation
BibTeX
Sentence Transformers
@inproceedings{reimers-2019-sentence-bert,
title = "Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks",
author = "Reimers, Nils and Gurevych, Iryna",
booktitle = "Proceedings of the 2019 Conference on Empirical Methods in Natural Language Processing",
month = "11",
year = "2019",
publisher = "Association for Computational Linguistics",
url = "https://arxiv.org/abs/1908.10084",
}
MultipleNegativesRankingLoss
@misc{henderson2017efficient,
title={Efficient Natural Language Response Suggestion for Smart Reply},
author={Matthew Henderson and Rami Al-Rfou and Brian Strope and Yun-hsuan Sung and Laszlo Lukacs and Ruiqi Guo and Sanjiv Kumar and Balint Miklos and Ray Kurzweil},
year={2017},
eprint={1705.00652},
archivePrefix={arXiv},
primaryClass={cs.CL}
}
- Downloads last month
- 3
Model tree for Shuu12121/CodeSearch-ModernBERT-Owl-4.1-Small-Fine-tuned-200
Base model
Shuu12121/CodeModernBERT-Owl-4.1