CrossEncoder
CrossEncoder
有关 Cross-Encoder 的介绍,请参阅 Cross-Encoders。
- class sentence_transformers.cross_encoder.CrossEncoder(model_name_or_path: str, num_labels: int | None = None, max_length: int | None = None, activation_fn: Callable | None = None, device: str | None = None, cache_folder: str | None = None, trust_remote_code: bool = False, revision: str | None = None, local_files_only: bool = False, token: bool | str | None = None, model_kwargs: dict | None = None, tokenizer_kwargs: dict | None = None, config_kwargs: dict | None = None, model_card_data: CrossEncoderModelCardData | None = None, backend: Literal['torch', 'onnx', 'openvino'] = 'torch')[source]
CrossEncoder 接受精确的两个句子/文本作为输入,并为该句子对预测得分或标签。例如,它可以预测句子对在 0...1 范围内的相似度。
它不生成句子嵌入,也不适用于单个句子。
- 参数:
model_name_or_path (str) – 来自 Hugging Face Hub 的模型名称,可以使用 AutoModel 加载,或者本地模型的路径。我们提供了几个预训练的 CrossEncoder 模型,可用于常见任务。
num_labels (int, optional) – 分类器的标签数量。如果为 1,则 CrossEncoder 是一个回归模型,输出连续得分 0...1。如果大于 1,则输出多个得分,这些得分可以经过 softmax 得到不同类别的概率得分。默认为 None。
max_length (int, optional) – 输入序列的最大长度。较长的序列将被截断。如果为 None,则使用模型的最大长度。默认为 None。
activation_fn (Callable, optional) – 默认激活函数的可调用对象(如 nn.Sigmoid),应在 model.predict() 之上使用。如果为 None。如果 num_labels=1,则使用 nn.Sigmoid();否则使用 nn.Identity()。默认为 None。
device (str, optional) – 应用于计算的设备(如“cuda”、“cpu”、“mps”、“npu”)。如果为 None,则检查是否可以使用 GPU。
cache_folder (str, Path, optional) – 缓存文件存储的文件夹路径。
trust_remote_code (bool, optional) – 是否允许 Hub 上定义的自定义模型在其自己的建模文件中。此选项仅应设置为 True 用于您信任并已阅读其代码的存储库,因为它将在您的本地机器上执行 Hub 上的代码。默认为 False。
revision (str, optional) – 要使用的特定模型版本。它可以是 Hugging Face 上存储的模型的分支名称、标签名称或提交 ID。默认为 None。
local_files_only (bool, optional) – 是否只查看本地文件(即不尝试下载模型)。
token (bool or str, optional) – 用于下载私有模型的 Hugging Face 身份验证令牌。
model_kwargs (Dict[str, Any], optional) –
要传递给 Hugging Face Transformers 模型的其他模型配置参数。特别有用的选项是
torch_dtype: 覆盖默认的 torch.dtype 并以特定的 dtype 加载模型。不同的选项有1.
torch.float16,torch.bfloat16或torch.float: 以指定的dtype加载,如果模型存在config.torch_dtype则忽略它。如果未指定 - 模型将以torch.float(fp32) 加载。2.
"auto"- 将尝试使用模型config.json文件中的torch_dtype条目。如果未找到此条目,则接下来检查检查点中第一个浮点类型权重的dtype,并将其用作dtype。这将使用模型训练结束时保存的dtype加载模型。它不能用作模型训练方式的指示器。因为它可能以一种半精度 dtype 训练,但保存为 fp32。attn_implementation: 模型中使用的注意力实现(如果相关)。可以是 “eager”(注意力的手动实现)、“sdpa”(使用 F.scaled_dot_product_attention)或 “flash_attention_2”(使用 Dao-AILab/flash-attention)中的任何一个。默认情况下,如果可用,对于 torch>=2.1.1 将使用 SDPA。否则默认是手动 “eager” 实现。
有关更多详细信息,请参阅 AutoModelForSequenceClassification.from_pretrained 文档。
tokenizer_kwargs (Dict[str, Any], optional) – 要传递给 Hugging Face Transformers 分词器的额外分词器配置参数。有关更多详细信息,请参阅 AutoTokenizer.from_pretrained 文档。
config_kwargs (Dict[str, Any], optional) – 要传递给 Hugging Face Transformers 配置的其他模型配置参数。有关更多详细信息,请参阅 AutoConfig.from_pretrained 文档。例如,您可以通过此参数设置
classifier_dropout。model_card_data (
SentenceTransformerModelCardData, optional) – 包含模型信息的模型卡数据对象。用于在保存模型时生成模型卡。如果未设置,则会创建一个默认的模型卡数据对象。backend (str) – 用于推理的后端。可以是“torch”(默认)、“onnx”或“openvino”之一。有关不同后端的基准测试信息,请参阅 https://sbert.net.cn/docs/cross_encoder/usage/efficiency.html。
初始化内部 Module 状态,由 nn.Module 和 ScriptModule 共享。
- bfloat16() T
将所有浮点参数和缓冲区转换为
bfloat16数据类型。注意
此方法就地修改模块。
- 返回:
self
- 返回类型:
- compile(*args, **kwargs)
使用
torch.compile()编译此模块的前向。此模块的 __call__ 方法已编译,所有参数按原样传递给
torch.compile()。有关此函数参数的详细信息,请参阅
torch.compile()。
- cpu() T
将所有模型参数和缓冲区移动到 CPU。
注意
此方法就地修改模块。
- 返回:
self
- 返回类型:
- cuda(device: int | device | None = None) T
将所有模型参数和缓冲区移至 GPU。
这也会使关联的参数和缓冲区成为不同的对象。因此,如果模块在优化时将驻留在 GPU 上,则应在构建优化器之前调用此方法。
注意
此方法就地修改模块。
- 参数:
device (int, optional) – 如果指定,所有参数将被复制到该设备
- 返回:
self
- 返回类型:
- double() T
将所有浮点参数和缓冲区转换为
double数据类型。注意
此方法就地修改模块。
- 返回:
self
- 返回类型:
- eval() T
将模块设置为评估模式。
这仅对某些模块有影响。有关它们在训练/评估模式下的行为细节,请参阅特定模块的文档,例如
Dropout、BatchNorm等。这相当于
self.train(False)。有关 .eval() 和其他可能混淆的类似机制的比较,请参阅 局部禁用梯度计算。
- 返回:
self
- 返回类型:
- fit(train_dataloader: DataLoader, evaluator: SentenceEvaluator | None = None, epochs: int = 1, loss_fct=None, activation_fct=Identity(), scheduler: str = 'WarmupLinear', warmup_steps: int = 10000, optimizer_class: type[Optimizer] = <class 'torch.optim.adamw.AdamW'>, optimizer_params: dict[str, object] = {'lr': 2e-05}, weight_decay: float = 0.01, evaluation_steps: int = 0, output_path: str | None = None, save_best_model: bool = True, max_grad_norm: float = 1, use_amp: bool = False, callback: Callable[[float, int, int], None] = None, show_progress_bar: bool = True) None[source]
v4.0 之前的已弃用训练方法,建议使用
CrossEncoderTrainer。此方法在后台使用CrossEncoderTrainer,但不如 Trainer 本身灵活。这种训练方法使用 DataLoader 和 Loss 函数来训练模型。
此方法应在 v4.0 中产生与 v4.0 之前相同的结果,但如果您在升级到 v4.0 后遇到现有训练脚本的问题,则可能希望改用
CrossEncoder.old_fit。它使用 v4.0 之前的旧训练方法。- 参数:
train_dataloader – 包含 InputExample 实例的 DataLoader
evaluator – 一个评估器(sentence_transformers.cross_encoder.evaluation)在训练期间对保留的开发数据评估模型性能。它用于确定保存到磁盘的最佳模型。
epochs – 训练的轮数
loss_fct – 训练使用的损失函数。如果为 None,则使用 BinaryCrossEntropy()(如果 self.config.num_labels == 1),否则使用 CrossEntropyLoss()。默认为 None。
activation_fct – 应用在模型输出 logits 之上的激活函数。
scheduler – 学习率调度器。可用调度器:constantlr, warmupconstant, warmuplinear, warmupcosine, warmupcosinewithhardrestarts
warmup_steps – 根据调度器的不同,行为也不同。对于 WarmupLinear(默认),学习率从 0 增加到最大学习率。在这些训练步骤之后,学习率线性地减小到零。
optimizer_class – 优化器
optimizer_params – 优化器参数
weight_decay – 模型参数的权重衰减
evaluation_steps – 如果大于 0,则在每个训练步骤数后使用 evaluator 评估模型
output_path – 模型和评估文件的存储路径
save_best_model – 如果为 True,则根据 evaluator 将最佳模型存储在 output_path
max_grad_norm – 用于梯度归一化。
use_amp – 使用自动混合精度 (AMP)。仅适用于 Pytorch >= 1.6.0
callback – 在每次评估后调用的回调函数。它必须按顺序接受以下三个参数:score、epoch 和 steps
show_progress_bar – 如果为 True,则显示一个 tqdm 进度条
- float() T
将所有浮点参数和缓冲区转换为
float数据类型。注意
此方法就地修改模块。
- 返回:
self
- 返回类型:
- get_backend() Literal['torch', 'onnx', 'openvino'][source]
返回用于推理的后端,可以是“torch”、“onnx”或“openvino”之一。
- 返回:
用于推理的后端。
- 返回类型:
str
- half() T
将所有浮点参数和缓冲区转换为
half数据类型。注意
此方法就地修改模块。
- 返回:
self
- 返回类型:
- old_fit(train_dataloader: ~torch.utils.data.dataloader.DataLoader, evaluator: ~sentence_transformers.evaluation.SentenceEvaluator.SentenceEvaluator | None = None, epochs: int = 1, loss_fct=None, activation_fct=Identity(), scheduler: str = 'WarmupLinear', warmup_steps: int = 10000, optimizer_class: type[~torch.optim.optimizer.Optimizer] = <class 'torch.optim.adamw.AdamW'>, optimizer_params: dict[str, object] = {'lr': 2e-05}, weight_decay: float = 0.01, evaluation_steps: int = 0, output_path: str | None = None, save_best_model: bool = True, max_grad_norm: float = 1, use_amp: bool = False, callback: ~collections.abc.Callable[[float, int, int], None] | None = None, show_progress_bar: bool = True) None[source]
v4.0 之前的已弃用训练方法,建议使用
CrossEncoderTrainer。此方法仅应在您升级到 v4.0 后遇到现有训练脚本的问题时使用。这种训练方法使用 DataLoader 和 Loss 函数来训练模型。
- 参数:
train_dataloader – 包含 InputExample 实例的 DataLoader
evaluator – 一个评估器(sentence_transformers.cross_encoder.evaluation)在训练期间对保留的开发数据评估模型性能。它用于确定保存到磁盘的最佳模型。
epochs – 训练的轮数
loss_fct – 训练使用的损失函数。如果为 None,则使用 BinaryCrossEntropy()(如果 self.config.num_labels == 1),否则使用 CrossEntropyLoss()。默认为 None。
activation_fct – 应用在模型输出 logits 之上的激活函数。
scheduler – 学习率调度器。可用调度器:constantlr, warmupconstant, warmuplinear, warmupcosine, warmupcosinewithhardrestarts
warmup_steps – 根据调度器的不同,行为也不同。对于 WarmupLinear(默认),学习率从 0 增加到最大学习率。在这些训练步骤之后,学习率线性地减小到零。
optimizer_class – 优化器
optimizer_params – 优化器参数
weight_decay – 模型参数的权重衰减
evaluation_steps – 如果大于 0,则在每个训练步骤数后使用 evaluator 评估模型
output_path – 模型和评估文件的存储路径
save_best_model – 如果为 True,则根据 evaluator 将最佳模型存储在 output_path
max_grad_norm – 用于梯度归一化。
use_amp – 使用自动混合精度 (AMP)。仅适用于 Pytorch >= 1.6.0
callback – 在每次评估后调用的回调函数。它必须按顺序接受以下三个参数:score、epoch 和 steps
show_progress_bar – 如果为 True,则显示一个 tqdm 进度条
- predict(sentences: tuple[str, str] | list[str], batch_size: int = 32, show_progress_bar: bool | None = None, activation_fn: Callable | None = None, apply_softmax: bool | None = False, convert_to_numpy: Literal[False] = True, convert_to_tensor: Literal[False] = False, device: str | list[str | torch.device] | None = None, pool: dict[Literal['input', 'output', 'processes'], Any] | None = None, chunk_size: int | None = None) torch.Tensor[source]
- predict(sentences: list[tuple[str, str]] | list[list[str]] | tuple[str, str] | list[str], batch_size: int = 32, show_progress_bar: bool | None = None, activation_fn: Callable | None = None, apply_softmax: bool | None = False, convert_to_numpy: Literal[True] = True, convert_to_tensor: Literal[False] = False, device: str | list[str | torch.device] | None = None, pool: dict[Literal['input', 'output', 'processes'], Any] | None = None, chunk_size: int | None = None) np.ndarray
- predict(sentences: list[tuple[str, str]] | list[list[str]] | tuple[str, str] | list[str], batch_size: int = 32, show_progress_bar: bool | None = None, activation_fn: Callable | None = None, apply_softmax: bool | None = False, convert_to_numpy: bool = True, convert_to_tensor: Literal[False] = False, device: str | list[str | torch.device] | None = None, pool: dict[Literal['input', 'output', 'processes'], Any] | None = None, chunk_size: int | None = None) torch.Tensor
- predict(sentences: list[tuple[str, str]] | list[list[str]], batch_size: int = 32, show_progress_bar: bool | None = None, activation_fn: Callable | None = None, apply_softmax: bool | None = False, convert_to_numpy: Literal[False] = True, convert_to_tensor: Literal[False] = False, device: str | list[str | torch.device] | None = None, pool: dict[Literal['input', 'output', 'processes'], Any] | None = None, chunk_size: int | None = None) list[torch.Tensor]
使用 CrossEncoder 对给定的句子对进行预测。
- 参数:
sentences (Union[List[Tuple[str, str]], Tuple[str, str]]) – 句子对列表 [(Sent1, Sent2), (Sent3, Sent4)] 或单个句子对 (Sent1, Sent2)。
batch_size (int, optional) – 编码的批次大小。默认为 32。
show_progress_bar (bool, optional) – 显示进度条。默认为 None。
activation_fn (callable, optional) – 应用在 CrossEncoder 的 logits 输出上的激活函数。如果为 None,则使用
model.activation_fn,它默认为torch.nn.Sigmoid(如果 num_labels=1),否则为torch.nn.Identity。默认为 None。convert_to_numpy (bool, optional) – 将输出转换为 numpy 矩阵。默认为 True。
apply_softmax (bool, optional) – 如果设置为 True 且 model.num_labels > 1,则对 logits 输出应用 softmax,使得每个样本的每个类别的得分总和为 1。默认为 False。
convert_to_numpy – 输出是否应为 numpy 向量列表。如果为 False,则输出 PyTorch 张量列表。默认为 True。
convert_to_tensor (bool, optional) – 输出是否应为一个大的张量。覆盖 convert_to_numpy。默认为 False。
device (Union[str, List[str]], optional) – 用于计算的设备。可以是单个设备字符串(例如,“cuda:0”、“cpu”)或设备列表(例如,[“cuda:0”、“cuda:1”])。如果提供列表,将自动使用多进程。默认为 None。
pool (Dict[str, Any], optional) – 使用
start_multi_process_pool()创建的 worker 池。如果提供,将使用多进程。如果为 None 且device是一个列表,则会自动创建一个池。默认为 None。chunk_size (int, optional) – 多进程的分块大小。如果为 None,则计算出一个合理的默认值。仅当
pool不是 None 或device是列表时使用。默认为 None。
- 返回:
对传入的句子对进行预测。返回类型取决于
convert_to_numpy和convert_to_tensor参数。如果convert_to_tensor为 True,输出将是一个torch.Tensor。如果convert_to_numpy为 True,输出将是一个numpy.ndarray。否则,输出将是torch.Tensor值列表。- 返回类型:
Union[List[torch.Tensor], np.ndarray, torch.Tensor]
示例
from sentence_transformers import CrossEncoder model = CrossEncoder("cross-encoder/stsb-roberta-base") sentences = [["I love cats", "Cats are amazing"], ["I prefer dogs", "Dogs are loyal"]] model.predict(sentences) # => array([0.6912767, 0.4303499], dtype=float32) # Using multiprocessing with automatic pool scores = model.predict(sentences, device=["cuda:0", "cuda:1"]) # Using multiprocessing with manual pool pool = model.start_multi_process_pool() scores = model.predict(sentences, pool=pool) model.stop_multi_process_pool(pool)
- push_to_hub(repo_id: str, *, token: str | None = None, private: bool | None = None, safe_serialization: bool = True, commit_message: str | None = None, exist_ok: bool = False, revision: str | None = None, create_pr: bool = False, tags: list[str] | None = None) str[source]
将 CrossEncoder 模型上传到 Hugging Face Hub。
示例
from sentence_transformers import CrossEncoder model = CrossEncoder("cross-encoder/ms-marco-MiniLM-L6-v2") model.push_to_hub("username/my-crossencoder-model") # => "https://hugging-face.cn/username/my-crossencoder-model"
- 参数:
repo_id (str) – Hugging Face Hub 上的存储库名称,例如“username/repo_name”、“organization/repo_name”或仅“repo_name”。
token (str, optional) – 用于 Hugging Face Hub API 的身份验证令牌。如果未提供,将使用通过 Hugging Face CLI 存储的令牌。
private (bool, optional) – 是否创建私有存储库。如果未指定,则存储库将是公开的。
safe_serialization (bool, optional) – 是否将模型权重转换为 safetensors 格式以实现更安全的序列化。默认为 True。
commit_message (str, optional) – 推送时使用的提交消息。默认为“Add new CrossEncoder model”。
exist_ok (bool, optional) – 如果为 True,则存储库已存在时不会引发错误。如果
create_pr=True,则忽略此参数。默认为 False。revision (str, optional) – 要提交到的 git 分支。默认为 'main' 分支的 HEAD。
create_pr (bool, optional) – 是创建带有上传的 Pull Request 还是直接提交。默认为 False。
tags (list[str], optional) – 要添加到模型卡的一系列标签。默认为 None。
- 返回:
提交或拉取请求的 URL(如果 create_pr=True)
- 返回类型:
str
- rank(query: str, documents: list[str], top_k: int | None = None, return_documents: bool = False, batch_size: int = 32, show_progress_bar: bool | None = None, activation_fn: Callable | None = None, apply_softmax=False, convert_to_numpy: bool = True, convert_to_tensor: bool = False, device: str | list[str | device] | None = None, pool: dict[Literal['input', 'output', 'processes'], Any] | None = None, chunk_size: int | None = None) list[dict[Literal['corpus_id', 'score', 'text'], int | float | str]][source]
使用 CrossEncoder 对给定的查询和文档进行排名。返回一个按得分排序的列表,包含文档索引和得分。
- 参数:
query (str) – 单个查询。
documents (List[str]) – 文档列表。
top_k (Optional[int], optional) – 返回前 k 个文档。如果为 None,则返回所有文档。默认为 None。
return_documents (bool, optional) – 如果为 True,则也返回文档。如果为 False,则仅返回索引和得分。默认为 False。
batch_size (int, optional) – 编码的批次大小。默认为 32。
show_progress_bar (bool, optional) – 显示进度条。默认为 None。
activation_fn ([type], optional) – 应用在 CrossEncoder 的 logits 输出上的激活函数。如果为 None,则使用 nn.Sigmoid()(如果 num_labels=1),否则使用 nn.Identity。默认为 None。
convert_to_numpy (bool, optional) – 将输出转换为 numpy 矩阵。默认为 True。
apply_softmax (bool, optional) – 如果维度大于 2 且 apply_softmax=True,则对 logits 输出应用 softmax。默认为 False。
convert_to_tensor (bool, optional) – 将输出转换为张量。默认为 False。
device (Union[str, List[str]], optional) – 用于计算的设备。可以是单个设备字符串(例如,“cuda:0”、“cpu”)或设备列表(例如,[“cuda:0”、“cuda:1”])。如果提供列表,将自动使用多进程。默认为 None。
pool (Dict[str, Any], optional) – 使用
start_multi_process_pool()创建的 worker 池。如果提供,将使用多进程。如果为 None 且device是一个列表,则会自动创建一个池。默认为 None。chunk_size (int, optional) – 多进程的分块大小。如果为 None,则计算出一个合理的默认值。仅当
pool不是 None 或device是列表时使用。默认为 None。
- 返回:
一个按得分排序的列表,包含文档的“corpus_id”、“score”以及可选的“text”。
- 返回类型:
List[Dict[Literal[“corpus_id”, “score”, “text”], Union[int, float, str]]]
示例
from sentence_transformers import CrossEncoder model = CrossEncoder("cross-encoder/ms-marco-MiniLM-L6-v2") query = "Who wrote 'To Kill a Mockingbird'?" documents = [ "'To Kill a Mockingbird' is a novel by Harper Lee published in 1960. It was immediately successful, winning the Pulitzer Prize, and has become a classic of modern American literature.", "The novel 'Moby-Dick' was written by Herman Melville and first published in 1851. It is considered a masterpiece of American literature and deals with complex themes of obsession, revenge, and the conflict between good and evil.", "Harper Lee, an American novelist widely known for her novel 'To Kill a Mockingbird', was born in 1926 in Monroeville, Alabama. She received the Pulitzer Prize for Fiction in 1961.", "Jane Austen was an English novelist known primarily for her six major novels, which interpret, critique and comment upon the British landed gentry at the end of the 18th century.", "The 'Harry Potter' series, which consists of seven fantasy novels written by British author J.K. Rowling, is among the most popular and critically acclaimed books of the modern era.", "'The Great Gatsby', a novel written by American author F. Scott Fitzgerald, was published in 1925. The story is set in the Jazz Age and follows the life of millionaire Jay Gatsby and his pursuit of Daisy Buchanan." ] model.rank(query, documents, return_documents=True)
[{'corpus_id': 0, 'score': 10.67858, 'text': "'To Kill a Mockingbird' is a novel by Harper Lee published in 1960. It was immediately successful, winning the Pulitzer Prize, and has become a classic of modern American literature."}, {'corpus_id': 2, 'score': 9.761677, 'text': "Harper Lee, an American novelist widely known for her novel 'To Kill a Mockingbird', was born in 1926 in Monroeville, Alabama. She received the Pulitzer Prize for Fiction in 1961."}, {'corpus_id': 1, 'score': -3.3099542, 'text': "The novel 'Moby-Dick' was written by Herman Melville and first published in 1851. It is considered a masterpiece of American literature and deals with complex themes of obsession, revenge, and the conflict between good and evil."}, {'corpus_id': 5, 'score': -4.8989105, 'text': "'The Great Gatsby', a novel written by American author F. Scott Fitzgerald, was published in 1925. The story is set in the Jazz Age and follows the life of millionaire Jay Gatsby and his pursuit of Daisy Buchanan."}, {'corpus_id': 4, 'score': -5.082967, 'text': "The 'Harry Potter' series, which consists of seven fantasy novels written by British author J.K. Rowling, is among the most popular and critically acclaimed books of the modern era."}]
- save_pretrained(path: str, *, safe_serialization: bool = True, **kwargs) None[source]
将模型和分词器保存到指定的路径。
- 参数:
path (str) – 应保存模型的目录
safe_serialization (bool, optional) – 是否使用 safetensors 或传统的 PyTorch 方法进行保存。默认为 True。
**kwargs – 传递给模型和分词器底层保存方法的其他参数。
- 返回:
无
- set_config_value(key: str, value) None[source]
设置底层模型配置中的一个值。
- 参数:
key (str) – 要设置的键。
value – 要设置的值。
- start_multi_process_pool(target_devices: list[str] | None = None) dict[Literal['input', 'output', 'processes'], Any][source]
启动一个多进程池,通过
CrossEncoder.predict使用多个独立进程进行预测。如果您想在多个 GPU 或 CPU 上进行预测,建议使用此方法。建议每个 GPU 只启动一个进程。此方法与 predict 和 stop_multi_process_pool 一起使用。
- 参数:
target_devices (List[str], optional) – PyTorch 目标设备,例如 [“cuda:0”, “cuda:1”, …], [“npu:0”, “npu:1”, …] 或 [“cpu”, “cpu”, “cpu”, “cpu”]。如果 target_devices 为 None 且 CUDA/NPU 可用,则将使用所有可用的 CUDA/NPU 设备。如果 target_devices 为 None 且 CUDA/NPU 不可用,则将使用 4 个 CPU 设备。
- 返回:
一个字典,包含目标进程、输入队列和输出队列。
- 返回类型:
Dict[str, Any]
- static stop_multi_process_pool(pool: dict[Literal['input', 'output', 'processes'], Any]) None[source]
停止所有通过 start_multi_process_pool 启动的进程。
- 参数:
pool (Dict[str, object]) – 包含输入队列、输出队列和进程列表的字典。
- 返回:
无
- to(*args, **kwargs)
移动和/或转换参数和缓冲区。
可以这样调用
- to(device=None, dtype=None, non_blocking=False)
- to(dtype, non_blocking=False)
- to(tensor, non_blocking=False)
- to(memory_format=torch.channels_last)
其签名类似于
torch.Tensor.to(),但仅接受浮点或复数dtype。此外,此方法只会将浮点或复数参数和缓冲区转换为dtype(如果给定)。整数参数和缓冲区将被移动到device(如果给定),但 dtype 保持不变。当设置non_blocking时,它会尝试异步转换/移动(相对于主机),如果可能的话,例如将具有固定内存的 CPU 张量移动到 CUDA 设备。请参阅下面的示例。
注意
此方法就地修改模块。
- 参数:
device (
torch.device) – 此模块中参数和缓冲区的所需设备dtype (
torch.dtype) – 此模块中参数和缓冲区的所需浮点数或复数 dtypetensor (torch.Tensor) – 张量,其 dtype 和设备是此模块中所有参数和缓冲区的所需 dtype 和设备
memory_format (
torch.memory_format) – 此模块中 4D 参数和缓冲区的所需内存格式(仅限关键字参数)
- 返回:
self
- 返回类型:
示例
>>> # xdoctest: +IGNORE_WANT("non-deterministic") >>> linear = nn.Linear(2, 2) >>> linear.weight Parameter containing: tensor([[ 0.1913, -0.3420], [-0.5113, -0.2325]]) >>> linear.to(torch.double) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1913, -0.3420], [-0.5113, -0.2325]], dtype=torch.float64) >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA1) >>> gpu1 = torch.device("cuda:1") >>> linear.to(gpu1, dtype=torch.half, non_blocking=True) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1914, -0.3420], [-0.5112, -0.2324]], dtype=torch.float16, device='cuda:1') >>> cpu = torch.device("cpu") >>> linear.to(cpu) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1914, -0.3420], [-0.5112, -0.2324]], dtype=torch.float16) >>> linear = nn.Linear(2, 2, bias=None).to(torch.cdouble) >>> linear.weight Parameter containing: tensor([[ 0.3741+0.j, 0.2382+0.j], [ 0.5593+0.j, -0.4443+0.j]], dtype=torch.complex128) >>> linear(torch.ones(3, 2, dtype=torch.cdouble)) tensor([[0.6122+0.j, 0.1150+0.j], [0.6122+0.j, 0.1150+0.j], [0.6122+0.j, 0.1150+0.j]], dtype=torch.complex128)
- train(mode: bool = True) T
将模块设置为训练模式。
这仅对某些模块有影响。有关它们在训练/评估模式下的行为细节,请参阅特定模块的文档,例如
Dropout、BatchNorm等。- 参数:
mode (bool) – 是否设置训练模式 (
True) 或评估模式 (False)。默认值:True。- 返回:
self
- 返回类型:
- property transformers_model: PreTrainedModel | None
获取底层 transformers PreTrainedModel 实例的属性。
- 返回:
底层的 transformers 模型,如果未找到则为 None。
- 返回类型:
PreTrainedModel or None
示例
from sentence_transformers import CrossEncoder model = CrossEncoder("cross-encoder/ms-marco-MiniLM-L6-v2") # You can now access the underlying transformers model transformers_model = model.transformers_model print(type(transformers_model)) # => <class 'transformers.models.bert.modeling_bert.BertForSequenceClassification'>
CrossEncoderModelCardData
- class sentence_transformers.cross_encoder.model_card.CrossEncoderModelCardData(language: str | list[str] | None = <factory>, license: str | None = None, model_name: str | None = None, model_id: str | None = None, train_datasets: list[dict[str, str]] = <factory>, eval_datasets: list[dict[str, str]] = <factory>, task_name: str | None = None, tags: list[str] | None = <factory>, local_files_only: bool = False, generate_widget_examples: bool = True)[source]
用于存储模型卡片中数据的数据类。
- 参数:
language (Optional[Union[str, List[str]]]) – 模型语言,可以是字符串或列表,例如“en”或 [“en”, “de”, “nl”]
license (Optional[str]) – 模型的许可证,例如“apache-2.0”、“mit”或“cc-by-nc-sa-4.0”
model_name (Optional[str]) – 模型的友好名称,例如“CrossEncoder based on answerdotai/ModernBERT-base”。
model_id (Optional[str]) – 推送模型到 Hub 时的模型 ID,例如“tomaarsen/ce-mpnet-base-ms-marco”。
train_datasets (List[Dict[str, str]]) – 训练数据集的名称和/或 Hugging Face 数据集 ID 列表。例如 [{“name”: “SNLI”, “id”: “stanfordnlp/snli”}, {“name”: “MultiNLI”, “id”: “nyu-mll/multi_nli”}, {“name”: “STSB”}]
eval_datasets (List[Dict[str, str]]) – 评估数据集的名称和/或 Hugging Face 数据集 ID 列表。例如 [{“name”: “SNLI”, “id”: “stanfordnlp/snli”}, {“id”: “mteb/stsbenchmark-sts”}]
task_name (str) – 模型训练的具有可读性的任务名称,例如“semantic search and paraphrase mining”。
tags (Optional[List[str]]) – 模型的一系列标签,例如 [“sentence-transformers”, “cross-encoder”]。
local_files_only (bool) – 如果为 True,则不尝试在 Hub 上查找数据集或基础模型信息。默认为 False。
提示
安装 codecarbon 以自动跟踪碳排放使用情况并将其包含在您的模型卡片中。
示例
>>> model = CrossEncoder( ... "microsoft/mpnet-base", ... model_card_data=CrossEncoderModelCardData( ... model_id="tomaarsen/ce-mpnet-base-allnli", ... train_datasets=[{"name": "SNLI", "id": "stanfordnlp/snli"}, {"name": "MultiNLI", "id": "nyu-mll/multi_nli"}], ... eval_datasets=[{"name": "SNLI", "id": "stanfordnlp/snli"}, {"name": "MultiNLI", "id": "nyu-mll/multi_nli"}], ... license="apache-2.0", ... language="en", ... ), ... )