Feature Extraction
Transformers
Safetensors
sentence-transformers
English
Chinese
c2llm
code
custom_code
Run this model with HF Jobs
Run codefuse-ai/C2LLM-0.5B on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs to fine-tune https://huggingface.co/codefuse-ai/C2LLM-0.5B. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/codefuse-ai/C2LLM-0.5B on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Instructions to use codefuse-ai/C2LLM-0.5B with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use codefuse-ai/C2LLM-0.5B with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("feature-extraction", model="codefuse-ai/C2LLM-0.5B", trust_remote_code=True)# pip install -U transformers accelerate # Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("codefuse-ai/C2LLM-0.5B", trust_remote_code=True, device_map="auto") - sentence-transformers
How to use codefuse-ai/C2LLM-0.5B with sentence-transformers:
from sentence_transformers import SentenceTransformer model = SentenceTransformer("codefuse-ai/C2LLM-0.5B", trust_remote_code=True) sentences = [ "The weather is lovely today.", "It's so sunny outside!", "He drove to the stadium." ] embeddings = model.encode(sentences) similarities = model.similarity(embeddings, embeddings) print(similarities.shape) # [3, 3] - Notebooks
- Google Colab
- Kaggle
Upload folder using huggingface_hub
Browse filesFiles changed (15)
- .gitattributes+1
- added_tokens.jsonAdded+24
- config.jsonAdded+38
- config_sentence_transformers.jsonAdded+8
- configuration_c2llm.pyAdded+87
- custom_transformer.pyAdded+45
- merges.txtAdded
- model.safetensorsAdded+3
- modeling_c2llm.pyAdded+641
- modules.jsonAdded+8
- sentence_bert_config.jsonAdded+4
- special_tokens_map.jsonAdded+31
- tokenizer.jsonAdded+3
- tokenizer_config.jsonAdded+208
- vocab.jsonAdded
32 unmodified lines33343532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text32 unmodified lines3334353632 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -texttokenizer.json filter=lfs diff=lfs merge=lfs -text
123456789101112131415161718192021222324{ "</tool_call>": 151658, "<tool_call>": 151657, "<|box_end|>": 151649, "<|box_start|>": 151648, "<|endoftext|>": 151643, "<|file_sep|>": 151664, "<|fim_middle|>": 151660, "<|fim_pad|>": 151662, "<|fim_prefix|>": 151659, "<|fim_suffix|>": 151661, "<|im_end|>": 151645, "<|im_start|>": 151644, "<|image_pad|>": 151655, "<|object_ref_end|>": 151647, "<|object_ref_start|>": 151646, "<|quad_end|>": 151651, "<|quad_start|>": 151650, "<|repo_name|>": 151663, "<|video_pad|>": 151656, "<|vision_end|>": 151653, "<|vision_pad|>": 151654, "<|vision_start|>": 151652}1234567891011121314151617181920212223242526272829303132333435363738{ "architectures": [ "C2LLMForEmbedding" ], "attention_dropout": 0.0, "attn_implementation": "flash_attention_2", "auto_map": { "AutoConfig": "configuration_c2llm.C2LLMConfig", "AutoModel": "modeling_c2llm.C2LLMForEmbedding" }, "compressed_dim": 896, "dtype": "bfloat16", "embedding_method": "pma", "hidden_act": "silu", "hidden_size": 896, "initializer_range": 0.02, "intermediate_size": 4864, "max_position_embeddings": 32768, "max_window_layers": 24, "model_type": "c2llm", "num_attention_heads": 14, "num_hidden_layers": 24, "num_key_value_heads": 2, "padding_side": "left", "pma_ln": true, "pma_norm": false, "pma_norm_mode": "post_normal", "pma_num_heads": 32, "rms_norm_eps": 1e-06, "rope_theta": 1000000.0, "sliding_window": null, "tokenizer_name_or_path": "codefuse-ai/C2LLM-0.5B", "torch_dtype": "bfloat16", "transformers_version": "4.51.3", "use_cache": true, "use_sliding_window": false, "vocab_size": 151936}12345678{ "prompts": { "query": "Given a query from a web search, retrieve code that is helpful in addressing the query.\n", "document": "Retrieved Answer:" }, "default_prompt_name": null, "similarity_fn_name": "cosine"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687from transformers import PretrainedConfig
class C2LLMConfig(PretrainedConfig): model_type = "c2llm" keys_to_ignore_at_inference = ["past_key_values"]
base_model_tp_plan = { "layers.*.self_attn.q_proj": "colwise", "layers.*.self_attn.k_proj": "colwise", "layers.*.self_attn.v_proj": "colwise", "layers.*.self_attn.o_proj": "rowwise", "layers.*.mlp.gate_proj": "colwise", "layers.*.mlp.up_proj": "colwise", "layers.*.mlp.down_proj": "rowwise", } base_model_pp_plan = { "embed_tokens": (["input_ids"], ["inputs_embeds"]), "layers": (["hidden_states", "attention_mask"], ["hidden_states"]), "norm": (["hidden_states"], ["hidden_states"]), }
def __init__( self, attention_dropout=0.0, bos_token_id=151643, eos_token_id=151643, hidden_act="silu", hidden_size=896, initializer_range=0.02, intermediate_size=4864, max_position_embeddings=32768, max_window_layers=24, model_type="c2llm", num_attention_heads=14, num_hidden_layers=24, num_key_value_heads=2, rms_norm_eps=1e-6, rope_theta=1000000.0, sliding_window=32768, tie_word_embeddings=True, torch_dtype="bfloat16", transformers_version="4.43.1", use_cache=True, use_sliding_window=False, vocab_size=151936, **kwargs, ): self.vocab_size = vocab_size self.max_position_embeddings = max_position_embeddings self.hidden_size = hidden_size self.intermediate_size = intermediate_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads self.use_sliding_window = use_sliding_window self.sliding_window = sliding_window if use_sliding_window else None self.max_window_layers = max_window_layers
# for backward compatibility if num_key_value_heads is None: num_key_value_heads = num_attention_heads
self.num_key_value_heads = num_key_value_heads self.hidden_act = hidden_act self.initializer_range = initializer_range self.rms_norm_eps = rms_norm_eps self.use_cache = use_cache self.rope_theta = rope_theta self.attention_dropout = attention_dropout
super().__init__( tie_word_embeddings=tie_word_embeddings, **kwargs, ) def to_dict(self): output = super().to_dict() keys_to_remove = [ "base_model" ] for key in keys_to_remove: output.pop(key, None) return output __all__ = ["C2LLMConfig"]123456789101112131415161718192021222324252627282930313233343536373839404142434445from __future__ import annotations
import inspectimport loggingimport osfrom collections.abc import Callablefrom pathlib import Pathfrom typing import TYPE_CHECKING, Any
from sentence_transformers.backend import load_onnx_model, load_openvino_model
try: from typing import Selfexcept ImportError: from typing_extensions import Self
import torchfrom transformers import AutoConfig, AutoModel, AutoTokenizer, MT5Config, PretrainedConfig, T5Configfrom transformers.utils.import_utils import is_peft_availablefrom transformers.utils.peft_utils import find_adapter_config_file
from sentence_transformers.models.InputModule import InputModule
logger = logging.getLogger(__name__)
if TYPE_CHECKING and is_peft_available(): from peft import PeftConfigfrom sentence_transformers.models import Transformer
class C2LLMTransformer(Transformer): config_file_name: str = "sentence_bert_config.json" config_keys: list[str] = ["max_seq_length", "do_lower_case"] save_in_root: bool = True
def forward(self, features: dict[str, torch.Tensor], **kwargs) -> dict[str, torch.Tensor]: trans_features = {key: value for key, value in features.items() if key in self.model_forward_params}
outputs = self.auto_model(**trans_features, **kwargs, return_dict=True) sentence_embedding = outputs["sentence_embedding"] features["sentence_embedding"] = sentence_embedding
return features123version https://git-lfs.github.com/spec/v1oid sha256:97aa3034776e942f09edc3df63c462ce6015c9e0a96d09e63070e334a96c484dsize 994540592123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641import osimport gcimport inspectimport mathimport multiprocessing as mpimport queuefrom multiprocessing import Queueimport warningsfrom typing import Any, Union, List, Dict, Literal, Optionalimport torchimport torch.nn.functional as Fimport torch.utils.checkpointfrom torch import nnfrom torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELossfrom transformers import PretrainedConfig
from transformers import Qwen2Configfrom transformers.activations import ACT2FNfrom transformers.cache_utils import Cache, DynamicCachefrom transformers.modeling_attn_mask_utils import _prepare_4d_causal_attention_mask, _prepare_4d_causal_attention_mask_for_sdpa, _prepare_4d_attention_mask, _prepare_4d_attention_mask_for_sdpafrom transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPastfrom transformers.modeling_utils import PreTrainedModelfrom transformers.utils import ( add_start_docstrings, add_start_docstrings_to_model_forward, is_flash_attn_2_available, is_flash_attn_greater_or_equal_2_10, logging, replace_return_docstrings,)import numpy as npfrom transformers import Qwen2Configfrom transformers import Qwen2ForCausalLMimport inspectimport mathimport osimport warningsfrom typing import List, Optional, Tuple, Unionfrom tqdm import tqdm, trangeimport torchimport torch.nn.functional as Fimport torch.utils.checkpointfrom torch import nnfrom torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
from transformers.activations import ACT2FNfrom transformers.cache_utils import Cache, DynamicCachefrom transformers.modeling_attn_mask_utils import _prepare_4d_causal_attention_mask, _prepare_4d_causal_attention_mask_for_sdpa, _prepare_4d_attention_mask, _prepare_4d_attention_mask_for_sdpafrom transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPastfrom transformers.modeling_utils import PreTrainedModelfrom transformers.utils import ( add_start_docstrings, add_start_docstrings_to_model_forward, is_flash_attn_2_available, is_flash_attn_greater_or_equal_2_10, logging, replace_return_docstrings,)import numpy as npimport torchimport osimport argparseimport jsonfrom tqdm import tqdmfrom typing import cast, List, Union, Tuplefrom transformers import AutoTokenizer, AutoModel # pylint: disable=C0413from peft import LoraConfig, get_peft_model, TaskTypeimport timeimport torch.nn.functional as Fimport sysimport timeimport torch import torch.nn as nnimport torch.nn.functional as Fimport numpy as npfrom tqdm import tqdm, trangefrom collections import defaultdictfrom transformers import AutoTokenizer, AutoModel, AutoModelForCausalLM, AutoConfigimport torch.distributed as distfrom deepspeed.utils.zero_to_fp32 import get_fp32_state_dict_from_zero_checkpointimport sysimport torchimport torch.nn as nnimport torch.nn.functional as Fimport mathimport reimport logginglogging.getLogger().setLevel(logging.INFO)from .configuration_c2llm import C2LLMConfigfrom transformers.models.qwen2.modeling_qwen2 import Qwen2DecoderLayer, Qwen2Attention
class MAB_POST(nn.Module): def __init__(self, dim_Q, dim_K, dim_V, num_heads, ln=False): super(MAB_POST, self).__init__() self.dim_V = dim_V self.num_heads = num_heads self.fc_q = nn.Linear(dim_Q, dim_V) self.fc_k = nn.Linear(dim_K, dim_V) self.fc_v = nn.Linear(dim_K, dim_V) if ln: self.ln0 = nn.LayerNorm(dim_V) self.ln1 = nn.LayerNorm(dim_V) self.fc_o = nn.Linear(dim_V, dim_V) nn.init.xavier_uniform_(self.fc_q.weight) nn.init.xavier_uniform_(self.fc_k.weight) nn.init.xavier_uniform_(self.fc_v.weight) nn.init.xavier_uniform_(self.fc_o.weight)
def forward(self, Q, K, pad_mask=None):
Q_ = self.fc_q(Q) K_, V_ = self.fc_k(K), self.fc_v(K)
dim_split = self.dim_V // self.num_heads Q_ = torch.cat(Q_.split(dim_split, 2), 0) K_ = torch.cat(K_.split(dim_split, 2), 0) V_ = torch.cat(V_.split(dim_split, 2), 0)
pad_mask = pad_mask.unsqueeze(1).repeat(self.num_heads, Q.size(1), 1) score = Q_.bmm(K_.transpose(1,2))/math.sqrt(self.dim_V) score = score.masked_fill(pad_mask == 0, -1e12) A = torch.softmax(score, 2) A = A * pad_mask O = torch.cat(A.bmm(V_).split(Q.size(0), 0), 2) O = Q + O O = O if getattr(self, 'ln0', None) is None else self.ln0(O) O = O + F.relu(self.fc_o(O)) O = O if getattr(self, 'ln1', None) is None else self.ln1(O) return O
class PMA(nn.Module): def __init__(self, dim, compressed_dim, num_heads, num_seeds, ln=False, pma_mode=None): super(PMA, self).__init__() self.S = nn.Parameter(torch.Tensor(1, num_seeds, compressed_dim)) nn.init.xavier_uniform_(self.S) if pma_mode == 'post_normal': self.mab = MAB_POST(compressed_dim, dim, compressed_dim, num_heads, ln=ln) else: raise ValueError(f"Error, the pma_mode {pma_mode} is not implemented !")
def forward(self, X, pad_mask): if self.S.dtype != torch.bfloat16: X = X.float() return self.mab(self.S.repeat(X.size(0), 1, 1), X, pad_mask)
class MAB_POST_v2(nn.Module): def __init__(self, dim_Q, dim_K, dim_V, num_heads, ln=False): super(MAB_POST_v2, self).__init__() self.dim_V = dim_V self.num_heads = num_heads self.fc_q = nn.Linear(dim_Q, dim_V) self.fc_k = nn.Linear(dim_K, dim_V) self.fc_v = nn.Linear(dim_K, dim_V)
if ln: self.ln0 = nn.LayerNorm(dim_V) self.ln1 = nn.LayerNorm(dim_V) self.fc_o = nn.Linear(dim_V, dim_V) nn.init.xavier_uniform_(self.fc_q.weight) nn.init.xavier_uniform_(self.fc_k.weight) nn.init.xavier_uniform_(self.fc_v.weight) nn.init.xavier_uniform_(self.fc_o.weight)
# Q(B, num_seed, D), pad_mask (bs, seq) Post-LN def forward(self, Q, K, pad_mask=None):
Q_tmp = self.fc_q(Q) # B, num_seed, C K_, V_ = self.fc_k(K), self.fc_v(K) # B, L, C
dim_split = self.dim_V // self.num_heads Q_ = torch.cat(Q_tmp.split(dim_split, 2), 0) # (B* num_head, num_seed, C) K_ = torch.cat(K_.split(dim_split, 2), 0) # (B* num_head, L, C) V_ = torch.cat(V_.split(dim_split, 2), 0) # (B* num_head,L, C)
pad_mask = pad_mask.unsqueeze(1).repeat(self.num_heads, Q.size(1), 1) # (B*num_head, num_seed, L) score = Q_.bmm(K_.transpose(1,2))/math.sqrt(self.dim_V) # (B*num_head, num_seed, L) score = score.masked_fill(pad_mask == 0, -1e12) # B,num_seed,L A = torch.softmax(score, 2) # (B*num_head, num_seed, L) A = A * pad_mask O = torch.cat(A.bmm(V_).split(Q.size(0), 0), 2) # (B, num_seed, D) O = Q_tmp + O # O = torch.cat((Q_ + A.bmm(V_)).split(Q.size(0), 0), 2) O = O if getattr(self, 'ln0', None) is None else self.ln0(O) O = O + F.relu(self.fc_o(O)) O = O if getattr(self, 'ln1', None) is None else self.ln1(O) return O
class PMA_v2(nn.Module): def __init__(self, dim, compressed_dim, num_heads, num_seeds, ln=False): super(PMA_v2, self).__init__() self.S = nn.Parameter(torch.Tensor(1, num_seeds, dim)) nn.init.xavier_uniform_(self.S) # if pma_mode == 'post_normal': self.mab = MAB_POST_v2(dim, dim, compressed_dim, num_heads, ln=ln) # elif pma_mode == 'pre_normal': # self.mab = MAB_PRE_NORMAL(dim, dim, compressed_dim, num_heads, ln=ln) # elif pma_mode == 'pre_gptj': # self.mab = MAB_PRE_GPTJ(dim, dim, compressed_dim, num_heads, ln=ln) # else: # raise ValueError(f"Error, the pma_mode {pma_mode} is not implemented !") # X: (bs, seq, emb), pad_mask: (bs, seq) def forward(self, X, pad_mask): if self.S.dtype != torch.bfloat16: X = X.float() return self.mab(self.S.expand(X.size(0), -1, -1), X, pad_mask)
class C2LLMModel(PreTrainedModel): config_class = C2LLMConfig config: C2LLMConfig base_model_prefix = "model" supports_gradient_checkpointing = True _no_split_modules = ["Qwen2DecoderLayer"] _skip_keys_device_placement = ["past_key_values"] _supports_flash_attn = True _supports_sdpa = True _supports_flex_attn = True
_can_compile_fullgraph = True _supports_attention_backend = True _can_record_outputs = { "hidden_states": Qwen2DecoderLayer, "attentions": Qwen2Attention, }
class C2LLMForEmbedding(C2LLMModel):
config_class = C2LLMConfig model_type = "c2llm"
def __init__(self, config): super().__init__(config) qwen_cfg = Qwen2Config.from_dict(config.to_dict()) self.plm_model = AutoModelForCausalLM.from_config(qwen_cfg) self.embedding_method = config.embedding_method self.inf_seq_length = 1024 self.padding_side = config.padding_side
self.emb_dim = self.plm_model.model.embed_tokens.weight.size(1) self.keep_max_layer = self.plm_model.config.num_hidden_layers self.num_heads = config.pma_num_heads self.ln = config.pma_ln self.norm = config.pma_norm self.pma_mode = config.pma_norm_mode self.compressed_dim = config.compressed_dim self.mha_pma_disc = PMA_v2(self.emb_dim, self.compressed_dim, self.num_heads, 1, ln=self.ln) self.pool = None self.target_devices = self.get_target_devices(None) self.tokenizer = AutoTokenizer.from_pretrained(config.tokenizer_name_or_path, padding_side=config.padding_side) if config.tokenizer_name_or_path is not None else None self.config_class = C2LLMConfig
def pma_embedding(self, mha_pma, A, mask): res = mha_pma(A, mask).squeeze(1) return res
def get_hidden_states(self, **inputs): outputs = self.plm_model(inputs['input_ids'], inputs['attention_mask'], output_hidden_states=True) return outputs.hidden_states[self.keep_max_layer]
def get_sentence_embedding(self, embedding_method, hidden_states, emb_type, attention_mask):
if embedding_method == 'pma': if emb_type == 'disc': res_embedding = self.pma_embedding(self.mha_pma_disc, hidden_states, attention_mask) if self.norm: res_embedding = torch.nn.functional.normalize(res_embedding, p=2.0, dim=-1, eps=1e-12, out=None) return res_embedding else: raise NotImplementedError(f"emb type {emb_type} hasn't been implemented") else: raise NotImplementedError(f"embedding method {embedding_method} hasn't been implemented")
@staticmethod def get_target_devices(devices: Union[str, int, List[str], List[int]]) -> List[str]: """
Args: devices (Union[str, int, List[str], List[int]]): specified devices, can be `str`, `int`, list of `str`, or list of `int`.
Raises: ValueError: Devices should be a string or an integer or a list of strings or a list of integers.
Returns: List[str]: A list of target devices in format. """ if devices is None: if torch.cuda.is_available(): return [f"cuda:{i}" for i in range(torch.cuda.device_count())] elif is_torch_npu_available(): return [f"npu:{i}" for i in range(torch.npu.device_count())] elif hasattr(torch, "musa") and torch.musa.is_available(): return [f"musa:{i}" for i in range(torch.musa.device_count())] elif torch.backends.mps.is_available(): try: return [f"mps:{i}" for i in range(torch.mps.device_count())] except: return ["mps"] else: return ["cpu"] elif isinstance(devices, str): return [devices] elif isinstance(devices, int): if hasattr(torch, "musa") and torch.musa.is_available(): return [f"musa:{devices}"] else: return [f"cuda:{devices}"] elif isinstance(devices, list): if isinstance(devices[0], str): return devices elif isinstance(devices[0], int): if hasattr(torch, "musa") and torch.musa.is_available(): return [f"musa:{device}" for device in devices] else: return [f"cuda:{device}" for device in devices] else: raise ValueError("devices should be a string or an integer or a list of strings or a list of integers.") else: raise ValueError("devices should be a string or an integer or a list of strings or a list of integers.")
# adapted from https://github.com/UKPLab/sentence-transformers/blob/1802076d4eae42ff0a5629e1b04e75785d4e193b/sentence_transformers/SentenceTransformer.py#L807 def start_multi_process_pool( self, process_target_func: Any, ) -> Dict[Literal["input", "output", "processes"], Any]: """ Starts a multi-process pool to process the encoding with several independent processes via :meth:`SentenceTransformer.encode_multi_process <sentence_transformers.SentenceTransformer.encode_multi_process>`.
This method is recommended if you want to encode on multiple GPUs or CPUs. It is advised to start only one process per GPU. This method works together with encode_multi_process and stop_multi_process_pool.
Returns: Dict[str, Any]: A dictionary with the target processes, an input queue, and an output queue. """ if self.plm_model is None or self.mha_pma_disc is None: raise ValueError("Model is not initialized.")
logging.info("Start multi-process pool on devices: {}".format(", ".join(map(str, self.target_devices))))
self.to("cpu") self.share_memory() ctx = mp.get_context("spawn") input_queue = ctx.Queue() output_queue = ctx.Queue() processes = []
for device_id in tqdm(self.target_devices, desc='initial target device'): p = ctx.Process( target=process_target_func, args=(device_id, self, input_queue, output_queue), daemon=True, ) p.start() processes.append(p)
return {"input": input_queue, "output": output_queue, "processes": processes}
@staticmethod def _encode_multi_process_worker( target_device: str, model: 'C2LLMForEmbedding', input_queue: Queue, results_queue: Queue ) -> None: model = model.to(target_device) while True: try: chunk_id, sentences, kwargs = ( input_queue.get() ) embeddings = model.encode_single_device( sentences, device=target_device, **kwargs )
results_queue.put([chunk_id, embeddings]) except queue.Empty: break def encode_multi_process( self, sentences: List[str], pool: Dict[Literal["input", "output", "processes"], Any], **kwargs ):
chunk_size = math.ceil(len(sentences) / len(pool["processes"]))
input_queue = pool["input"] last_chunk_id = 0 chunk = []
for sentence in sentences: chunk.append(sentence) if len(chunk) >= chunk_size: input_queue.put( [last_chunk_id, chunk, kwargs] ) last_chunk_id += 1 chunk = []
if len(chunk) > 0: input_queue.put([last_chunk_id, chunk, kwargs]) last_chunk_id += 1
output_queue = pool["output"] results_list = sorted( [output_queue.get() for _ in trange(last_chunk_id, desc="")], key=lambda x: x[0], ) embeddings = self._concatenate_results_from_multi_process([result[1] for result in results_list]) return embeddings
def _concatenate_results_from_multi_process(self, results_list: List[Union[torch.Tensor, np.ndarray, Any]]): """concatenate and return the results from all the processes
Args: results_list (List[Union[torch.Tensor, np.ndarray, Any]]): A list of results from all the processes.
Raises: NotImplementedError: Unsupported type for results_list
Returns: Union[torch.Tensor, np.ndarray]: return the embedding vectors in a numpy array or tensor. """ if isinstance(results_list[0], torch.Tensor): # move all tensors to the same device results_list = [res.to(self.target_devices[0]) for res in results_list] return torch.cat(results_list, dim=0) elif isinstance(results_list[0], np.ndarray): return np.concatenate(results_list, axis=0) else: raise NotImplementedError("Unsupported type for results_list")
def forward(self, input_ids: torch.Tensor, attention_mask: torch.Tensor, return_dict: bool=True, **kwargs): outputs = self.plm_model(input_ids, attention_mask, output_hidden_states=True) hidden_states = outputs.hidden_states[self.keep_max_layer] embeddings = self.get_sentence_embedding(self.embedding_method, hidden_states, 'disc', attention_mask) if not return_dict: return (embeddings,) return {"sentence_embedding": embeddings}
def encode_single_device( self, sentences: Union[List[str], str], batch_size: int = 16, convert_to_numpy: bool = False, convert_to_tensor: bool = True, show_progress_bar: bool = True, max_seq_length: int = 1024, device: Optional[str] = None, **kwargs: Any ): if max_seq_length is None: max_seq_length = self.inf_seq_length
input_is_string = False if isinstance(sentences, str) or not hasattr(sentences, "__len__"): sentences = [sentences] input_is_string = True all_embeddings = [] length_sorted_idx = np.argsort([-len(s) for s in sentences]) sentences_sorted = [sentences[idx] for idx in length_sorted_idx] # 大到小重排 with torch.no_grad(): for start_index in trange(0, len(sentences), batch_size, desc="Batches", disable=not show_progress_bar): sentences_batch = sentences_sorted[start_index: start_index + batch_size] inputs = self.tokenizer(sentences_batch, padding=True, truncation=True, max_length=max_seq_length, return_tensors='pt').to(self.plm_model.device) hidden_states = self.get_hidden_states(**inputs) embeddings = self.get_sentence_embedding(self.embedding_method, hidden_states, 'disc', inputs['attention_mask']) embeddings = embeddings.detach() if convert_to_numpy: if embeddings.dtype == torch.bfloat16: embeddings = embeddings.cpu().to(torch.float32) else: embeddings = embeddings.cpu() all_embeddings.extend(embeddings) all_embeddings = [all_embeddings[idx] for idx in np.argsort(length_sorted_idx)] if convert_to_tensor: all_embeddings = torch.stack(all_embeddings) elif convert_to_numpy: all_embeddings = np.asarray([emb.numpy() for emb in all_embeddings])
if input_is_string: all_embeddings = all_embeddings[0] return all_embeddings
def encode(self, sentences, batch_size=16, convert_to_numpy=False, convert_to_tensor=True, show_progress_bar=True, max_seq_length=None, **kwargs):
if max_seq_length is None: max_seq_length = self.inf_seq_length if convert_to_tensor == convert_to_numpy: convert_to_tensor=True convert_to_numpy=False if isinstance(sentences, str) or len(self.target_devices) == 1: return self.encode_single_device( sentences, batch_size=batch_size, convert_to_numpy=convert_to_numpy, convert_to_tensor=convert_to_tensor, show_progress_bar=show_progress_bar, max_seq_length=max_seq_length, device=self.target_devices[0], **kwargs ) if self.pool is None: self.pool = self.start_multi_process_pool(C2LLMForEmbedding._encode_multi_process_worker)
all_embeddings = [] length_sorted_idx = np.argsort([-len(s) for s in sentences]) sentences_sorted = [sentences[idx] for idx in length_sorted_idx] # 大到小重排 with torch.no_grad(): for start_index in trange(0, len(sentences), batch_size, desc="Batches", disable=not show_progress_bar): sentences_batch = sentences_sorted[start_index: start_index + batch_size] embeddings_batch = self.encode_multi_process( sentences_batch, self.pool, convert_to_numpy=convert_to_numpy, convert_to_tensor=convert_to_tensor, show_progress_bar=show_progress_bar, max_seq_length=max_seq_length, **kwargs ) embeddings_batch = embeddings_batch.detach() if convert_to_numpy: if embeddings_batch.dtype == torch.bfloat16: embeddings_batch = embeddings_batch.cpu().to(torch.float32) else: embeddings_batch = embeddings_batch.cpu() all_embeddings.extend(embeddings_batch) all_embeddings = [all_embeddings[idx] for idx in np.argsort(length_sorted_idx)] if convert_to_tensor: all_embeddings = torch.stack(all_embeddings) elif convert_to_numpy: all_embeddings = np.asarray([emb.numpy() for emb in all_embeddings])
return all_embeddings
def encode_queries(self, sentences, batch_size=16, convert_to_numpy=False, convert_to_tensor=True, show_progress_bar=True, max_seq_length=None, **kwargs): if max_seq_length is None: max_seq_length = self.inf_seq_length if convert_to_tensor == convert_to_numpy: convert_to_tensor=True convert_to_numpy=False
return self.encode( sentences=sentences, batch_size=batch_size, convert_to_numpy=convert_to_numpy, convert_to_tensor=convert_to_tensor, show_progress_bar=show_progress_bar, max_seq_length=max_seq_length, **kwargs )
def encode_corpus(self, sentences, batch_size=16, convert_to_numpy=False, convert_to_tensor=True, show_progress_bar=True, max_seq_length=None, **kwargs):
if max_seq_length is None: max_seq_length = self.inf_seq_length if convert_to_tensor == convert_to_numpy: convert_to_tensor=True convert_to_numpy=False sentences = [sentence['title']+' '+sentence['text'] for sentence in sentences]
return self.encode( sentences=sentences, batch_size=batch_size, convert_to_numpy=convert_to_numpy, convert_to_tensor=convert_to_tensor, show_progress_bar=show_progress_bar, max_seq_length=max_seq_length, **kwargs )
@staticmethod def stop_multi_process_pool(pool: Dict[Literal["input", "output", "processes"], Any]) -> None: """ Stops all processes started with start_multi_process_pool.
Args: pool (Dict[str, object]): A dictionary containing the input queue, output queue, and process list.
Returns: None """ for p in pool["processes"]: p.terminate()
for p in pool["processes"]: p.join() p.close()
pool["input"].close() pool["output"].close() pool = None
def stop_self_pool(self): if self.pool is not None: self.stop_multi_process_pool(self.pool) self.pool = None try: self.model.to('cpu') torch.cuda.empty_cache() except: pass if gc is not None and callable(gc.collect): gc.collect()
def __del__(self): self.stop_self_pool()
12345678[ { "idx": 0, "name": "0", "path": "", "type": "custom_transformer.C2LLMTransformer" }]1234{ "max_seq_length": 32768, "do_lower_case": false}12345678910111213141516171819202122232425262728293031{ "additional_special_tokens": [ "<|im_start|>", "<|im_end|>", "<|object_ref_start|>", "<|object_ref_end|>", "<|box_start|>", "<|box_end|>", "<|quad_start|>", "<|quad_end|>", "<|vision_start|>", "<|vision_end|>", "<|vision_pad|>", "<|image_pad|>", "<|video_pad|>" ], "eos_token": { "content": "<|im_end|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }, "pad_token": { "content": "<|endoftext|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }}123version https://git-lfs.github.com/spec/v1oid sha256:9c5ae00e602b8860cbd784ba82a8aa14e8feecec692e7076590d014d7b7fdafasize 11421896123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208{ "add_bos_token": false, "add_prefix_space": false, "added_tokens_decoder": { "151643": { "content": "<|endoftext|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151644": { "content": "<|im_start|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151645": { "content": "<|im_end|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151646": { "content": "<|object_ref_start|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151647": { "content": "<|object_ref_end|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151648": { "content": "<|box_start|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151649": { "content": "<|box_end|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151650": { "content": "<|quad_start|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151651": { "content": "<|quad_end|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151652": { "content": "<|vision_start|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151653": { "content": "<|vision_end|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151654": { "content": "<|vision_pad|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151655": { "content": "<|image_pad|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151656": { "content": "<|video_pad|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151657": { "content": "<tool_call>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "151658": { "content": "</tool_call>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "151659": { "content": "<|fim_prefix|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "151660": { "content": "<|fim_middle|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "151661": { "content": "<|fim_suffix|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "151662": { "content": "<|fim_pad|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "151663": { "content": "<|repo_name|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "151664": { "content": "<|file_sep|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false } }, "additional_special_tokens": [ "<|im_start|>", "<|im_end|>", "<|object_ref_start|>", "<|object_ref_end|>", "<|box_start|>", "<|box_end|>", "<|quad_start|>", "<|quad_end|>", "<|vision_start|>", "<|vision_end|>", "<|vision_pad|>", "<|image_pad|>", "<|video_pad|>" ], "bos_token": null, "chat_template": "{%- if tools %}\n {{- '<|im_start|>system\\n' }}\n {%- if messages[0]['role'] == 'system' %}\n {{- messages[0]['content'] }}\n {%- else %}\n {{- 'You are Qwen, created by Alibaba Cloud. You are a helpful assistant.' }}\n {%- endif %}\n {{- \"\\n\\n# Tools\\n\\nYou may call one or more functions to assist with the user query.\\n\\nYou are provided with function signatures within <tools></tools> XML tags:\\n<tools>\" }}\n {%- for tool in tools %}\n {{- \"\\n\" }}\n {{- tool | tojson }}\n {%- endfor %}\n {{- \"\\n</tools>\\n\\nFor each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:\\n<tool_call>\\n{\\\"name\\\": <function-name>, \\\"arguments\\\": <args-json-object>}\\n</tool_call><|im_end|>\\n\" }}\n{%- else %}\n {%- if messages[0]['role'] == 'system' %}\n {{- '<|im_start|>system\\n' + messages[0]['content'] + '<|im_end|>\\n' }}\n {%- else %}\n {{- '<|im_start|>system\\nYou are Qwen, created by Alibaba Cloud. You are a helpful assistant.<|im_end|>\\n' }}\n {%- endif %}\n{%- endif %}\n{%- for message in messages %}\n {%- if (message.role == \"user\") or (message.role == \"system\" and not loop.first) or (message.role == \"assistant\" and not message.tool_calls) %}\n {{- '<|im_start|>' + message.role + '\\n' + message.content + '<|im_end|>' + '\\n' }}\n {%- elif message.role == \"assistant\" %}\n {{- '<|im_start|>' + message.role }}\n {%- if message.content %}\n {{- '\\n' + message.content }}\n {%- endif %}\n {%- for tool_call in message.tool_calls %}\n {%- if tool_call.function is defined %}\n {%- set tool_call = tool_call.function %}\n {%- endif %}\n {{- '\\n<tool_call>\\n{\"name\": \"' }}\n {{- tool_call.name }}\n {{- '\", \"arguments\": ' }}\n {{- tool_call.arguments | tojson }}\n {{- '}\\n</tool_call>' }}\n {%- endfor %}\n {{- '<|im_end|>\\n' }}\n {%- elif message.role == \"tool\" %}\n {%- if (loop.index0 == 0) or (messages[loop.index0 - 1].role != \"tool\") %}\n {{- '<|im_start|>user' }}\n {%- endif %}\n {{- '\\n<tool_response>\\n' }}\n {{- message.content }}\n {{- '\\n</tool_response>' }}\n {%- if loop.last or (messages[loop.index0 + 1].role != \"tool\") %}\n {{- '<|im_end|>\\n' }}\n {%- endif %}\n {%- endif %}\n{%- endfor %}\n{%- if add_generation_prompt %}\n {{- '<|im_start|>assistant\\n' }}\n{%- endif %}\n", "clean_up_tokenization_spaces": false, "eos_token": "<|im_end|>", "errors": "replace", "extra_special_tokens": {}, "model_max_length": 32768, "pad_token": "<|endoftext|>", "split_special_tokens": false, "tokenizer_class": "Qwen2Tokenizer", "unk_token": null}.gitattributes+1
added_tokens.jsonAdded+24
config.jsonAdded+38
config_sentence_transformers.jsonAdded+8
configuration_c2llm.pyAdded+87
custom_transformer.pyAdded+45
merges.txtAdded
model.safetensorsAdded+3
modeling_c2llm.pyAdded+641
modules.jsonAdded+8
sentence_bert_config.jsonAdded+4
special_tokens_map.jsonAdded+31
tokenizer.jsonAdded+3
tokenizer_config.jsonAdded+208
vocab.jsonAdded