index
int64
0
731k
package
stringlengths
2
98
name
stringlengths
1
76
docstring
stringlengths
0
281k
code
stringlengths
4
1.07M
signature
stringlengths
2
42.8k
9,907
pygeoif.geometry
Point
A zero dimensional geometry. A point has zero length and zero area. Attributes: ---------- x, y, z : float Coordinate values Example: ------- >>> p = Point(1.0, -1.0) >>> print p POINT (1.0 -1.0) >>> p.y -1.0 >>> p.x 1.0
class Point(_Geometry): """ A zero dimensional geometry. A point has zero length and zero area. Attributes: ---------- x, y, z : float Coordinate values Example: ------- >>> p = Point(1.0, -1.0) >>> print p POINT (1.0 -1.0) >>> p.y -1.0 >>> p.x 1.0 """ _geoms: PointType def __init__(self, x: float, y: float, z: Optional[float] = None) -> None: """ Initialize a Point. Parameters ---------- 2 or 3 coordinate parameters: x, y, [z] : float Easting, northing, and elevation. """ geoms = (x, y, z) if z is not None else (x, y) object.__setattr__( self, "_geoms", geoms, ) def __repr__(self) -> str: """Return the representation.""" if self.is_empty: return f"{self.geom_type}()" return f"{self.geom_type}{self._geoms}" @property def is_empty(self) -> bool: """ Return if this geometry is empty. A Point is considered empty when it has no valid coordinates. """ return any(coord is None or math.isnan(coord) for coord in self._geoms) @property def x(self) -> float: """Return x coordinate.""" return self._geoms[0] @property def y(self) -> float: """Return y coordinate.""" return self._geoms[1] @property def z(self) -> Optional[float]: """Return z coordinate.""" if self.has_z: return self._geoms[2] # type: ignore [misc] msg = f"The {self!r} geometry does not have z values" raise DimensionError(msg) @property def coords(self) -> Union[Tuple[PointType], Tuple[()]]: """Return the geometry coordinates.""" return () if self.is_empty else (self._geoms,) @property def has_z(self) -> bool: """Return True if the geometry's coordinate sequence(s) have z values.""" return len(self._geoms) == 3 # noqa: PLR2004 @property def _wkt_coords(self) -> str: return " ".join(str(coordinate) for coordinate in self._geoms) @property def __geo_interface__(self) -> GeoInterface: """Return the geo interface.""" geo_interface = super().__geo_interface__ geo_interface["coordinates"] = cast(PointType, tuple(self._geoms)) return geo_interface @classmethod def from_coordinates(cls, coordinates: Sequence[PointType]) -> "Point": """Construct a point from coordinates.""" return cls(*coordinates[0]) @classmethod def _from_dict(cls, geo_interface: GeoInterface) -> "Point": cls._check_dict(geo_interface) return cls(*geo_interface["coordinates"]) def _get_bounds(self) -> Bounds: return self.x, self.y, self.x, self.y def _prepare_hull(self) -> Iterable[Point2D]: return ((self.x, self.y),)
(x: float, y: float, z: Optional[float] = None) -> None
9,911
pygeoif.geometry
__init__
Initialize a Point. Parameters ---------- 2 or 3 coordinate parameters: x, y, [z] : float Easting, northing, and elevation.
def __init__(self, x: float, y: float, z: Optional[float] = None) -> None: """ Initialize a Point. Parameters ---------- 2 or 3 coordinate parameters: x, y, [z] : float Easting, northing, and elevation. """ geoms = (x, y, z) if z is not None else (x, y) object.__setattr__( self, "_geoms", geoms, )
(self, x: float, y: float, z: Optional[float] = None) -> NoneType
9,912
pygeoif.geometry
__repr__
Return the representation.
def __repr__(self) -> str: """Return the representation.""" if self.is_empty: return f"{self.geom_type}()" return f"{self.geom_type}{self._geoms}"
(self) -> str
9,915
pygeoif.geometry
_get_bounds
null
def _get_bounds(self) -> Bounds: return self.x, self.y, self.x, self.y
(self) -> Tuple[float, float, float, float]
9,916
pygeoif.geometry
_prepare_hull
null
def _prepare_hull(self) -> Iterable[Point2D]: return ((self.x, self.y),)
(self) -> Iterable[Tuple[float, float]]
9,917
pygeoif.geometry
Polygon
A two-dimensional figure bounded by a linear ring. A polygon has a non-zero area. It may have one or more negative-space "holes" which are also bounded by linear rings. If any rings cross each other, the geometry is invalid and operations on it may fail. Attributes ---------- exterior : LinearRing The ring which bounds the positive space of the polygon. interiors : sequence A sequence of rings which bound all existing holes.
class Polygon(_Geometry): """ A two-dimensional figure bounded by a linear ring. A polygon has a non-zero area. It may have one or more negative-space "holes" which are also bounded by linear rings. If any rings cross each other, the geometry is invalid and operations on it may fail. Attributes ---------- exterior : LinearRing The ring which bounds the positive space of the polygon. interiors : sequence A sequence of rings which bound all existing holes. """ _geoms: Tuple[LinearRing, ...] def __init__( self, shell: LineType, holes: Optional[Sequence[LineType]] = None, ) -> None: """ Initialize the polygon. Parameters ---------- shell : sequence A sequence of (x, y [,z]) numeric coordinate pairs or triples holes : sequence A sequence of objects which satisfy the same requirements as the shell parameters above Example ------- Create a square polygon with no holes >>> coords = ((0., 0.), (0., 1.), (1., 1.), (1., 0.), (0., 0.)) >>> polygon = Polygon(coords) """ interiors = tuple(LinearRing(hole) for hole in holes) if holes else () exterior = LinearRing(shell) object.__setattr__(self, "_geoms", (exterior, interiors)) def __repr__(self) -> str: """Return the representation.""" return f"{self.geom_type}{self.coords}" @property def exterior(self) -> LinearRing: """Return the exterior Linear Ring of the polygon.""" return self._geoms[0] @property def interiors(self) -> Iterator[LinearRing]: """Interiors (Holes) of the polygon.""" yield from ( interior for interior in self._geoms[1] # type: ignore [attr-defined] if interior ) @property def is_empty(self) -> bool: """ Return if this geometry is empty. A polygon is empty when it does not have an exterior. """ return self._geoms[0].is_empty @property def coords(self) -> PolygonType: """ Return Coordinates of the Polygon. Note that this is not implemented in Shapely. """ if self._geoms[1]: return cast( PolygonType, ( self.exterior.coords, tuple(interior.coords for interior in self.interiors if interior), ), ) return cast(PolygonType, (self.exterior.coords,)) @property def has_z(self) -> Optional[bool]: """Return True if the geometry's coordinate sequence(s) have z values.""" return self._geoms[0].has_z @property def _wkt_coords(self) -> str: ec = self.exterior._wkt_coords # noqa: SLF001 ic = "".join( f",({interior._wkt_coords})" for interior in self.interiors # noqa: SLF001 ) return f"({ec}){ic}" @property def __geo_interface__(self) -> GeoInterface: """Return the geo interface.""" geo_interface = super().__geo_interface__ coords = (self.exterior.coords, *tuple(hole.coords for hole in self.interiors)) geo_interface["coordinates"] = coords return geo_interface @classmethod def from_coordinates(cls, coordinates: PolygonType) -> "Polygon": """Construct a linestring from coordinates.""" return cls(*coordinates) @classmethod def from_linear_rings(cls, shell: LinearRing, *args: LinearRing) -> "Polygon": """Construct a Polygon from linear rings.""" return cls( shell=shell.coords, holes=tuple(lr.coords for lr in args), ) @classmethod def _from_dict(cls, geo_interface: GeoInterface) -> "Polygon": cls._check_dict(geo_interface) if not geo_interface["coordinates"]: return cls(shell=(), holes=()) return cls( shell=cast(LineType, geo_interface["coordinates"][0]), holes=cast(Tuple[LineType], geo_interface["coordinates"][1:]), ) def _get_bounds(self) -> Bounds: return self.exterior._get_bounds() # noqa: SLF001 def _prepare_hull(self) -> Iterable[Point2D]: return self.exterior._prepare_hull() # noqa: SLF001
(shell: Union[Sequence[Tuple[float, float]], Sequence[Tuple[float, float, float]]], holes: Optional[Sequence[Union[Sequence[Tuple[float, float]], Sequence[Tuple[float, float, float]]]]] = None) -> None
9,921
pygeoif.geometry
__init__
Initialize the polygon. Parameters ---------- shell : sequence A sequence of (x, y [,z]) numeric coordinate pairs or triples holes : sequence A sequence of objects which satisfy the same requirements as the shell parameters above Example ------- Create a square polygon with no holes >>> coords = ((0., 0.), (0., 1.), (1., 1.), (1., 0.), (0., 0.)) >>> polygon = Polygon(coords)
def __init__( self, shell: LineType, holes: Optional[Sequence[LineType]] = None, ) -> None: """ Initialize the polygon. Parameters ---------- shell : sequence A sequence of (x, y [,z]) numeric coordinate pairs or triples holes : sequence A sequence of objects which satisfy the same requirements as the shell parameters above Example ------- Create a square polygon with no holes >>> coords = ((0., 0.), (0., 1.), (1., 1.), (1., 0.), (0., 0.)) >>> polygon = Polygon(coords) """ interiors = tuple(LinearRing(hole) for hole in holes) if holes else () exterior = LinearRing(shell) object.__setattr__(self, "_geoms", (exterior, interiors))
(self, shell: Union[Sequence[Tuple[float, float]], Sequence[Tuple[float, float, float]]], holes: Optional[Sequence[Union[Sequence[Tuple[float, float]], Sequence[Tuple[float, float, float]]]]] = None) -> NoneType
9,922
pygeoif.geometry
__repr__
Return the representation.
def __repr__(self) -> str: """Return the representation.""" return f"{self.geom_type}{self.coords}"
(self) -> str
9,925
pygeoif.geometry
_get_bounds
null
def _get_bounds(self) -> Bounds: return self.exterior._get_bounds() # noqa: SLF001
(self) -> Tuple[float, float, float, float]
9,926
pygeoif.geometry
_prepare_hull
null
def _prepare_hull(self) -> Iterable[Point2D]: return self.exterior._prepare_hull() # noqa: SLF001
(self) -> Iterable[Tuple[float, float]]
9,931
pygeoif.factories
from_wkt
Create a geometry from its WKT representation.
def from_wkt(geo_str: str) -> Optional[Union[Geometry, GeometryCollection]]: """Create a geometry from its WKT representation.""" type_map = { "POINT": _point_from_wkt_coordinates, "LINESTRING": _line_from_wkt_coordinates, "LINEARRING": _ring_from_wkt_coordinates, "POLYGON": _polygon_from_wkt_coordinates, "MULTIPOINT": _multipoint_from_wkt_coordinates, "MULTILINESTRING": _multiline_from_wkt_coordinates, "MULTIPOLYGON": _multipolygon_from_wkt_coordinates, "GEOMETRYCOLLECTION": _multigeometry_from_wkt_coordinates, } wkt = geo_str.upper().strip() wkt = " ".join(line.strip() for line in wkt.splitlines()) try: wkt = wkt_regex.match(wkt).group("wkt") # type: ignore [union-attr] geometry_type = wkt_regex.match(wkt).group("type") # type: ignore [union-attr] outerstr = outer.search(wkt) coordinates = outerstr.group(1) # type: ignore [union-attr] except AttributeError as exc: msg = f"Cannot parse {wkt}" raise WKTParserError(msg) from exc constructor = type_map[geometry_type] try: return constructor(coordinates) # type: ignore [return-value] except TypeError as exc: msg = f"Cannot parse {wkt}" raise WKTParserError(msg) from exc
(geo_str: str) -> Union[pygeoif.geometry.Point, pygeoif.geometry.LineString, pygeoif.geometry.LinearRing, pygeoif.geometry.Polygon, pygeoif.geometry.MultiPoint, pygeoif.geometry.MultiLineString, pygeoif.geometry.MultiPolygon, pygeoif.geometry.GeometryCollection, NoneType]
9,934
pygeoif.factories
mapping
Return a GeoJSON-like mapping. Parameters ---------- ob : An object which implements __geo_interface__. Returns ------- dict Example ------- >>> pt = Point(0, 0) >>> mapping(pt) {'type': 'Point', 'bbox': (0, 0, 0, 0), 'coordinates': (0, 0)}
def mapping( ob: Union[GeoType, GeoCollectionType], ) -> Union[GeoCollectionInterface, GeoInterface]: """ Return a GeoJSON-like mapping. Parameters ---------- ob : An object which implements __geo_interface__. Returns ------- dict Example ------- >>> pt = Point(0, 0) >>> mapping(pt) {'type': 'Point', 'bbox': (0, 0, 0, 0), 'coordinates': (0, 0)} """ return ob.__geo_interface__
(ob: Union[pygeoif.types.GeoType, pygeoif.types.GeoCollectionType]) -> Union[pygeoif.types.GeoCollectionInterface, pygeoif.types.GeoInterface]
9,935
pygeoif.factories
orient
Return a polygon with exteriors and interiors in the right orientation. if ccw is True than the exterior will be in counterclockwise orientation and the interiors will be in clockwise orientation, or the other way round when ccw is False.
def orient(polygon: Polygon, ccw: bool = True) -> Polygon: # noqa: FBT001, FBT002 """ Return a polygon with exteriors and interiors in the right orientation. if ccw is True than the exterior will be in counterclockwise orientation and the interiors will be in clockwise orientation, or the other way round when ccw is False. """ shell = get_oriented_ring(polygon.exterior.coords, ccw) ccw = not ccw # flip orientation for holes holes = [get_oriented_ring(ring.coords, ccw) for ring in polygon.interiors] return Polygon(shell=shell, holes=holes)
(polygon: pygeoif.geometry.Polygon, ccw: bool = True) -> pygeoif.geometry.Polygon
9,936
pygeoif.factories
shape
Return a new geometry with coordinates *copied* from the context. Changes to the original context will not be reflected in the geometry object. Parameters ---------- context : a GeoJSON-like dict, which provides a "type" member describing the type of the geometry and "coordinates" member providing a list of coordinates, or an object which implements __geo_interface__. Returns ------- Geometry object Example ------- Create a Point from GeoJSON, and then create a copy using __geo_interface__. >>> context = {'type': 'Point', 'coordinates': [0, 1]} >>> geom = shape(context) >>> geom.geom_type == 'Point' True >>> geom.wkt 'POINT (0 1)' >>> geom2 = shape(geom) >>> geom == geom2 True
def shape( context: Union[ GeoType, GeoCollectionType, GeoInterface, GeoCollectionInterface, ], ) -> Union[Geometry, GeometryCollection]: """ Return a new geometry with coordinates *copied* from the context. Changes to the original context will not be reflected in the geometry object. Parameters ---------- context : a GeoJSON-like dict, which provides a "type" member describing the type of the geometry and "coordinates" member providing a list of coordinates, or an object which implements __geo_interface__. Returns ------- Geometry object Example ------- Create a Point from GeoJSON, and then create a copy using __geo_interface__. >>> context = {'type': 'Point', 'coordinates': [0, 1]} >>> geom = shape(context) >>> geom.geom_type == 'Point' True >>> geom.wkt 'POINT (0 1)' >>> geom2 = shape(geom) >>> geom == geom2 True """ type_map = { "Point": Point, "LineString": LineString, "LinearRing": LinearRing, "Polygon": Polygon, "MultiPoint": MultiPoint, "MultiLineString": MultiLineString, "MultiPolygon": MultiPolygon, } geometry = context if isinstance(context, dict) else mapping(context) if not geometry: msg = ( # type: ignore [unreachable] "Object does not implement __geo_interface__" ) raise TypeError(msg) if constructor := type_map.get(geometry["type"]): return constructor._from_dict( # type: ignore [attr-defined, no-any-return] geometry, ) if geometry["type"] == "GeometryCollection": geometries = [shape(fi) for fi in geometry["geometries"]] return GeometryCollection(geometries) msg = f"[{geometry['type']} is not implemented" raise NotImplementedError(msg)
(context: Union[pygeoif.types.GeoType, pygeoif.types.GeoCollectionType, pygeoif.types.GeoInterface, pygeoif.types.GeoCollectionInterface]) -> Union[pygeoif.geometry.Point, pygeoif.geometry.LineString, pygeoif.geometry.LinearRing, pygeoif.geometry.Polygon, pygeoif.geometry.MultiPoint, pygeoif.geometry.MultiLineString, pygeoif.geometry.MultiPolygon, pygeoif.geometry.GeometryCollection]
9,939
rouver.util
absolute_url
Construct an absolute URL, using the request URL as base. Non-printable and non-ASCII characters in the path are encoded, but other characters, most notably slashes and percent signs are not encoded. Make sure to call urllib.parse.quote() on paths that can potentially contain such characters before passing them to absolute_url().
def absolute_url(request: Request, path: str) -> str: """ Construct an absolute URL, using the request URL as base. Non-printable and non-ASCII characters in the path are encoded, but other characters, most notably slashes and percent signs are not encoded. Make sure to call urllib.parse.quote() on paths that can potentially contain such characters before passing them to absolute_url(). """ base_url: str = request.base_url return urljoin(base_url, quote(path, safe="/:?&$@,;+=%~"))
(request: werkzeug.wrappers.request.Request, path: str) -> str
9,941
sentence_transformers.cross_encoder.CrossEncoder
CrossEncoder
A CrossEncoder takes exactly two sentences / texts as input and either predicts a score or label for this sentence pair. It can for example predict the similarity of the sentence pair on a scale of 0 ... 1. It does not yield a sentence embedding and does not work for individual sentences. :param model_name: A model name from Hugging Face Hub that can be loaded with AutoModel, or a path to a local model. We provide several pre-trained CrossEncoder models that can be used for common tasks. :param num_labels: Number of labels of the classifier. If 1, the CrossEncoder is a regression model that outputs a continuous score 0...1. If > 1, it output several scores that can be soft-maxed to get probability scores for the different classes. :param max_length: Max length for input sequences. Longer sequences will be truncated. If None, max length of the model will be used :param device: Device that should be used for the model. If None, it will use CUDA if available. :param tokenizer_args: Arguments passed to AutoTokenizer :param automodel_args: Arguments passed to AutoModelForSequenceClassification :param trust_remote_code: Whether or not to allow for custom models defined on the Hub in their own modeling files. This option should only be set to True for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. :param revision: The specific model version to use. It can be a branch name, a tag name, or a commit id, for a stored model on Hugging Face. :param default_activation_function: Callable (like nn.Sigmoid) about the default activation function that should be used on-top of model.predict(). If None. nn.Sigmoid() will be used if num_labels=1, else nn.Identity() :param classifier_dropout: The dropout ratio for the classification head.
class CrossEncoder(PushToHubMixin): """ A CrossEncoder takes exactly two sentences / texts as input and either predicts a score or label for this sentence pair. It can for example predict the similarity of the sentence pair on a scale of 0 ... 1. It does not yield a sentence embedding and does not work for individual sentences. :param model_name: A model name from Hugging Face Hub that can be loaded with AutoModel, or a path to a local model. We provide several pre-trained CrossEncoder models that can be used for common tasks. :param num_labels: Number of labels of the classifier. If 1, the CrossEncoder is a regression model that outputs a continuous score 0...1. If > 1, it output several scores that can be soft-maxed to get probability scores for the different classes. :param max_length: Max length for input sequences. Longer sequences will be truncated. If None, max length of the model will be used :param device: Device that should be used for the model. If None, it will use CUDA if available. :param tokenizer_args: Arguments passed to AutoTokenizer :param automodel_args: Arguments passed to AutoModelForSequenceClassification :param trust_remote_code: Whether or not to allow for custom models defined on the Hub in their own modeling files. This option should only be set to True for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. :param revision: The specific model version to use. It can be a branch name, a tag name, or a commit id, for a stored model on Hugging Face. :param default_activation_function: Callable (like nn.Sigmoid) about the default activation function that should be used on-top of model.predict(). If None. nn.Sigmoid() will be used if num_labels=1, else nn.Identity() :param classifier_dropout: The dropout ratio for the classification head. """ def __init__( self, model_name: str, num_labels: int = None, max_length: int = None, device: str = None, tokenizer_args: Dict = {}, automodel_args: Dict = {}, trust_remote_code: bool = False, revision: Optional[str] = None, default_activation_function=None, classifier_dropout: float = None, ): self.config = AutoConfig.from_pretrained(model_name, trust_remote_code=trust_remote_code, revision=revision) classifier_trained = True if self.config.architectures is not None: classifier_trained = any( [arch.endswith("ForSequenceClassification") for arch in self.config.architectures] ) if classifier_dropout is not None: self.config.classifier_dropout = classifier_dropout if num_labels is None and not classifier_trained: num_labels = 1 if num_labels is not None: self.config.num_labels = num_labels self.model = AutoModelForSequenceClassification.from_pretrained( model_name, config=self.config, revision=revision, trust_remote_code=trust_remote_code, **automodel_args ) self.tokenizer = AutoTokenizer.from_pretrained(model_name, revision=revision, **tokenizer_args) self.max_length = max_length if device is None: device = get_device_name() logger.info("Use pytorch device: {}".format(device)) self._target_device = torch.device(device) if default_activation_function is not None: self.default_activation_function = default_activation_function try: self.config.sbert_ce_default_activation_function = util.fullname(self.default_activation_function) except Exception as e: logger.warning( "Was not able to update config about the default_activation_function: {}".format(str(e)) ) elif ( hasattr(self.config, "sbert_ce_default_activation_function") and self.config.sbert_ce_default_activation_function is not None ): self.default_activation_function = util.import_from_string( self.config.sbert_ce_default_activation_function )() else: self.default_activation_function = nn.Sigmoid() if self.config.num_labels == 1 else nn.Identity() def smart_batching_collate(self, batch): texts = [[] for _ in range(len(batch[0].texts))] labels = [] for example in batch: for idx, text in enumerate(example.texts): texts[idx].append(text.strip()) labels.append(example.label) tokenized = self.tokenizer( *texts, padding=True, truncation="longest_first", return_tensors="pt", max_length=self.max_length ) labels = torch.tensor(labels, dtype=torch.float if self.config.num_labels == 1 else torch.long).to( self._target_device ) for name in tokenized: tokenized[name] = tokenized[name].to(self._target_device) return tokenized, labels def smart_batching_collate_text_only(self, batch): texts = [[] for _ in range(len(batch[0]))] for example in batch: for idx, text in enumerate(example): texts[idx].append(text.strip()) tokenized = self.tokenizer( *texts, padding=True, truncation="longest_first", return_tensors="pt", max_length=self.max_length ) for name in tokenized: tokenized[name] = tokenized[name].to(self._target_device) return tokenized def fit( self, train_dataloader: DataLoader, evaluator: SentenceEvaluator = None, epochs: int = 1, loss_fct=None, activation_fct=nn.Identity(), scheduler: str = "WarmupLinear", warmup_steps: int = 10000, optimizer_class: Type[Optimizer] = torch.optim.AdamW, optimizer_params: Dict[str, object] = {"lr": 2e-5}, weight_decay: float = 0.01, evaluation_steps: int = 0, output_path: str = 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, ): """ Train the model with the given training objective Each training objective is sampled in turn for one batch. We sample only as many batches from each objective as there are in the smallest one to make sure of equal training with each dataset. :param train_dataloader: DataLoader with training InputExamples :param evaluator: An evaluator (sentence_transformers.evaluation) evaluates the model performance during training on held-out dev data. It is used to determine the best model that is saved to disc. :param epochs: Number of epochs for training :param loss_fct: Which loss function to use for training. If None, will use nn.BCEWithLogitsLoss() if self.config.num_labels == 1 else nn.CrossEntropyLoss() :param activation_fct: Activation function applied on top of logits output of model. :param scheduler: Learning rate scheduler. Available schedulers: constantlr, warmupconstant, warmuplinear, warmupcosine, warmupcosinewithhardrestarts :param warmup_steps: Behavior depends on the scheduler. For WarmupLinear (default), the learning rate is increased from o up to the maximal learning rate. After these many training steps, the learning rate is decreased linearly back to zero. :param optimizer_class: Optimizer :param optimizer_params: Optimizer parameters :param weight_decay: Weight decay for model parameters :param evaluation_steps: If > 0, evaluate the model using evaluator after each number of training steps :param output_path: Storage path for the model and evaluation files :param save_best_model: If true, the best model (according to evaluator) is stored at output_path :param max_grad_norm: Used for gradient normalization. :param use_amp: Use Automatic Mixed Precision (AMP). Only for Pytorch >= 1.6.0 :param callback: Callback function that is invoked after each evaluation. It must accept the following three parameters in this order: `score`, `epoch`, `steps` :param show_progress_bar: If True, output a tqdm progress bar """ train_dataloader.collate_fn = self.smart_batching_collate if use_amp: if is_torch_npu_available(): scaler = torch.npu.amp.GradScaler() else: scaler = torch.cuda.amp.GradScaler() self.model.to(self._target_device) if output_path is not None: os.makedirs(output_path, exist_ok=True) self.best_score = -9999999 num_train_steps = int(len(train_dataloader) * epochs) # Prepare optimizers param_optimizer = list(self.model.named_parameters()) no_decay = ["bias", "LayerNorm.bias", "LayerNorm.weight"] optimizer_grouped_parameters = [ { "params": [p for n, p in param_optimizer if not any(nd in n for nd in no_decay)], "weight_decay": weight_decay, }, {"params": [p for n, p in param_optimizer if any(nd in n for nd in no_decay)], "weight_decay": 0.0}, ] optimizer = optimizer_class(optimizer_grouped_parameters, **optimizer_params) if isinstance(scheduler, str): scheduler = SentenceTransformer._get_scheduler( optimizer, scheduler=scheduler, warmup_steps=warmup_steps, t_total=num_train_steps ) if loss_fct is None: loss_fct = nn.BCEWithLogitsLoss() if self.config.num_labels == 1 else nn.CrossEntropyLoss() skip_scheduler = False for epoch in trange(epochs, desc="Epoch", disable=not show_progress_bar): training_steps = 0 self.model.zero_grad() self.model.train() for features, labels in tqdm( train_dataloader, desc="Iteration", smoothing=0.05, disable=not show_progress_bar ): if use_amp: with torch.autocast(device_type=self._target_device.type): model_predictions = self.model(**features, return_dict=True) logits = activation_fct(model_predictions.logits) if self.config.num_labels == 1: logits = logits.view(-1) loss_value = loss_fct(logits, labels) scale_before_step = scaler.get_scale() scaler.scale(loss_value).backward() scaler.unscale_(optimizer) torch.nn.utils.clip_grad_norm_(self.model.parameters(), max_grad_norm) scaler.step(optimizer) scaler.update() skip_scheduler = scaler.get_scale() != scale_before_step else: model_predictions = self.model(**features, return_dict=True) logits = activation_fct(model_predictions.logits) if self.config.num_labels == 1: logits = logits.view(-1) loss_value = loss_fct(logits, labels) loss_value.backward() torch.nn.utils.clip_grad_norm_(self.model.parameters(), max_grad_norm) optimizer.step() optimizer.zero_grad() if not skip_scheduler: scheduler.step() training_steps += 1 if evaluator is not None and evaluation_steps > 0 and training_steps % evaluation_steps == 0: self._eval_during_training( evaluator, output_path, save_best_model, epoch, training_steps, callback ) self.model.zero_grad() self.model.train() if evaluator is not None: self._eval_during_training(evaluator, output_path, save_best_model, epoch, -1, callback) def predict( self, sentences: List[List[str]], batch_size: int = 32, show_progress_bar: bool = None, num_workers: int = 0, activation_fct=None, apply_softmax=False, convert_to_numpy: bool = True, convert_to_tensor: bool = False, ): """ Performs predicts with the CrossEncoder on the given sentence pairs. :param sentences: A list of sentence pairs [[Sent1, Sent2], [Sent3, Sent4]] :param batch_size: Batch size for encoding :param show_progress_bar: Output progress bar :param num_workers: Number of workers for tokenization :param activation_fct: Activation function applied on the logits output of the CrossEncoder. If None, nn.Sigmoid() will be used if num_labels=1, else nn.Identity :param convert_to_numpy: Convert the output to a numpy matrix. :param apply_softmax: If there are more than 2 dimensions and apply_softmax=True, applies softmax on the logits output :param convert_to_tensor: Convert the output to a tensor. :return: Predictions for the passed sentence pairs """ input_was_string = False if isinstance(sentences[0], str): # Cast an individual sentence to a list with length 1 sentences = [sentences] input_was_string = True inp_dataloader = DataLoader( sentences, batch_size=batch_size, collate_fn=self.smart_batching_collate_text_only, num_workers=num_workers, shuffle=False, ) if show_progress_bar is None: show_progress_bar = ( logger.getEffectiveLevel() == logging.INFO or logger.getEffectiveLevel() == logging.DEBUG ) iterator = inp_dataloader if show_progress_bar: iterator = tqdm(inp_dataloader, desc="Batches") if activation_fct is None: activation_fct = self.default_activation_function pred_scores = [] self.model.eval() self.model.to(self._target_device) with torch.no_grad(): for features in iterator: model_predictions = self.model(**features, return_dict=True) logits = activation_fct(model_predictions.logits) if apply_softmax and len(logits[0]) > 1: logits = torch.nn.functional.softmax(logits, dim=1) pred_scores.extend(logits) if self.config.num_labels == 1: pred_scores = [score[0] for score in pred_scores] if convert_to_tensor: pred_scores = torch.stack(pred_scores) elif convert_to_numpy: pred_scores = np.asarray([score.cpu().detach().numpy() for score in pred_scores]) if input_was_string: pred_scores = pred_scores[0] return pred_scores def rank( self, query: str, documents: List[str], top_k: Optional[int] = None, return_documents: bool = False, batch_size: int = 32, show_progress_bar: bool = None, num_workers: int = 0, activation_fct=None, apply_softmax=False, convert_to_numpy: bool = True, convert_to_tensor: bool = False, ) -> List[Dict]: """ Performs ranking with the CrossEncoder on the given query and documents. Returns a sorted list with the document indices and scores. Example: :: from sentence_transformers import CrossEncoder model = CrossEncoder("cross-encoder/ms-marco-MiniLM-L-6-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."}] :param query: A single query :param documents: A list of documents :param top_k: Return the top-k documents. If None, all documents are returned. :param return_documents: If True, also returns the documents. If False, only returns the indices and scores. :param batch_size: Batch size for encoding :param show_progress_bar: Output progress bar :param num_workers: Number of workers for tokenization :param activation_fct: Activation function applied on the logits output of the CrossEncoder. If None, nn.Sigmoid() will be used if num_labels=1, else nn.Identity :param convert_to_numpy: Convert the output to a numpy matrix. :param apply_softmax: If there are more than 2 dimensions and apply_softmax=True, applies softmax on the logits output :param convert_to_tensor: Convert the output to a tensor. :return: A sorted list with the document indices and scores, and optionally also documents. """ query_doc_pairs = [[query, doc] for doc in documents] scores = self.predict( query_doc_pairs, batch_size=batch_size, show_progress_bar=show_progress_bar, num_workers=num_workers, activation_fct=activation_fct, apply_softmax=apply_softmax, convert_to_numpy=convert_to_numpy, convert_to_tensor=convert_to_tensor, ) results = [] for i in range(len(scores)): if return_documents: results.append({"corpus_id": i, "score": scores[i], "text": documents[i]}) else: results.append({"corpus_id": i, "score": scores[i]}) results = sorted(results, key=lambda x: x["score"], reverse=True) return results[:top_k] def _eval_during_training(self, evaluator, output_path, save_best_model, epoch, steps, callback): """Runs evaluation during the training""" if evaluator is not None: score = evaluator(self, output_path=output_path, epoch=epoch, steps=steps) if callback is not None: callback(score, epoch, steps) if score > self.best_score: self.best_score = score if save_best_model: self.save(output_path) def save(self, path: str, *, safe_serialization: bool = True, **kwargs) -> None: """ Saves the model and tokenizer to path; identical to `save_pretrained` """ if path is None: return logger.info("Save model to {}".format(path)) self.model.save_pretrained(path, safe_serialization=safe_serialization, **kwargs) self.tokenizer.save_pretrained(path, **kwargs) def save_pretrained(self, path: str, *, safe_serialization: bool = True, **kwargs) -> None: """ Saves the model and tokenizer to path; identical to `save` """ return self.save(path, safe_serialization=safe_serialization, **kwargs) @wraps(PushToHubMixin.push_to_hub) def push_to_hub( self, repo_id: str, *, commit_message: Optional[str] = None, private: Optional[bool] = None, safe_serialization: bool = True, tags: Optional[List[str]] = None, **kwargs, ) -> str: if isinstance(tags, str): tags = [tags] elif tags is None: tags = [] if "cross-encoder" not in tags: tags.insert(0, "cross-encoder") return super().push_to_hub( repo_id=repo_id, safe_serialization=safe_serialization, commit_message=commit_message, private=private, tags=tags, **kwargs, )
(model_name: str, num_labels: int = None, max_length: int = None, device: str = None, tokenizer_args: Dict = {}, automodel_args: Dict = {}, trust_remote_code: bool = False, revision: Optional[str] = None, default_activation_function=None, classifier_dropout: float = None)
9,942
sentence_transformers.cross_encoder.CrossEncoder
__init__
null
def __init__( self, model_name: str, num_labels: int = None, max_length: int = None, device: str = None, tokenizer_args: Dict = {}, automodel_args: Dict = {}, trust_remote_code: bool = False, revision: Optional[str] = None, default_activation_function=None, classifier_dropout: float = None, ): self.config = AutoConfig.from_pretrained(model_name, trust_remote_code=trust_remote_code, revision=revision) classifier_trained = True if self.config.architectures is not None: classifier_trained = any( [arch.endswith("ForSequenceClassification") for arch in self.config.architectures] ) if classifier_dropout is not None: self.config.classifier_dropout = classifier_dropout if num_labels is None and not classifier_trained: num_labels = 1 if num_labels is not None: self.config.num_labels = num_labels self.model = AutoModelForSequenceClassification.from_pretrained( model_name, config=self.config, revision=revision, trust_remote_code=trust_remote_code, **automodel_args ) self.tokenizer = AutoTokenizer.from_pretrained(model_name, revision=revision, **tokenizer_args) self.max_length = max_length if device is None: device = get_device_name() logger.info("Use pytorch device: {}".format(device)) self._target_device = torch.device(device) if default_activation_function is not None: self.default_activation_function = default_activation_function try: self.config.sbert_ce_default_activation_function = util.fullname(self.default_activation_function) except Exception as e: logger.warning( "Was not able to update config about the default_activation_function: {}".format(str(e)) ) elif ( hasattr(self.config, "sbert_ce_default_activation_function") and self.config.sbert_ce_default_activation_function is not None ): self.default_activation_function = util.import_from_string( self.config.sbert_ce_default_activation_function )() else: self.default_activation_function = nn.Sigmoid() if self.config.num_labels == 1 else nn.Identity()
(self, model_name: str, num_labels: Optional[int] = None, max_length: Optional[int] = None, device: Optional[str] = None, tokenizer_args: Dict = {}, automodel_args: Dict = {}, trust_remote_code: bool = False, revision: Optional[str] = None, default_activation_function=None, classifier_dropout: Optional[float] = None)
9,943
transformers.utils.hub
_create_repo
Create the repo if needed, cleans up repo_id with deprecated kwargs `repo_url` and `organization`, retrieves the token.
def _create_repo( self, repo_id: str, private: Optional[bool] = None, token: Optional[Union[bool, str]] = None, repo_url: Optional[str] = None, organization: Optional[str] = None, ) -> str: """ Create the repo if needed, cleans up repo_id with deprecated kwargs `repo_url` and `organization`, retrieves the token. """ if repo_url is not None: warnings.warn( "The `repo_url` argument is deprecated and will be removed in v5 of Transformers. Use `repo_id` " "instead." ) if repo_id is not None: raise ValueError( "`repo_id` and `repo_url` are both specified. Please set only the argument `repo_id`." ) repo_id = repo_url.replace(f"{HUGGINGFACE_CO_RESOLVE_ENDPOINT}/", "") if organization is not None: warnings.warn( "The `organization` argument is deprecated and will be removed in v5 of Transformers. Set your " "organization directly in the `repo_id` passed instead (`repo_id={organization}/{model_id}`)." ) if not repo_id.startswith(organization): if "/" in repo_id: repo_id = repo_id.split("/")[-1] repo_id = f"{organization}/{repo_id}" url = create_repo(repo_id=repo_id, token=token, private=private, exist_ok=True) return url.repo_id
(self, repo_id: str, private: Optional[bool] = None, token: Union[bool, str, NoneType] = None, repo_url: Optional[str] = None, organization: Optional[str] = None) -> str
9,944
sentence_transformers.cross_encoder.CrossEncoder
_eval_during_training
Runs evaluation during the training
def _eval_during_training(self, evaluator, output_path, save_best_model, epoch, steps, callback): """Runs evaluation during the training""" if evaluator is not None: score = evaluator(self, output_path=output_path, epoch=epoch, steps=steps) if callback is not None: callback(score, epoch, steps) if score > self.best_score: self.best_score = score if save_best_model: self.save(output_path)
(self, evaluator, output_path, save_best_model, epoch, steps, callback)
9,945
transformers.utils.hub
_get_files_timestamps
Returns the list of files with their last modification timestamp.
def _get_files_timestamps(self, working_dir: Union[str, os.PathLike]): """ Returns the list of files with their last modification timestamp. """ return {f: os.path.getmtime(os.path.join(working_dir, f)) for f in os.listdir(working_dir)}
(self, working_dir: Union[str, os.PathLike])
9,946
transformers.utils.hub
_upload_modified_files
Uploads all modified files in `working_dir` to `repo_id`, based on `files_timestamps`.
def _upload_modified_files( self, working_dir: Union[str, os.PathLike], repo_id: str, files_timestamps: Dict[str, float], commit_message: Optional[str] = None, token: Optional[Union[bool, str]] = None, create_pr: bool = False, revision: str = None, commit_description: str = None, ): """ Uploads all modified files in `working_dir` to `repo_id`, based on `files_timestamps`. """ if commit_message is None: if "Model" in self.__class__.__name__: commit_message = "Upload model" elif "Config" in self.__class__.__name__: commit_message = "Upload config" elif "Tokenizer" in self.__class__.__name__: commit_message = "Upload tokenizer" elif "FeatureExtractor" in self.__class__.__name__: commit_message = "Upload feature extractor" elif "Processor" in self.__class__.__name__: commit_message = "Upload processor" else: commit_message = f"Upload {self.__class__.__name__}" modified_files = [ f for f in os.listdir(working_dir) if f not in files_timestamps or os.path.getmtime(os.path.join(working_dir, f)) > files_timestamps[f] ] # filter for actual files + folders at the root level modified_files = [ f for f in modified_files if os.path.isfile(os.path.join(working_dir, f)) or os.path.isdir(os.path.join(working_dir, f)) ] operations = [] # upload standalone files for file in modified_files: if os.path.isdir(os.path.join(working_dir, file)): # go over individual files of folder for f in os.listdir(os.path.join(working_dir, file)): operations.append( CommitOperationAdd( path_or_fileobj=os.path.join(working_dir, file, f), path_in_repo=os.path.join(file, f) ) ) else: operations.append( CommitOperationAdd(path_or_fileobj=os.path.join(working_dir, file), path_in_repo=file) ) if revision is not None: create_branch(repo_id=repo_id, branch=revision, token=token, exist_ok=True) logger.info(f"Uploading the following files to {repo_id}: {','.join(modified_files)}") return create_commit( repo_id=repo_id, operations=operations, commit_message=commit_message, commit_description=commit_description, token=token, create_pr=create_pr, revision=revision, )
(self, working_dir: Union[str, os.PathLike], repo_id: str, files_timestamps: Dict[str, float], commit_message: Optional[str] = None, token: Union[bool, str, NoneType] = None, create_pr: bool = False, revision: Optional[str] = None, commit_description: Optional[str] = None)
9,947
sentence_transformers.cross_encoder.CrossEncoder
fit
Train the model with the given training objective Each training objective is sampled in turn for one batch. We sample only as many batches from each objective as there are in the smallest one to make sure of equal training with each dataset. :param train_dataloader: DataLoader with training InputExamples :param evaluator: An evaluator (sentence_transformers.evaluation) evaluates the model performance during training on held-out dev data. It is used to determine the best model that is saved to disc. :param epochs: Number of epochs for training :param loss_fct: Which loss function to use for training. If None, will use nn.BCEWithLogitsLoss() if self.config.num_labels == 1 else nn.CrossEntropyLoss() :param activation_fct: Activation function applied on top of logits output of model. :param scheduler: Learning rate scheduler. Available schedulers: constantlr, warmupconstant, warmuplinear, warmupcosine, warmupcosinewithhardrestarts :param warmup_steps: Behavior depends on the scheduler. For WarmupLinear (default), the learning rate is increased from o up to the maximal learning rate. After these many training steps, the learning rate is decreased linearly back to zero. :param optimizer_class: Optimizer :param optimizer_params: Optimizer parameters :param weight_decay: Weight decay for model parameters :param evaluation_steps: If > 0, evaluate the model using evaluator after each number of training steps :param output_path: Storage path for the model and evaluation files :param save_best_model: If true, the best model (according to evaluator) is stored at output_path :param max_grad_norm: Used for gradient normalization. :param use_amp: Use Automatic Mixed Precision (AMP). Only for Pytorch >= 1.6.0 :param callback: Callback function that is invoked after each evaluation. It must accept the following three parameters in this order: `score`, `epoch`, `steps` :param show_progress_bar: If True, output a tqdm progress bar
def fit( self, train_dataloader: DataLoader, evaluator: SentenceEvaluator = None, epochs: int = 1, loss_fct=None, activation_fct=nn.Identity(), scheduler: str = "WarmupLinear", warmup_steps: int = 10000, optimizer_class: Type[Optimizer] = torch.optim.AdamW, optimizer_params: Dict[str, object] = {"lr": 2e-5}, weight_decay: float = 0.01, evaluation_steps: int = 0, output_path: str = 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, ): """ Train the model with the given training objective Each training objective is sampled in turn for one batch. We sample only as many batches from each objective as there are in the smallest one to make sure of equal training with each dataset. :param train_dataloader: DataLoader with training InputExamples :param evaluator: An evaluator (sentence_transformers.evaluation) evaluates the model performance during training on held-out dev data. It is used to determine the best model that is saved to disc. :param epochs: Number of epochs for training :param loss_fct: Which loss function to use for training. If None, will use nn.BCEWithLogitsLoss() if self.config.num_labels == 1 else nn.CrossEntropyLoss() :param activation_fct: Activation function applied on top of logits output of model. :param scheduler: Learning rate scheduler. Available schedulers: constantlr, warmupconstant, warmuplinear, warmupcosine, warmupcosinewithhardrestarts :param warmup_steps: Behavior depends on the scheduler. For WarmupLinear (default), the learning rate is increased from o up to the maximal learning rate. After these many training steps, the learning rate is decreased linearly back to zero. :param optimizer_class: Optimizer :param optimizer_params: Optimizer parameters :param weight_decay: Weight decay for model parameters :param evaluation_steps: If > 0, evaluate the model using evaluator after each number of training steps :param output_path: Storage path for the model and evaluation files :param save_best_model: If true, the best model (according to evaluator) is stored at output_path :param max_grad_norm: Used for gradient normalization. :param use_amp: Use Automatic Mixed Precision (AMP). Only for Pytorch >= 1.6.0 :param callback: Callback function that is invoked after each evaluation. It must accept the following three parameters in this order: `score`, `epoch`, `steps` :param show_progress_bar: If True, output a tqdm progress bar """ train_dataloader.collate_fn = self.smart_batching_collate if use_amp: if is_torch_npu_available(): scaler = torch.npu.amp.GradScaler() else: scaler = torch.cuda.amp.GradScaler() self.model.to(self._target_device) if output_path is not None: os.makedirs(output_path, exist_ok=True) self.best_score = -9999999 num_train_steps = int(len(train_dataloader) * epochs) # Prepare optimizers param_optimizer = list(self.model.named_parameters()) no_decay = ["bias", "LayerNorm.bias", "LayerNorm.weight"] optimizer_grouped_parameters = [ { "params": [p for n, p in param_optimizer if not any(nd in n for nd in no_decay)], "weight_decay": weight_decay, }, {"params": [p for n, p in param_optimizer if any(nd in n for nd in no_decay)], "weight_decay": 0.0}, ] optimizer = optimizer_class(optimizer_grouped_parameters, **optimizer_params) if isinstance(scheduler, str): scheduler = SentenceTransformer._get_scheduler( optimizer, scheduler=scheduler, warmup_steps=warmup_steps, t_total=num_train_steps ) if loss_fct is None: loss_fct = nn.BCEWithLogitsLoss() if self.config.num_labels == 1 else nn.CrossEntropyLoss() skip_scheduler = False for epoch in trange(epochs, desc="Epoch", disable=not show_progress_bar): training_steps = 0 self.model.zero_grad() self.model.train() for features, labels in tqdm( train_dataloader, desc="Iteration", smoothing=0.05, disable=not show_progress_bar ): if use_amp: with torch.autocast(device_type=self._target_device.type): model_predictions = self.model(**features, return_dict=True) logits = activation_fct(model_predictions.logits) if self.config.num_labels == 1: logits = logits.view(-1) loss_value = loss_fct(logits, labels) scale_before_step = scaler.get_scale() scaler.scale(loss_value).backward() scaler.unscale_(optimizer) torch.nn.utils.clip_grad_norm_(self.model.parameters(), max_grad_norm) scaler.step(optimizer) scaler.update() skip_scheduler = scaler.get_scale() != scale_before_step else: model_predictions = self.model(**features, return_dict=True) logits = activation_fct(model_predictions.logits) if self.config.num_labels == 1: logits = logits.view(-1) loss_value = loss_fct(logits, labels) loss_value.backward() torch.nn.utils.clip_grad_norm_(self.model.parameters(), max_grad_norm) optimizer.step() optimizer.zero_grad() if not skip_scheduler: scheduler.step() training_steps += 1 if evaluator is not None and evaluation_steps > 0 and training_steps % evaluation_steps == 0: self._eval_during_training( evaluator, output_path, save_best_model, epoch, training_steps, callback ) self.model.zero_grad() self.model.train() if evaluator is not None: self._eval_during_training(evaluator, output_path, save_best_model, epoch, -1, callback)
(self, train_dataloader: torch.utils.data.dataloader.DataLoader, evaluator: Optional[sentence_transformers.evaluation.SentenceEvaluator.SentenceEvaluator] = 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: Optional[str] = None, save_best_model: bool = True, max_grad_norm: float = 1, use_amp: bool = False, callback: Optional[Callable[[float, int, int], NoneType]] = None, show_progress_bar: bool = True)
9,948
sentence_transformers.cross_encoder.CrossEncoder
predict
Performs predicts with the CrossEncoder on the given sentence pairs. :param sentences: A list of sentence pairs [[Sent1, Sent2], [Sent3, Sent4]] :param batch_size: Batch size for encoding :param show_progress_bar: Output progress bar :param num_workers: Number of workers for tokenization :param activation_fct: Activation function applied on the logits output of the CrossEncoder. If None, nn.Sigmoid() will be used if num_labels=1, else nn.Identity :param convert_to_numpy: Convert the output to a numpy matrix. :param apply_softmax: If there are more than 2 dimensions and apply_softmax=True, applies softmax on the logits output :param convert_to_tensor: Convert the output to a tensor. :return: Predictions for the passed sentence pairs
def predict( self, sentences: List[List[str]], batch_size: int = 32, show_progress_bar: bool = None, num_workers: int = 0, activation_fct=None, apply_softmax=False, convert_to_numpy: bool = True, convert_to_tensor: bool = False, ): """ Performs predicts with the CrossEncoder on the given sentence pairs. :param sentences: A list of sentence pairs [[Sent1, Sent2], [Sent3, Sent4]] :param batch_size: Batch size for encoding :param show_progress_bar: Output progress bar :param num_workers: Number of workers for tokenization :param activation_fct: Activation function applied on the logits output of the CrossEncoder. If None, nn.Sigmoid() will be used if num_labels=1, else nn.Identity :param convert_to_numpy: Convert the output to a numpy matrix. :param apply_softmax: If there are more than 2 dimensions and apply_softmax=True, applies softmax on the logits output :param convert_to_tensor: Convert the output to a tensor. :return: Predictions for the passed sentence pairs """ input_was_string = False if isinstance(sentences[0], str): # Cast an individual sentence to a list with length 1 sentences = [sentences] input_was_string = True inp_dataloader = DataLoader( sentences, batch_size=batch_size, collate_fn=self.smart_batching_collate_text_only, num_workers=num_workers, shuffle=False, ) if show_progress_bar is None: show_progress_bar = ( logger.getEffectiveLevel() == logging.INFO or logger.getEffectiveLevel() == logging.DEBUG ) iterator = inp_dataloader if show_progress_bar: iterator = tqdm(inp_dataloader, desc="Batches") if activation_fct is None: activation_fct = self.default_activation_function pred_scores = [] self.model.eval() self.model.to(self._target_device) with torch.no_grad(): for features in iterator: model_predictions = self.model(**features, return_dict=True) logits = activation_fct(model_predictions.logits) if apply_softmax and len(logits[0]) > 1: logits = torch.nn.functional.softmax(logits, dim=1) pred_scores.extend(logits) if self.config.num_labels == 1: pred_scores = [score[0] for score in pred_scores] if convert_to_tensor: pred_scores = torch.stack(pred_scores) elif convert_to_numpy: pred_scores = np.asarray([score.cpu().detach().numpy() for score in pred_scores]) if input_was_string: pred_scores = pred_scores[0] return pred_scores
(self, sentences: List[List[str]], batch_size: int = 32, show_progress_bar: Optional[bool] = None, num_workers: int = 0, activation_fct=None, apply_softmax=False, convert_to_numpy: bool = True, convert_to_tensor: bool = False)
9,949
transformers.utils.hub
push_to_hub
Upload the {object_files} to the 🤗 Model Hub. Parameters: repo_id (`str`): The name of the repository you want to push your {object} to. It should contain your organization name when pushing to a given organization. use_temp_dir (`bool`, *optional*): Whether or not to use a temporary directory to store the files saved before they are pushed to the Hub. Will default to `True` if there is no directory named like `repo_id`, `False` otherwise. commit_message (`str`, *optional*): Message to commit while pushing. Will default to `"Upload {object}"`. private (`bool`, *optional*): Whether or not the repository created should be private. token (`bool` or `str`, *optional*): The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated when running `huggingface-cli login` (stored in `~/.huggingface`). Will default to `True` if `repo_url` is not specified. max_shard_size (`int` or `str`, *optional*, defaults to `"5GB"`): Only applicable for models. The maximum size for a checkpoint before being sharded. Checkpoints shard will then be each of size lower than this size. If expressed as a string, needs to be digits followed by a unit (like `"5MB"`). We default it to `"5GB"` so that users can easily load models on free-tier Google Colab instances without any CPU OOM issues. create_pr (`bool`, *optional*, defaults to `False`): Whether or not to create a PR with the uploaded files or directly commit. safe_serialization (`bool`, *optional*, defaults to `True`): Whether or not to convert the model weights in safetensors format for safer serialization. revision (`str`, *optional*): Branch to push the uploaded files to. commit_description (`str`, *optional*): The description of the commit that will be created tags (`List[str]`, *optional*): List of tags to push on the Hub. Examples: ```python from transformers import {object_class} {object} = {object_class}.from_pretrained("google-bert/bert-base-cased") # Push the {object} to your namespace with the name "my-finetuned-bert". {object}.push_to_hub("my-finetuned-bert") # Push the {object} to an organization with the name "my-finetuned-bert". {object}.push_to_hub("huggingface/my-finetuned-bert") ```
def get_file_from_repo( path_or_repo: Union[str, os.PathLike], filename: str, cache_dir: Optional[Union[str, os.PathLike]] = None, force_download: bool = False, resume_download: bool = False, proxies: Optional[Dict[str, str]] = None, token: Optional[Union[bool, str]] = None, revision: Optional[str] = None, local_files_only: bool = False, subfolder: str = "", **deprecated_kwargs, ): """ Tries to locate a file in a local folder and repo, downloads and cache it if necessary. Args: path_or_repo (`str` or `os.PathLike`): This can be either: - a string, the *model id* of a model repo on huggingface.co. - a path to a *directory* potentially containing the file. filename (`str`): The name of the file to locate in `path_or_repo`. cache_dir (`str` or `os.PathLike`, *optional*): Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used. force_download (`bool`, *optional*, defaults to `False`): Whether or not to force to (re-)download the configuration files and override the cached versions if they exist. resume_download (`bool`, *optional*, defaults to `False`): Whether or not to delete incompletely received file. Attempts to resume the download if such a file exists. proxies (`Dict[str, str]`, *optional*): A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request. token (`str` or *bool*, *optional*): The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated when running `huggingface-cli login` (stored in `~/.huggingface`). revision (`str`, *optional*, defaults to `"main"`): The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any identifier allowed by git. local_files_only (`bool`, *optional*, defaults to `False`): If `True`, will only try to load the tokenizer configuration from local files. subfolder (`str`, *optional*, defaults to `""`): In case the relevant files are located inside a subfolder of the model repo on huggingface.co, you can specify the folder name here. <Tip> Passing `token=True` is required when you want to use a private model. </Tip> Returns: `Optional[str]`: Returns the resolved file (to the cache folder if downloaded from a repo) or `None` if the file does not exist. Examples: ```python # Download a tokenizer configuration from huggingface.co and cache. tokenizer_config = get_file_from_repo("google-bert/bert-base-uncased", "tokenizer_config.json") # This model does not have a tokenizer config so the result will be None. tokenizer_config = get_file_from_repo("FacebookAI/xlm-roberta-base", "tokenizer_config.json") ``` """ use_auth_token = deprecated_kwargs.pop("use_auth_token", None) if use_auth_token is not None: warnings.warn( "The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. Please use `token` instead.", FutureWarning, ) if token is not None: raise ValueError("`token` and `use_auth_token` are both specified. Please set only the argument `token`.") token = use_auth_token return cached_file( path_or_repo_id=path_or_repo, filename=filename, cache_dir=cache_dir, force_download=force_download, resume_download=resume_download, proxies=proxies, token=token, revision=revision, local_files_only=local_files_only, subfolder=subfolder, _raise_exceptions_for_gated_repo=False, _raise_exceptions_for_missing_entries=False, _raise_exceptions_for_connection_errors=False, )
(self, repo_id: str, use_temp_dir: Optional[bool] = None, commit_message: Optional[str] = None, private: Optional[bool] = None, token: Union[bool, str, NoneType] = None, max_shard_size: Union[int, str, NoneType] = '5GB', create_pr: bool = False, safe_serialization: bool = True, revision: str = None, commit_description: str = None, tags: Optional[List[str]] = None, **deprecated_kwargs) -> str
9,950
sentence_transformers.cross_encoder.CrossEncoder
rank
Performs ranking with the CrossEncoder on the given query and documents. Returns a sorted list with the document indices and scores. Example: :: from sentence_transformers import CrossEncoder model = CrossEncoder("cross-encoder/ms-marco-MiniLM-L-6-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."}] :param query: A single query :param documents: A list of documents :param top_k: Return the top-k documents. If None, all documents are returned. :param return_documents: If True, also returns the documents. If False, only returns the indices and scores. :param batch_size: Batch size for encoding :param show_progress_bar: Output progress bar :param num_workers: Number of workers for tokenization :param activation_fct: Activation function applied on the logits output of the CrossEncoder. If None, nn.Sigmoid() will be used if num_labels=1, else nn.Identity :param convert_to_numpy: Convert the output to a numpy matrix. :param apply_softmax: If there are more than 2 dimensions and apply_softmax=True, applies softmax on the logits output :param convert_to_tensor: Convert the output to a tensor. :return: A sorted list with the document indices and scores, and optionally also documents.
def rank( self, query: str, documents: List[str], top_k: Optional[int] = None, return_documents: bool = False, batch_size: int = 32, show_progress_bar: bool = None, num_workers: int = 0, activation_fct=None, apply_softmax=False, convert_to_numpy: bool = True, convert_to_tensor: bool = False, ) -> List[Dict]: """ Performs ranking with the CrossEncoder on the given query and documents. Returns a sorted list with the document indices and scores. Example: :: from sentence_transformers import CrossEncoder model = CrossEncoder("cross-encoder/ms-marco-MiniLM-L-6-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."}] :param query: A single query :param documents: A list of documents :param top_k: Return the top-k documents. If None, all documents are returned. :param return_documents: If True, also returns the documents. If False, only returns the indices and scores. :param batch_size: Batch size for encoding :param show_progress_bar: Output progress bar :param num_workers: Number of workers for tokenization :param activation_fct: Activation function applied on the logits output of the CrossEncoder. If None, nn.Sigmoid() will be used if num_labels=1, else nn.Identity :param convert_to_numpy: Convert the output to a numpy matrix. :param apply_softmax: If there are more than 2 dimensions and apply_softmax=True, applies softmax on the logits output :param convert_to_tensor: Convert the output to a tensor. :return: A sorted list with the document indices and scores, and optionally also documents. """ query_doc_pairs = [[query, doc] for doc in documents] scores = self.predict( query_doc_pairs, batch_size=batch_size, show_progress_bar=show_progress_bar, num_workers=num_workers, activation_fct=activation_fct, apply_softmax=apply_softmax, convert_to_numpy=convert_to_numpy, convert_to_tensor=convert_to_tensor, ) results = [] for i in range(len(scores)): if return_documents: results.append({"corpus_id": i, "score": scores[i], "text": documents[i]}) else: results.append({"corpus_id": i, "score": scores[i]}) results = sorted(results, key=lambda x: x["score"], reverse=True) return results[:top_k]
(self, query: str, documents: List[str], top_k: Optional[int] = None, return_documents: bool = False, batch_size: int = 32, show_progress_bar: Optional[bool] = None, num_workers: int = 0, activation_fct=None, apply_softmax=False, convert_to_numpy: bool = True, convert_to_tensor: bool = False) -> List[Dict]
9,951
sentence_transformers.cross_encoder.CrossEncoder
save
Saves the model and tokenizer to path; identical to `save_pretrained`
def save(self, path: str, *, safe_serialization: bool = True, **kwargs) -> None: """ Saves the model and tokenizer to path; identical to `save_pretrained` """ if path is None: return logger.info("Save model to {}".format(path)) self.model.save_pretrained(path, safe_serialization=safe_serialization, **kwargs) self.tokenizer.save_pretrained(path, **kwargs)
(self, path: str, *, safe_serialization: bool = True, **kwargs) -> NoneType
9,952
sentence_transformers.cross_encoder.CrossEncoder
save_pretrained
Saves the model and tokenizer to path; identical to `save`
def save_pretrained(self, path: str, *, safe_serialization: bool = True, **kwargs) -> None: """ Saves the model and tokenizer to path; identical to `save` """ return self.save(path, safe_serialization=safe_serialization, **kwargs)
(self, path: str, *, safe_serialization: bool = True, **kwargs) -> NoneType
9,953
sentence_transformers.cross_encoder.CrossEncoder
smart_batching_collate
null
def smart_batching_collate(self, batch): texts = [[] for _ in range(len(batch[0].texts))] labels = [] for example in batch: for idx, text in enumerate(example.texts): texts[idx].append(text.strip()) labels.append(example.label) tokenized = self.tokenizer( *texts, padding=True, truncation="longest_first", return_tensors="pt", max_length=self.max_length ) labels = torch.tensor(labels, dtype=torch.float if self.config.num_labels == 1 else torch.long).to( self._target_device ) for name in tokenized: tokenized[name] = tokenized[name].to(self._target_device) return tokenized, labels
(self, batch)
9,954
sentence_transformers.cross_encoder.CrossEncoder
smart_batching_collate_text_only
null
def smart_batching_collate_text_only(self, batch): texts = [[] for _ in range(len(batch[0]))] for example in batch: for idx, text in enumerate(example): texts[idx].append(text.strip()) tokenized = self.tokenizer( *texts, padding=True, truncation="longest_first", return_tensors="pt", max_length=self.max_length ) for name in tokenized: tokenized[name] = tokenized[name].to(self._target_device) return tokenized
(self, batch)
9,955
sentence_transformers.readers.InputExample
InputExample
Structure for one input example with texts, the label and a unique id
class InputExample: """ Structure for one input example with texts, the label and a unique id """ def __init__(self, guid: str = "", texts: List[str] = None, label: Union[int, float] = 0): """ Creates one InputExample with the given texts, guid and label :param guid id for the example :param texts the texts for the example. :param label the label for the example """ self.guid = guid self.texts = texts self.label = label def __str__(self): return "<InputExample> label: {}, texts: {}".format(str(self.label), "; ".join(self.texts))
(guid: str = '', texts: List[str] = None, label: Union[int, float] = 0)
9,956
sentence_transformers.readers.InputExample
__init__
Creates one InputExample with the given texts, guid and label :param guid id for the example :param texts the texts for the example. :param label the label for the example
def __init__(self, guid: str = "", texts: List[str] = None, label: Union[int, float] = 0): """ Creates one InputExample with the given texts, guid and label :param guid id for the example :param texts the texts for the example. :param label the label for the example """ self.guid = guid self.texts = texts self.label = label
(self, guid: str = '', texts: Optional[List[str]] = None, label: Union[int, float] = 0)
9,957
sentence_transformers.readers.InputExample
__str__
null
def __str__(self): return "<InputExample> label: {}, texts: {}".format(str(self.label), "; ".join(self.texts))
(self)
9,958
sentence_transformers.LoggingHandler
LoggingHandler
null
class LoggingHandler(logging.Handler): def __init__(self, level=logging.NOTSET): super().__init__(level) def emit(self, record): try: msg = self.format(record) tqdm.tqdm.write(msg) self.flush() except (KeyboardInterrupt, SystemExit): raise except Exception: self.handleError(record)
(level=0)
9,959
sentence_transformers.LoggingHandler
__init__
null
def __init__(self, level=logging.NOTSET): super().__init__(level)
(self, level=0)
9,966
sentence_transformers.LoggingHandler
emit
null
def emit(self, record): try: msg = self.format(record) tqdm.tqdm.write(msg) self.flush() except (KeyboardInterrupt, SystemExit): raise except Exception: self.handleError(record)
(self, record)
9,978
sentence_transformers.datasets.ParallelSentencesDataset
ParallelSentencesDataset
This dataset reader can be used to read-in parallel sentences, i.e., it reads in a file with tab-seperated sentences with the same sentence in different languages. For example, the file can look like this (EN DE ES): hello world hallo welt hola mundo second sentence zweiter satz segunda oración The sentence in the first column will be mapped to a sentence embedding using the given the embedder. For example, embedder is a mono-lingual sentence embedding method for English. The sentences in the other languages will also be mapped to this English sentence embedding. When getting a sample from the dataset, we get one sentence with the according sentence embedding for this sentence. teacher_model can be any class that implement an encode function. The encode function gets a list of sentences and returns a list of sentence embeddings
class ParallelSentencesDataset(Dataset): """ This dataset reader can be used to read-in parallel sentences, i.e., it reads in a file with tab-seperated sentences with the same sentence in different languages. For example, the file can look like this (EN\tDE\tES): hello world hallo welt hola mundo second sentence zweiter satz segunda oración The sentence in the first column will be mapped to a sentence embedding using the given the embedder. For example, embedder is a mono-lingual sentence embedding method for English. The sentences in the other languages will also be mapped to this English sentence embedding. When getting a sample from the dataset, we get one sentence with the according sentence embedding for this sentence. teacher_model can be any class that implement an encode function. The encode function gets a list of sentences and returns a list of sentence embeddings """ def __init__( self, student_model: SentenceTransformer, teacher_model: SentenceTransformer, batch_size: int = 8, use_embedding_cache: bool = True, ): """ Parallel sentences dataset reader to train student model given a teacher model :param student_model: Student sentence embedding model that should be trained :param teacher_model: Teacher model, that provides the sentence embeddings for the first column in the dataset file """ self.student_model = student_model self.teacher_model = teacher_model self.datasets = [] self.datasets_iterator = [] self.datasets_tokenized = [] self.dataset_indices = [] self.copy_dataset_indices = [] self.cache = [] self.batch_size = batch_size self.use_embedding_cache = use_embedding_cache self.embedding_cache = {} self.num_sentences = 0 def load_data(self, filepath: str, weight: int = 100, max_sentences: int = None, max_sentence_length: int = 128): """ Reads in a tab-seperated .txt/.csv/.tsv or .gz file. The different columns contain the different translations of the sentence in the first column :param filepath: Filepath to the file :param weight: If more than one dataset is loaded with load_data: With which frequency should data be sampled from this dataset? :param max_sentences: Max number of lines to be read from filepath :param max_sentence_length: Skip the example if one of the sentences is has more characters than max_sentence_length :param batch_size: Size for encoding parallel sentences :return: """ logger.info("Load " + filepath) parallel_sentences = [] with gzip.open(filepath, "rt", encoding="utf8") if filepath.endswith(".gz") else open( filepath, encoding="utf8" ) as fIn: count = 0 for line in fIn: sentences = line.strip().split("\t") if ( max_sentence_length is not None and max_sentence_length > 0 and max([len(sent) for sent in sentences]) > max_sentence_length ): continue parallel_sentences.append(sentences) count += 1 if max_sentences is not None and max_sentences > 0 and count >= max_sentences: break self.add_dataset( parallel_sentences, weight=weight, max_sentences=max_sentences, max_sentence_length=max_sentence_length ) def add_dataset( self, parallel_sentences: List[List[str]], weight: int = 100, max_sentences: int = None, max_sentence_length: int = 128, ): sentences_map = {} for sentences in parallel_sentences: if ( max_sentence_length is not None and max_sentence_length > 0 and max([len(sent) for sent in sentences]) > max_sentence_length ): continue source_sentence = sentences[0] if source_sentence not in sentences_map: sentences_map[source_sentence] = set() for sent in sentences: sentences_map[source_sentence].add(sent) if max_sentences is not None and max_sentences > 0 and len(sentences_map) >= max_sentences: break if len(sentences_map) == 0: return self.num_sentences += sum([len(sentences_map[sent]) for sent in sentences_map]) dataset_id = len(self.datasets) self.datasets.append(list(sentences_map.items())) self.datasets_iterator.append(0) self.dataset_indices.extend([dataset_id] * weight) def generate_data(self): source_sentences_list = [] target_sentences_list = [] for data_idx in self.dataset_indices: src_sentence, trg_sentences = self.next_entry(data_idx) source_sentences_list.append(src_sentence) target_sentences_list.append(trg_sentences) # Generate embeddings src_embeddings = self.get_embeddings(source_sentences_list) for src_embedding, trg_sentences in zip(src_embeddings, target_sentences_list): for trg_sentence in trg_sentences: self.cache.append(InputExample(texts=[trg_sentence], label=src_embedding)) random.shuffle(self.cache) def next_entry(self, data_idx): source, target_sentences = self.datasets[data_idx][self.datasets_iterator[data_idx]] self.datasets_iterator[data_idx] += 1 if self.datasets_iterator[data_idx] >= len(self.datasets[data_idx]): # Restart iterator self.datasets_iterator[data_idx] = 0 random.shuffle(self.datasets[data_idx]) return source, target_sentences def get_embeddings(self, sentences): if not self.use_embedding_cache: return self.teacher_model.encode( sentences, batch_size=self.batch_size, show_progress_bar=False, convert_to_numpy=True ) # Use caching new_sentences = [] for sent in sentences: if sent not in self.embedding_cache: new_sentences.append(sent) if len(new_sentences) > 0: new_embeddings = self.teacher_model.encode( new_sentences, batch_size=self.batch_size, show_progress_bar=False, convert_to_numpy=True ) for sent, embedding in zip(new_sentences, new_embeddings): self.embedding_cache[sent] = embedding return [self.embedding_cache[sent] for sent in sentences] def __len__(self): return self.num_sentences def __getitem__(self, idx): if len(self.cache) == 0: self.generate_data() return self.cache.pop()
(student_model: <module 'sentence_transformers.SentenceTransformer' from '/usr/local/lib/python3.10/site-packages/sentence_transformers/SentenceTransformer.py'>, teacher_model: <module 'sentence_transformers.SentenceTransformer' from '/usr/local/lib/python3.10/site-packages/sentence_transformers/SentenceTransformer.py'>, batch_size: int = 8, use_embedding_cache: bool = True)
9,979
torch.utils.data.dataset
__add__
null
def __add__(self, other: "Dataset[T_co]") -> "ConcatDataset[T_co]": return ConcatDataset([self, other])
(self, other: torch.utils.data.dataset.Dataset[+T_co]) -> torch.utils.data.dataset.ConcatDataset[+T_co]
9,980
sentence_transformers.datasets.ParallelSentencesDataset
__getitem__
null
def __getitem__(self, idx): if len(self.cache) == 0: self.generate_data() return self.cache.pop()
(self, idx)
9,981
sentence_transformers.datasets.ParallelSentencesDataset
__init__
Parallel sentences dataset reader to train student model given a teacher model :param student_model: Student sentence embedding model that should be trained :param teacher_model: Teacher model, that provides the sentence embeddings for the first column in the dataset file
def __init__( self, student_model: SentenceTransformer, teacher_model: SentenceTransformer, batch_size: int = 8, use_embedding_cache: bool = True, ): """ Parallel sentences dataset reader to train student model given a teacher model :param student_model: Student sentence embedding model that should be trained :param teacher_model: Teacher model, that provides the sentence embeddings for the first column in the dataset file """ self.student_model = student_model self.teacher_model = teacher_model self.datasets = [] self.datasets_iterator = [] self.datasets_tokenized = [] self.dataset_indices = [] self.copy_dataset_indices = [] self.cache = [] self.batch_size = batch_size self.use_embedding_cache = use_embedding_cache self.embedding_cache = {} self.num_sentences = 0
(self, student_model: <module 'sentence_transformers.SentenceTransformer' from '/usr/local/lib/python3.10/site-packages/sentence_transformers/SentenceTransformer.py'>, teacher_model: <module 'sentence_transformers.SentenceTransformer' from '/usr/local/lib/python3.10/site-packages/sentence_transformers/SentenceTransformer.py'>, batch_size: int = 8, use_embedding_cache: bool = True)
9,982
sentence_transformers.datasets.ParallelSentencesDataset
__len__
null
def __len__(self): return self.num_sentences
(self)
9,983
sentence_transformers.datasets.ParallelSentencesDataset
add_dataset
null
def add_dataset( self, parallel_sentences: List[List[str]], weight: int = 100, max_sentences: int = None, max_sentence_length: int = 128, ): sentences_map = {} for sentences in parallel_sentences: if ( max_sentence_length is not None and max_sentence_length > 0 and max([len(sent) for sent in sentences]) > max_sentence_length ): continue source_sentence = sentences[0] if source_sentence not in sentences_map: sentences_map[source_sentence] = set() for sent in sentences: sentences_map[source_sentence].add(sent) if max_sentences is not None and max_sentences > 0 and len(sentences_map) >= max_sentences: break if len(sentences_map) == 0: return self.num_sentences += sum([len(sentences_map[sent]) for sent in sentences_map]) dataset_id = len(self.datasets) self.datasets.append(list(sentences_map.items())) self.datasets_iterator.append(0) self.dataset_indices.extend([dataset_id] * weight)
(self, parallel_sentences: List[List[str]], weight: int = 100, max_sentences: Optional[int] = None, max_sentence_length: int = 128)
9,984
sentence_transformers.datasets.ParallelSentencesDataset
generate_data
null
def generate_data(self): source_sentences_list = [] target_sentences_list = [] for data_idx in self.dataset_indices: src_sentence, trg_sentences = self.next_entry(data_idx) source_sentences_list.append(src_sentence) target_sentences_list.append(trg_sentences) # Generate embeddings src_embeddings = self.get_embeddings(source_sentences_list) for src_embedding, trg_sentences in zip(src_embeddings, target_sentences_list): for trg_sentence in trg_sentences: self.cache.append(InputExample(texts=[trg_sentence], label=src_embedding)) random.shuffle(self.cache)
(self)
9,985
sentence_transformers.datasets.ParallelSentencesDataset
get_embeddings
null
def get_embeddings(self, sentences): if not self.use_embedding_cache: return self.teacher_model.encode( sentences, batch_size=self.batch_size, show_progress_bar=False, convert_to_numpy=True ) # Use caching new_sentences = [] for sent in sentences: if sent not in self.embedding_cache: new_sentences.append(sent) if len(new_sentences) > 0: new_embeddings = self.teacher_model.encode( new_sentences, batch_size=self.batch_size, show_progress_bar=False, convert_to_numpy=True ) for sent, embedding in zip(new_sentences, new_embeddings): self.embedding_cache[sent] = embedding return [self.embedding_cache[sent] for sent in sentences]
(self, sentences)
9,986
sentence_transformers.datasets.ParallelSentencesDataset
load_data
Reads in a tab-seperated .txt/.csv/.tsv or .gz file. The different columns contain the different translations of the sentence in the first column :param filepath: Filepath to the file :param weight: If more than one dataset is loaded with load_data: With which frequency should data be sampled from this dataset? :param max_sentences: Max number of lines to be read from filepath :param max_sentence_length: Skip the example if one of the sentences is has more characters than max_sentence_length :param batch_size: Size for encoding parallel sentences :return:
def load_data(self, filepath: str, weight: int = 100, max_sentences: int = None, max_sentence_length: int = 128): """ Reads in a tab-seperated .txt/.csv/.tsv or .gz file. The different columns contain the different translations of the sentence in the first column :param filepath: Filepath to the file :param weight: If more than one dataset is loaded with load_data: With which frequency should data be sampled from this dataset? :param max_sentences: Max number of lines to be read from filepath :param max_sentence_length: Skip the example if one of the sentences is has more characters than max_sentence_length :param batch_size: Size for encoding parallel sentences :return: """ logger.info("Load " + filepath) parallel_sentences = [] with gzip.open(filepath, "rt", encoding="utf8") if filepath.endswith(".gz") else open( filepath, encoding="utf8" ) as fIn: count = 0 for line in fIn: sentences = line.strip().split("\t") if ( max_sentence_length is not None and max_sentence_length > 0 and max([len(sent) for sent in sentences]) > max_sentence_length ): continue parallel_sentences.append(sentences) count += 1 if max_sentences is not None and max_sentences > 0 and count >= max_sentences: break self.add_dataset( parallel_sentences, weight=weight, max_sentences=max_sentences, max_sentence_length=max_sentence_length )
(self, filepath: str, weight: int = 100, max_sentences: Optional[int] = None, max_sentence_length: int = 128)
9,987
sentence_transformers.datasets.ParallelSentencesDataset
next_entry
null
def next_entry(self, data_idx): source, target_sentences = self.datasets[data_idx][self.datasets_iterator[data_idx]] self.datasets_iterator[data_idx] += 1 if self.datasets_iterator[data_idx] >= len(self.datasets[data_idx]): # Restart iterator self.datasets_iterator[data_idx] = 0 random.shuffle(self.datasets[data_idx]) return source, target_sentences
(self, data_idx)
9,988
sentence_transformers.SentenceTransformer
SentenceTransformer
Loads or creates a SentenceTransformer model that can be used to map sentences / text to embeddings. :param model_name_or_path: If it is a filepath on disc, it loads the model from that path. If it is not a path, it first tries to download a pre-trained SentenceTransformer model. If that fails, tries to construct a model from the Hugging Face Hub with that name. :param modules: A list of torch Modules that should be called sequentially, can be used to create custom SentenceTransformer models from scratch. :param device: Device (like "cuda", "cpu", "mps", "npu") that should be used for computation. If None, checks if a GPU can be used. :param prompts: A dictionary with prompts for the model. The key is the prompt name, the value is the prompt text. The prompt text will be prepended before any text to encode. For example: `{"query": "query: ", "passage": "passage: "}` or `{"clustering": "Identify the main category based on the titles in "}`. :param default_prompt_name: The name of the prompt that should be used by default. If not set, no prompt will be applied. :param cache_folder: Path to store models. Can also be set by the SENTENCE_TRANSFORMERS_HOME environment variable. :param trust_remote_code: Whether or not to allow for custom models defined on the Hub in their own modeling files. This option should only be set to True for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. :param revision: The specific model version to use. It can be a branch name, a tag name, or a commit id, for a stored model on Hugging Face. :param token: Hugging Face authentication token to download private models. :param truncate_dim: The dimension to truncate sentence embeddings to. `None` does no truncation. Truncation is only applicable during inference when `.encode` is called.
class SentenceTransformer(nn.Sequential): """ Loads or creates a SentenceTransformer model that can be used to map sentences / text to embeddings. :param model_name_or_path: If it is a filepath on disc, it loads the model from that path. If it is not a path, it first tries to download a pre-trained SentenceTransformer model. If that fails, tries to construct a model from the Hugging Face Hub with that name. :param modules: A list of torch Modules that should be called sequentially, can be used to create custom SentenceTransformer models from scratch. :param device: Device (like "cuda", "cpu", "mps", "npu") that should be used for computation. If None, checks if a GPU can be used. :param prompts: A dictionary with prompts for the model. The key is the prompt name, the value is the prompt text. The prompt text will be prepended before any text to encode. For example: `{"query": "query: ", "passage": "passage: "}` or `{"clustering": "Identify the main category based on the titles in "}`. :param default_prompt_name: The name of the prompt that should be used by default. If not set, no prompt will be applied. :param cache_folder: Path to store models. Can also be set by the SENTENCE_TRANSFORMERS_HOME environment variable. :param trust_remote_code: Whether or not to allow for custom models defined on the Hub in their own modeling files. This option should only be set to True for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. :param revision: The specific model version to use. It can be a branch name, a tag name, or a commit id, for a stored model on Hugging Face. :param token: Hugging Face authentication token to download private models. :param truncate_dim: The dimension to truncate sentence embeddings to. `None` does no truncation. Truncation is only applicable during inference when `.encode` is called. """ def __init__( self, model_name_or_path: Optional[str] = None, modules: Optional[Iterable[nn.Module]] = None, device: Optional[str] = None, prompts: Optional[Dict[str, str]] = None, default_prompt_name: Optional[str] = None, cache_folder: Optional[str] = None, trust_remote_code: bool = False, revision: Optional[str] = None, token: Optional[Union[bool, str]] = None, use_auth_token: Optional[Union[bool, str]] = None, truncate_dim: Optional[int] = None, ): # Note: self._load_sbert_model can also update `self.prompts` and `self.default_prompt_name` self.prompts = prompts or {} self.default_prompt_name = default_prompt_name self.truncate_dim = truncate_dim self._model_card_vars = {} self._model_card_text = None self._model_config = {} if use_auth_token is not None: warnings.warn( "The `use_auth_token` argument is deprecated and will be removed in v3 of SentenceTransformers.", FutureWarning, ) if token is not None: raise ValueError( "`token` and `use_auth_token` are both specified. Please set only the argument `token`." ) token = use_auth_token if cache_folder is None: cache_folder = os.getenv("SENTENCE_TRANSFORMERS_HOME") if model_name_or_path is not None and model_name_or_path != "": logger.info("Load pretrained SentenceTransformer: {}".format(model_name_or_path)) # Old models that don't belong to any organization basic_transformer_models = [ "albert-base-v1", "albert-base-v2", "albert-large-v1", "albert-large-v2", "albert-xlarge-v1", "albert-xlarge-v2", "albert-xxlarge-v1", "albert-xxlarge-v2", "bert-base-cased-finetuned-mrpc", "bert-base-cased", "bert-base-chinese", "bert-base-german-cased", "bert-base-german-dbmdz-cased", "bert-base-german-dbmdz-uncased", "bert-base-multilingual-cased", "bert-base-multilingual-uncased", "bert-base-uncased", "bert-large-cased-whole-word-masking-finetuned-squad", "bert-large-cased-whole-word-masking", "bert-large-cased", "bert-large-uncased-whole-word-masking-finetuned-squad", "bert-large-uncased-whole-word-masking", "bert-large-uncased", "camembert-base", "ctrl", "distilbert-base-cased-distilled-squad", "distilbert-base-cased", "distilbert-base-german-cased", "distilbert-base-multilingual-cased", "distilbert-base-uncased-distilled-squad", "distilbert-base-uncased-finetuned-sst-2-english", "distilbert-base-uncased", "distilgpt2", "distilroberta-base", "gpt2-large", "gpt2-medium", "gpt2-xl", "gpt2", "openai-gpt", "roberta-base-openai-detector", "roberta-base", "roberta-large-mnli", "roberta-large-openai-detector", "roberta-large", "t5-11b", "t5-3b", "t5-base", "t5-large", "t5-small", "transfo-xl-wt103", "xlm-clm-ende-1024", "xlm-clm-enfr-1024", "xlm-mlm-100-1280", "xlm-mlm-17-1280", "xlm-mlm-en-2048", "xlm-mlm-ende-1024", "xlm-mlm-enfr-1024", "xlm-mlm-enro-1024", "xlm-mlm-tlm-xnli15-1024", "xlm-mlm-xnli15-1024", "xlm-roberta-base", "xlm-roberta-large-finetuned-conll02-dutch", "xlm-roberta-large-finetuned-conll02-spanish", "xlm-roberta-large-finetuned-conll03-english", "xlm-roberta-large-finetuned-conll03-german", "xlm-roberta-large", "xlnet-base-cased", "xlnet-large-cased", ] if not os.path.exists(model_name_or_path): # Not a path, load from hub if "\\" in model_name_or_path or model_name_or_path.count("/") > 1: raise ValueError("Path {} not found".format(model_name_or_path)) if "/" not in model_name_or_path and model_name_or_path.lower() not in basic_transformer_models: # A model from sentence-transformers model_name_or_path = __MODEL_HUB_ORGANIZATION__ + "/" + model_name_or_path if is_sentence_transformer_model(model_name_or_path, token, cache_folder=cache_folder, revision=revision): modules = self._load_sbert_model( model_name_or_path, token=token, cache_folder=cache_folder, revision=revision, trust_remote_code=trust_remote_code, ) else: modules = self._load_auto_model( model_name_or_path, token=token, cache_folder=cache_folder, revision=revision, trust_remote_code=trust_remote_code, ) if modules is not None and not isinstance(modules, OrderedDict): modules = OrderedDict([(str(idx), module) for idx, module in enumerate(modules)]) super().__init__(modules) if device is None: device = get_device_name() logger.info("Use pytorch device_name: {}".format(device)) self.to(device) self.is_hpu_graph_enabled = False if self.default_prompt_name is not None and self.default_prompt_name not in self.prompts: raise ValueError( f"Default prompt name '{self.default_prompt_name}' not found in the configured prompts " f"dictionary with keys {list(self.prompts.keys())!r}." ) if self.prompts: logger.info(f"{len(self.prompts)} prompts are loaded, with the keys: {list(self.prompts.keys())}") if self.default_prompt_name: logger.warning( f"Default prompt name is set to '{self.default_prompt_name}'. " "This prompt will be applied to all `encode()` calls, except if `encode()` " "is called with `prompt` or `prompt_name` parameters." ) # Ideally, INSTRUCTOR models should set `include_prompt=False` in their pooling configuration, but # that would be a breaking change for users currently using the InstructorEmbedding project. # So, instead we hardcode setting it for the main INSTRUCTOR models, and otherwise give a warning if we # suspect the user is using an INSTRUCTOR model. if model_name_or_path in ("hkunlp/instructor-base", "hkunlp/instructor-large", "hkunlp/instructor-xl"): self.set_pooling_include_prompt(include_prompt=False) elif ( model_name_or_path and "/" in model_name_or_path and "instructor" in model_name_or_path.split("/")[1].lower() ): if any([module.include_prompt for module in self if isinstance(module, Pooling)]): logger.warning( "Instructor models require `include_prompt=False` in the pooling configuration. " "Either update the model configuration or call `model.set_pooling_include_prompt(False)` after loading the model." ) def encode( self, sentences: Union[str, List[str]], prompt_name: Optional[str] = None, prompt: Optional[str] = None, batch_size: int = 32, show_progress_bar: bool = None, output_value: Optional[Literal["sentence_embedding", "token_embeddings"]] = "sentence_embedding", precision: Literal["float32", "int8", "uint8", "binary", "ubinary"] = "float32", convert_to_numpy: bool = True, convert_to_tensor: bool = False, device: str = None, normalize_embeddings: bool = False, ) -> Union[List[Tensor], ndarray, Tensor]: """ Computes sentence embeddings. :param sentences: the sentences to embed. :param prompt_name: The name of the prompt to use for encoding. Must be a key in the `prompts` dictionary, which is either set in the constructor or loaded from the model configuration. For example if `prompt_name` is ``"query"`` and the `prompts` is ``{"query": "query: ", ...}``, then the sentence "What is the capital of France?" will be encoded as "query: What is the capital of France?" because the sentence is appended to the prompt. If `prompt` is also set, this argument is ignored. :param prompt: The prompt to use for encoding. For example, if the prompt is ``"query: "``, then the sentence "What is the capital of France?" will be encoded as "query: What is the capital of France?" because the sentence is appended to the prompt. If `prompt` is set, `prompt_name` is ignored. :param batch_size: the batch size used for the computation. :param show_progress_bar: Whether to output a progress bar when encode sentences. :param output_value: The type of embeddings to return: "sentence_embedding" to get sentence embeddings, "token_embeddings" to get wordpiece token embeddings, and `None`, to get all output values. Defaults to "sentence_embedding". :param precision: The precision to use for the embeddings. Can be "float32", "int8", "uint8", "binary", or "ubinary". All non-float32 precisions are quantized embeddings. Quantized embeddings are smaller in size and faster to compute, but may have a lower accuracy. They are useful for reducing the size of the embeddings of a corpus for semantic search, among other tasks. Defaults to "float32". :param convert_to_numpy: Whether the output should be a list of numpy vectors. If False, it is a list of PyTorch tensors. :param convert_to_tensor: Whether the output should be one large tensor. Overwrites `convert_to_numpy`. :param device: Which `torch.device` to use for the computation. :param normalize_embeddings: Whether to normalize returned vectors to have length 1. In that case, the faster dot-product (util.dot_score) instead of cosine similarity can be used. :return: By default, a 2d numpy array with shape [num_inputs, output_dimension] is returned. If only one string input is provided, then the output is a 1d array with shape [output_dimension]. If `convert_to_tensor`, a torch Tensor is returned instead. If `self.truncate_dim <= output_dimension` then output_dimension is `self.truncate_dim`. """ if self.device.type == "hpu" and not self.is_hpu_graph_enabled: import habana_frameworks.torch as ht ht.hpu.wrap_in_hpu_graph(self, disable_tensor_cache=True) self.is_hpu_graph_enabled = True self.eval() if show_progress_bar is None: show_progress_bar = ( logger.getEffectiveLevel() == logging.INFO or logger.getEffectiveLevel() == logging.DEBUG ) if convert_to_tensor: convert_to_numpy = False if output_value != "sentence_embedding": convert_to_tensor = False convert_to_numpy = False input_was_string = False if isinstance(sentences, str) or not hasattr( sentences, "__len__" ): # Cast an individual sentence to a list with length 1 sentences = [sentences] input_was_string = True if prompt is None: if prompt_name is not None: try: prompt = self.prompts[prompt_name] except KeyError: raise ValueError( f"Prompt name '{prompt_name}' not found in the configured prompts dictionary with keys {list(self.prompts.keys())!r}." ) elif self.default_prompt_name is not None: prompt = self.prompts.get(self.default_prompt_name, None) else: if prompt_name is not None: logger.warning( "Encode with either a `prompt`, a `prompt_name`, or neither, but not both. " "Ignoring the `prompt_name` in favor of `prompt`." ) extra_features = {} if prompt is not None: sentences = [prompt + sentence for sentence in sentences] # Some models (e.g. INSTRUCTOR, GRIT) require removing the prompt before pooling # Tracking the prompt length allow us to remove the prompt during pooling tokenized_prompt = self.tokenize([prompt]) if "input_ids" in tokenized_prompt: extra_features["prompt_length"] = tokenized_prompt["input_ids"].shape[-1] - 1 if device is None: device = self.device self.to(device) all_embeddings = [] length_sorted_idx = np.argsort([-self._text_length(sen) for sen in sentences]) sentences_sorted = [sentences[idx] for idx in length_sorted_idx] 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] features = self.tokenize(sentences_batch) features = batch_to_device(features, device) features.update(extra_features) with torch.no_grad(): out_features = self.forward(features) out_features["sentence_embedding"] = truncate_embeddings( out_features["sentence_embedding"], self.truncate_dim ) if output_value == "token_embeddings": embeddings = [] for token_emb, attention in zip(out_features[output_value], out_features["attention_mask"]): last_mask_id = len(attention) - 1 while last_mask_id > 0 and attention[last_mask_id].item() == 0: last_mask_id -= 1 embeddings.append(token_emb[0 : last_mask_id + 1]) elif output_value is None: # Return all outputs embeddings = [] for sent_idx in range(len(out_features["sentence_embedding"])): row = {name: out_features[name][sent_idx] for name in out_features} embeddings.append(row) else: # Sentence embeddings embeddings = out_features[output_value] embeddings = embeddings.detach() if normalize_embeddings: embeddings = torch.nn.functional.normalize(embeddings, p=2, dim=1) # fixes for #522 and #487 to avoid oom problems on gpu with large datasets if convert_to_numpy: embeddings = embeddings.cpu() all_embeddings.extend(embeddings) all_embeddings = [all_embeddings[idx] for idx in np.argsort(length_sorted_idx)] if precision and precision != "float32": all_embeddings = quantize_embeddings(all_embeddings, precision=precision) if convert_to_tensor: if len(all_embeddings): if isinstance(all_embeddings, np.ndarray): all_embeddings = torch.from_numpy(all_embeddings) else: all_embeddings = torch.stack(all_embeddings) else: all_embeddings = torch.Tensor() elif convert_to_numpy: if not isinstance(all_embeddings, np.ndarray): all_embeddings = np.asarray([emb.numpy() for emb in all_embeddings]) elif isinstance(all_embeddings, np.ndarray): all_embeddings = [torch.from_numpy(embedding) for embedding in all_embeddings] if input_was_string: all_embeddings = all_embeddings[0] return all_embeddings def start_multi_process_pool(self, target_devices: List[str] = None): """ Starts multi process to process the encoding with several, independent processes. 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. :param target_devices: PyTorch target devices, e.g. ["cuda:0", "cuda:1", ...], ["npu:0", "npu:1", ...] or ["cpu", "cpu", "cpu", "cpu"]. If target_devices is None and CUDA/NPU is available, then all available CUDA/NPU devices will be used. If target_devices is None and CUDA/NPU is not available, then 4 CPU devices will be used. :return: Returns a dict with the target processes, an input queue and and output queue. """ if target_devices is None: if torch.cuda.is_available(): target_devices = ["cuda:{}".format(i) for i in range(torch.cuda.device_count())] elif is_torch_npu_available(): target_devices = ["npu:{}".format(i) for i in range(torch.npu.device_count())] else: logger.info("CUDA/NPU is not available. Starting 4 CPU workers") target_devices = ["cpu"] * 4 logger.info("Start multi-process pool on devices: {}".format(", ".join(map(str, 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 target_devices: p = ctx.Process( target=SentenceTransformer._encode_multi_process_worker, 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 stop_multi_process_pool(pool): """ Stops all processes started with start_multi_process_pool """ for p in pool["processes"]: p.terminate() for p in pool["processes"]: p.join() p.close() pool["input"].close() pool["output"].close() def encode_multi_process( self, sentences: List[str], pool: Dict[str, object], prompt_name: Optional[str] = None, prompt: Optional[str] = None, batch_size: int = 32, chunk_size: int = None, normalize_embeddings: bool = False, ): """ This method allows to run encode() on multiple GPUs. The sentences are chunked into smaller packages and sent to individual processes, which encode these on the different GPUs. This method is only suitable for encoding large sets of sentences :param sentences: List of sentences :param pool: A pool of workers started with SentenceTransformer.start_multi_process_pool :param prompt_name: The name of the prompt to use for encoding. Must be a key in the `prompts` dictionary, which is either set in the constructor or loaded from the model configuration. For example if `prompt_name` is ``"query"`` and the `prompts` is ``{"query": "query: {}", ...}``, then the sentence "What is the capital of France?" will be encoded as "query: What is the capital of France?". If `prompt` is also set, this argument is ignored. :param prompt: The prompt to use for encoding. For example, if the prompt is ``"query: {}"``, then the sentence "What is the capital of France?" will be encoded as "query: What is the capital of France?". If `prompt` is set, `prompt_name` is ignored. :param batch_size: Encode sentences with batch size :param chunk_size: Sentences are chunked and sent to the individual processes. If none, it determine a sensible size. :param normalize_embeddings: Whether to normalize returned vectors to have length 1. In that case, the faster dot-product (util.dot_score) instead of cosine similarity can be used. :return: 2d numpy array with shape [num_inputs, output_dimension] """ if chunk_size is None: chunk_size = min(math.ceil(len(sentences) / len(pool["processes"]) / 10), 5000) logger.debug(f"Chunk data into {math.ceil(len(sentences) / chunk_size)} packages of size {chunk_size}") 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, batch_size, chunk, prompt_name, prompt, normalize_embeddings]) last_chunk_id += 1 chunk = [] if len(chunk) > 0: input_queue.put([last_chunk_id, batch_size, chunk, prompt_name, prompt, normalize_embeddings]) last_chunk_id += 1 output_queue = pool["output"] results_list = sorted([output_queue.get() for _ in range(last_chunk_id)], key=lambda x: x[0]) embeddings = np.concatenate([result[1] for result in results_list]) return embeddings @staticmethod def _encode_multi_process_worker(target_device: str, model, input_queue, results_queue): """ Internal working process to encode sentences in multi-process setup """ while True: try: chunk_id, batch_size, sentences, prompt_name, prompt, normalize_embeddings = input_queue.get() embeddings = model.encode( sentences, prompt_name=prompt_name, prompt=prompt, device=target_device, show_progress_bar=False, convert_to_numpy=True, batch_size=batch_size, normalize_embeddings=normalize_embeddings, ) results_queue.put([chunk_id, embeddings]) except queue.Empty: break def set_pooling_include_prompt(self, include_prompt: bool) -> None: """ Sets the `include_prompt` attribute in the pooling layer in the model, if there is one. :param include_prompt: Whether to include the prompt in the pooling layer. """ for module in self: if isinstance(module, Pooling): module.include_prompt = include_prompt break def get_max_seq_length(self): """ Returns the maximal sequence length for input the model accepts. Longer inputs will be truncated """ if hasattr(self._first_module(), "max_seq_length"): return self._first_module().max_seq_length return None def tokenize(self, texts: Union[List[str], List[Dict], List[Tuple[str, str]]]): """ Tokenizes the texts """ kwargs = {} # HPU models reach optimal performance if the padding is not dynamic if self.device.type == "hpu": kwargs["padding"] = "max_length" try: return self._first_module().tokenize(texts, **kwargs) except TypeError: # In case some Module does not allow for kwargs in tokenize, we also try without any return self._first_module().tokenize(texts) def get_sentence_features(self, *features): return self._first_module().get_sentence_features(*features) def get_sentence_embedding_dimension(self) -> Optional[int]: """ :return: The number of dimensions in the output of `encode`. If it's not known, it's `None`. """ output_dim = None for mod in reversed(self._modules.values()): sent_embedding_dim_method = getattr(mod, "get_sentence_embedding_dimension", None) if callable(sent_embedding_dim_method): output_dim = sent_embedding_dim_method() break if self.truncate_dim is not None: # The user requested truncation. If they set it to a dim greater than output_dim, # no truncation will actually happen. So return output_dim insead of self.truncate_dim return min(output_dim or np.inf, self.truncate_dim) return output_dim @contextmanager def truncate_sentence_embeddings(self, truncate_dim: Optional[int]): """ In this context, `model.encode` outputs sentence embeddings truncated at dimension `truncate_dim`. This may be useful when you are using the same model for different applications where different dimensions are needed. :param truncate_dim: The dimension to truncate sentence embeddings to. `None` does no truncation. Example:: from sentence_transformers import SentenceTransformer model = SentenceTransformer("model-name") with model.truncate_sentence_embeddings(truncate_dim=16): embeddings_truncated = model.encode(["hello there", "hiya"]) assert embeddings_truncated.shape[-1] == 16 """ original_output_dim = self.truncate_dim try: self.truncate_dim = truncate_dim yield finally: self.truncate_dim = original_output_dim def _first_module(self): """Returns the first module of this sequential embedder""" return self._modules[next(iter(self._modules))] def _last_module(self): """Returns the last module of this sequential embedder""" return self._modules[next(reversed(self._modules))] def save( self, path: str, model_name: Optional[str] = None, create_model_card: bool = True, train_datasets: Optional[List[str]] = None, safe_serialization: bool = True, ): """ Saves all elements for this seq. sentence embedder into different sub-folders :param path: Path on disc :param model_name: Optional model name :param create_model_card: If True, create a README.md with basic information about this model :param train_datasets: Optional list with the names of the datasets used to to train the model :param safe_serialization: If true, save the model using safetensors. If false, save the model the traditional PyTorch way """ if path is None: return os.makedirs(path, exist_ok=True) logger.info("Save model to {}".format(path)) modules_config = [] # Save some model info if "__version__" not in self._model_config: self._model_config["__version__"] = { "sentence_transformers": __version__, "transformers": transformers.__version__, "pytorch": torch.__version__, } with open(os.path.join(path, "config_sentence_transformers.json"), "w") as fOut: config = self._model_config.copy() config["prompts"] = self.prompts config["default_prompt_name"] = self.default_prompt_name json.dump(config, fOut, indent=2) # Save modules for idx, name in enumerate(self._modules): module = self._modules[name] if idx == 0 and isinstance(module, Transformer): # Save transformer model in the main folder model_path = path + "/" else: model_path = os.path.join(path, str(idx) + "_" + type(module).__name__) os.makedirs(model_path, exist_ok=True) if isinstance(module, Transformer): module.save(model_path, safe_serialization=safe_serialization) else: module.save(model_path) modules_config.append( {"idx": idx, "name": name, "path": os.path.basename(model_path), "type": type(module).__module__} ) with open(os.path.join(path, "modules.json"), "w") as fOut: json.dump(modules_config, fOut, indent=2) # Create model card if create_model_card: self._create_model_card(path, model_name, train_datasets) def _create_model_card( self, path: str, model_name: Optional[str] = None, train_datasets: Optional[List[str]] = None ): """ Create an automatic model and stores it in path """ if self._model_card_text is not None and len(self._model_card_text) > 0: model_card = self._model_card_text else: tags = ModelCardTemplate.__TAGS__.copy() model_card = ModelCardTemplate.__MODEL_CARD__ if ( len(self._modules) == 2 and isinstance(self._first_module(), Transformer) and isinstance(self._last_module(), Pooling) and self._last_module().get_pooling_mode_str() in ["cls", "max", "mean"] ): pooling_module = self._last_module() pooling_mode = pooling_module.get_pooling_mode_str() model_card = model_card.replace( "{USAGE_TRANSFORMERS_SECTION}", ModelCardTemplate.__USAGE_TRANSFORMERS__ ) pooling_fct_name, pooling_fct = ModelCardTemplate.model_card_get_pooling_function(pooling_mode) model_card = ( model_card.replace("{POOLING_FUNCTION}", pooling_fct) .replace("{POOLING_FUNCTION_NAME}", pooling_fct_name) .replace("{POOLING_MODE}", pooling_mode) ) tags.append("transformers") # Print full model model_card = model_card.replace("{FULL_MODEL_STR}", str(self)) # Add tags model_card = model_card.replace("{TAGS}", "\n".join(["- " + t for t in tags])) datasets_str = "" if train_datasets is not None: datasets_str = "datasets:\n" + "\n".join(["- " + d for d in train_datasets]) model_card = model_card.replace("{DATASETS}", datasets_str) # Add dim info self._model_card_vars["{NUM_DIMENSIONS}"] = self.get_sentence_embedding_dimension() # Replace vars we created while using the model for name, value in self._model_card_vars.items(): model_card = model_card.replace(name, str(value)) # Replace remaining vars with default values for name, value in ModelCardTemplate.__DEFAULT_VARS__.items(): model_card = model_card.replace(name, str(value)) if model_name is not None: model_card = model_card.replace("{MODEL_NAME}", model_name.strip()) with open(os.path.join(path, "README.md"), "w", encoding="utf8") as fOut: fOut.write(model_card.strip()) @save_to_hub_args_decorator def save_to_hub( self, repo_id: str, organization: Optional[str] = None, token: Optional[str] = None, private: Optional[bool] = None, safe_serialization: bool = True, commit_message: str = "Add new SentenceTransformer model.", local_model_path: Optional[str] = None, exist_ok: bool = False, replace_model_card: bool = False, train_datasets: Optional[List[str]] = None, ) -> str: """ DEPRECATED, use `push_to_hub` instead. Uploads all elements of this Sentence Transformer to a new HuggingFace Hub repository. :param repo_id: Repository name for your model in the Hub, including the user or organization. :param token: An authentication token (See https://huggingface.co/settings/token) :param private: Set to true, for hosting a private model :param safe_serialization: If true, save the model using safetensors. If false, save the model the traditional PyTorch way :param commit_message: Message to commit while pushing. :param local_model_path: Path of the model locally. If set, this file path will be uploaded. Otherwise, the current model will be uploaded :param exist_ok: If true, saving to an existing repository is OK. If false, saving only to a new repository is possible :param replace_model_card: If true, replace an existing model card in the hub with the automatically created model card :param train_datasets: Datasets used to train the model. If set, the datasets will be added to the model card in the Hub. :param organization: Deprecated. Organization in which you want to push your model or tokenizer (you must be a member of this organization). :return: The url of the commit of your model in the repository on the Hugging Face Hub. """ logger.warning( "The `save_to_hub` method is deprecated and will be removed in a future version of SentenceTransformers." " Please use `push_to_hub` instead for future model uploads." ) if organization: if "/" not in repo_id: logger.warning( f'Providing an `organization` to `save_to_hub` is deprecated, please use `repo_id="{organization}/{repo_id}"` instead.' ) repo_id = f"{organization}/{repo_id}" elif repo_id.split("/")[0] != organization: raise ValueError( "Providing an `organization` to `save_to_hub` is deprecated, please only use `repo_id`." ) else: logger.warning( f'Providing an `organization` to `save_to_hub` is deprecated, please only use `repo_id="{repo_id}"` instead.' ) return self.push_to_hub( repo_id=repo_id, token=token, private=private, safe_serialization=safe_serialization, commit_message=commit_message, local_model_path=local_model_path, exist_ok=exist_ok, replace_model_card=replace_model_card, train_datasets=train_datasets, ) def push_to_hub( self, repo_id: str, token: Optional[str] = None, private: Optional[bool] = None, safe_serialization: bool = True, commit_message: str = "Add new SentenceTransformer model.", local_model_path: Optional[str] = None, exist_ok: bool = False, replace_model_card: bool = False, train_datasets: Optional[List[str]] = None, ) -> str: """ Uploads all elements of this Sentence Transformer to a new HuggingFace Hub repository. :param repo_id: Repository name for your model in the Hub, including the user or organization. :param token: An authentication token (See https://huggingface.co/settings/token) :param private: Set to true, for hosting a private model :param safe_serialization: If true, save the model using safetensors. If false, save the model the traditional PyTorch way :param commit_message: Message to commit while pushing. :param local_model_path: Path of the model locally. If set, this file path will be uploaded. Otherwise, the current model will be uploaded :param exist_ok: If true, saving to an existing repository is OK. If false, saving only to a new repository is possible :param replace_model_card: If true, replace an existing model card in the hub with the automatically created model card :param train_datasets: Datasets used to train the model. If set, the datasets will be added to the model card in the Hub. :return: The url of the commit of your model in the repository on the Hugging Face Hub. """ api = HfApi(token=token) repo_url = api.create_repo( repo_id=repo_id, private=private, repo_type=None, exist_ok=exist_ok, ) repo_id = repo_url.repo_id # Update the repo_id in case the old repo_id didn't contain a user or organization if local_model_path: folder_url = api.upload_folder( repo_id=repo_id, folder_path=local_model_path, commit_message=commit_message ) else: with tempfile.TemporaryDirectory() as tmp_dir: create_model_card = replace_model_card or not os.path.exists(os.path.join(tmp_dir, "README.md")) self.save( tmp_dir, model_name=repo_url.repo_id, create_model_card=create_model_card, train_datasets=train_datasets, safe_serialization=safe_serialization, ) folder_url = api.upload_folder(repo_id=repo_id, folder_path=tmp_dir, commit_message=commit_message) refs = api.list_repo_refs(repo_id=repo_id) for branch in refs.branches: if branch.name == "main": return f"https://huggingface.co/{repo_id}/commit/{branch.target_commit}" # This isn't expected to ever be reached. return folder_url def smart_batching_collate(self, batch: List["InputExample"]) -> Tuple[List[Dict[str, Tensor]], Tensor]: """ Transforms a batch from a SmartBatchingDataset to a batch of tensors for the model Here, batch is a list of InputExample instances: [InputExample(...), ...] :param batch: a batch from a SmartBatchingDataset :return: a batch of tensors for the model """ texts = [example.texts for example in batch] sentence_features = [self.tokenize(sentence) for sentence in zip(*texts)] labels = torch.tensor([example.label for example in batch]) return sentence_features, labels def _text_length(self, text: Union[List[int], List[List[int]]]): """ Help function to get the length for the input text. Text can be either a list of ints (which means a single text as input), or a tuple of list of ints (representing several text inputs to the model). """ if isinstance(text, dict): # {key: value} case return len(next(iter(text.values()))) elif not hasattr(text, "__len__"): # Object has no len() method return 1 elif len(text) == 0 or isinstance(text[0], int): # Empty string or list of ints return len(text) else: return sum([len(t) for t in text]) # Sum of length of individual strings def fit( self, train_objectives: Iterable[Tuple[DataLoader, nn.Module]], evaluator: SentenceEvaluator = None, epochs: int = 1, steps_per_epoch=None, scheduler: str = "WarmupLinear", warmup_steps: int = 10000, optimizer_class: Type[Optimizer] = torch.optim.AdamW, optimizer_params: Dict[str, object] = {"lr": 2e-5}, weight_decay: float = 0.01, evaluation_steps: int = 0, output_path: str = 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, checkpoint_path: str = None, checkpoint_save_steps: int = 500, checkpoint_save_total_limit: int = 0, ): """ Train the model with the given training objective Each training objective is sampled in turn for one batch. We sample only as many batches from each objective as there are in the smallest one to make sure of equal training with each dataset. :param train_objectives: Tuples of (DataLoader, LossFunction). Pass more than one for multi-task learning :param evaluator: An evaluator (sentence_transformers.evaluation) evaluates the model performance during training on held-out dev data. It is used to determine the best model that is saved to disc. :param epochs: Number of epochs for training :param steps_per_epoch: Number of training steps per epoch. If set to None (default), one epoch is equal the DataLoader size from train_objectives. :param scheduler: Learning rate scheduler. Available schedulers: constantlr, warmupconstant, warmuplinear, warmupcosine, warmupcosinewithhardrestarts :param warmup_steps: Behavior depends on the scheduler. For WarmupLinear (default), the learning rate is increased from o up to the maximal learning rate. After these many training steps, the learning rate is decreased linearly back to zero. :param optimizer_class: Optimizer :param optimizer_params: Optimizer parameters :param weight_decay: Weight decay for model parameters :param evaluation_steps: If > 0, evaluate the model using evaluator after each number of training steps :param output_path: Storage path for the model and evaluation files :param save_best_model: If true, the best model (according to evaluator) is stored at output_path :param max_grad_norm: Used for gradient normalization. :param use_amp: Use Automatic Mixed Precision (AMP). Only for Pytorch >= 1.6.0 :param callback: Callback function that is invoked after each evaluation. It must accept the following three parameters in this order: `score`, `epoch`, `steps` :param show_progress_bar: If True, output a tqdm progress bar :param checkpoint_path: Folder to save checkpoints during training :param checkpoint_save_steps: Will save a checkpoint after so many steps :param checkpoint_save_total_limit: Total number of checkpoints to store """ ##Add info to model card # info_loss_functions = "\n".join(["- {} with {} training examples".format(str(loss), len(dataloader)) for dataloader, loss in train_objectives]) info_loss_functions = [] for dataloader, loss in train_objectives: info_loss_functions.extend(ModelCardTemplate.get_train_objective_info(dataloader, loss)) info_loss_functions = "\n\n".join([text for text in info_loss_functions]) info_fit_parameters = json.dumps( { "evaluator": fullname(evaluator), "epochs": epochs, "steps_per_epoch": steps_per_epoch, "scheduler": scheduler, "warmup_steps": warmup_steps, "optimizer_class": str(optimizer_class), "optimizer_params": optimizer_params, "weight_decay": weight_decay, "evaluation_steps": evaluation_steps, "max_grad_norm": max_grad_norm, }, indent=4, sort_keys=True, ) self._model_card_text = None self._model_card_vars["{TRAINING_SECTION}"] = ModelCardTemplate.__TRAINING_SECTION__.replace( "{LOSS_FUNCTIONS}", info_loss_functions ).replace("{FIT_PARAMETERS}", info_fit_parameters) if use_amp: if is_torch_npu_available(): scaler = torch.npu.amp.GradScaler() else: scaler = torch.cuda.amp.GradScaler() self.to(self.device) dataloaders = [dataloader for dataloader, _ in train_objectives] # Use smart batching for dataloader in dataloaders: dataloader.collate_fn = self.smart_batching_collate loss_models = [loss for _, loss in train_objectives] for loss_model in loss_models: loss_model.to(self.device) self.best_score = -9999999 if steps_per_epoch is None or steps_per_epoch == 0: steps_per_epoch = min([len(dataloader) for dataloader in dataloaders]) num_train_steps = int(steps_per_epoch * epochs) # Prepare optimizers optimizers = [] schedulers = [] for loss_model in loss_models: param_optimizer = list(loss_model.named_parameters()) no_decay = ["bias", "LayerNorm.bias", "LayerNorm.weight"] optimizer_grouped_parameters = [ { "params": [p for n, p in param_optimizer if not any(nd in n for nd in no_decay)], "weight_decay": weight_decay, }, {"params": [p for n, p in param_optimizer if any(nd in n for nd in no_decay)], "weight_decay": 0.0}, ] optimizer = optimizer_class(optimizer_grouped_parameters, **optimizer_params) scheduler_obj = self._get_scheduler( optimizer, scheduler=scheduler, warmup_steps=warmup_steps, t_total=num_train_steps ) optimizers.append(optimizer) schedulers.append(scheduler_obj) global_step = 0 data_iterators = [iter(dataloader) for dataloader in dataloaders] num_train_objectives = len(train_objectives) skip_scheduler = False for epoch in trange(epochs, desc="Epoch", disable=not show_progress_bar): training_steps = 0 for loss_model in loss_models: loss_model.zero_grad() loss_model.train() for _ in trange(steps_per_epoch, desc="Iteration", smoothing=0.05, disable=not show_progress_bar): for train_idx in range(num_train_objectives): loss_model = loss_models[train_idx] optimizer = optimizers[train_idx] scheduler = schedulers[train_idx] data_iterator = data_iterators[train_idx] try: data = next(data_iterator) except StopIteration: data_iterator = iter(dataloaders[train_idx]) data_iterators[train_idx] = data_iterator data = next(data_iterator) features, labels = data labels = labels.to(self.device) features = list(map(lambda batch: batch_to_device(batch, self.device), features)) if use_amp: with torch.autocast(device_type=self.device.type): loss_value = loss_model(features, labels) scale_before_step = scaler.get_scale() scaler.scale(loss_value).backward() scaler.unscale_(optimizer) torch.nn.utils.clip_grad_norm_(loss_model.parameters(), max_grad_norm) scaler.step(optimizer) scaler.update() skip_scheduler = scaler.get_scale() != scale_before_step else: loss_value = loss_model(features, labels) loss_value.backward() torch.nn.utils.clip_grad_norm_(loss_model.parameters(), max_grad_norm) optimizer.step() optimizer.zero_grad() if not skip_scheduler: scheduler.step() training_steps += 1 global_step += 1 if evaluation_steps > 0 and training_steps % evaluation_steps == 0: self._eval_during_training( evaluator, output_path, save_best_model, epoch, training_steps, callback ) for loss_model in loss_models: loss_model.zero_grad() loss_model.train() if ( checkpoint_path is not None and checkpoint_save_steps is not None and checkpoint_save_steps > 0 and global_step % checkpoint_save_steps == 0 ): self._save_checkpoint(checkpoint_path, checkpoint_save_total_limit, global_step) self._eval_during_training(evaluator, output_path, save_best_model, epoch, -1, callback) if evaluator is None and output_path is not None: # No evaluator, but output path: save final model version self.save(output_path) if checkpoint_path is not None: self._save_checkpoint(checkpoint_path, checkpoint_save_total_limit, global_step) def evaluate(self, evaluator: SentenceEvaluator, output_path: str = None): """ Evaluate the model :param evaluator: the evaluator :param output_path: the evaluator can write the results to this path """ if output_path is not None: os.makedirs(output_path, exist_ok=True) return evaluator(self, output_path) def _eval_during_training(self, evaluator, output_path, save_best_model, epoch, steps, callback): """Runs evaluation during the training""" eval_path = output_path if output_path is not None: os.makedirs(output_path, exist_ok=True) eval_path = os.path.join(output_path, "eval") os.makedirs(eval_path, exist_ok=True) if evaluator is not None: score = evaluator(self, output_path=eval_path, epoch=epoch, steps=steps) if callback is not None: callback(score, epoch, steps) if score > self.best_score: self.best_score = score if save_best_model: self.save(output_path) def _save_checkpoint(self, checkpoint_path, checkpoint_save_total_limit, step): # Store new checkpoint self.save(os.path.join(checkpoint_path, str(step))) # Delete old checkpoints if checkpoint_save_total_limit is not None and checkpoint_save_total_limit > 0: old_checkpoints = [] for subdir in os.listdir(checkpoint_path): if subdir.isdigit(): old_checkpoints.append({"step": int(subdir), "path": os.path.join(checkpoint_path, subdir)}) if len(old_checkpoints) > checkpoint_save_total_limit: old_checkpoints = sorted(old_checkpoints, key=lambda x: x["step"]) shutil.rmtree(old_checkpoints[0]["path"]) def _load_auto_model( self, model_name_or_path: str, token: Optional[Union[bool, str]], cache_folder: Optional[str], revision: Optional[str] = None, trust_remote_code: bool = False, ): """ Creates a simple Transformer + Mean Pooling model and returns the modules """ logger.warning( "No sentence-transformers model found with name {}. Creating a new one with MEAN pooling.".format( model_name_or_path ) ) transformer_model = Transformer( model_name_or_path, cache_dir=cache_folder, model_args={"token": token, "trust_remote_code": trust_remote_code, "revision": revision}, tokenizer_args={"token": token, "trust_remote_code": trust_remote_code, "revision": revision}, ) pooling_model = Pooling(transformer_model.get_word_embedding_dimension(), "mean") return [transformer_model, pooling_model] def _load_sbert_model( self, model_name_or_path: str, token: Optional[Union[bool, str]], cache_folder: Optional[str], revision: Optional[str] = None, trust_remote_code: bool = False, ): """ Loads a full sentence-transformers model """ # Check if the config_sentence_transformers.json file exists (exists since v2 of the framework) config_sentence_transformers_json_path = load_file_path( model_name_or_path, "config_sentence_transformers.json", token=token, cache_folder=cache_folder, revision=revision, ) if config_sentence_transformers_json_path is not None: with open(config_sentence_transformers_json_path) as fIn: self._model_config = json.load(fIn) if ( "__version__" in self._model_config and "sentence_transformers" in self._model_config["__version__"] and self._model_config["__version__"]["sentence_transformers"] > __version__ ): logger.warning( "You try to use a model that was created with version {}, however, your version is {}. This might cause unexpected behavior or errors. In that case, try to update to the latest version.\n\n\n".format( self._model_config["__version__"]["sentence_transformers"], __version__ ) ) # Set prompts if not already overridden by the __init__ calls if not self.prompts: self.prompts = self._model_config.get("prompts", {}) if not self.default_prompt_name: self.default_prompt_name = self._model_config.get("default_prompt_name", None) # Check if a readme exists model_card_path = load_file_path( model_name_or_path, "README.md", token=token, cache_folder=cache_folder, revision=revision ) if model_card_path is not None: try: with open(model_card_path, encoding="utf8") as fIn: self._model_card_text = fIn.read() except Exception: pass # Load the modules of sentence transformer modules_json_path = load_file_path( model_name_or_path, "modules.json", token=token, cache_folder=cache_folder, revision=revision ) with open(modules_json_path) as fIn: modules_config = json.load(fIn) modules = OrderedDict() for module_config in modules_config: module_class = import_from_string(module_config["type"]) # For Transformer, don't load the full directory, rely on `transformers` instead # But, do load the config file first. if module_class == Transformer and module_config["path"] == "": kwargs = {} for config_name in [ "sentence_bert_config.json", "sentence_roberta_config.json", "sentence_distilbert_config.json", "sentence_camembert_config.json", "sentence_albert_config.json", "sentence_xlm-roberta_config.json", "sentence_xlnet_config.json", ]: config_path = load_file_path( model_name_or_path, config_name, token=token, cache_folder=cache_folder, revision=revision ) if config_path is not None: with open(config_path) as fIn: kwargs = json.load(fIn) break hub_kwargs = {"token": token, "trust_remote_code": trust_remote_code, "revision": revision} if "model_args" in kwargs: kwargs["model_args"].update(hub_kwargs) else: kwargs["model_args"] = hub_kwargs if "tokenizer_args" in kwargs: kwargs["tokenizer_args"].update(hub_kwargs) else: kwargs["tokenizer_args"] = hub_kwargs module = Transformer(model_name_or_path, cache_dir=cache_folder, **kwargs) else: # Normalize does not require any files to be loaded if module_class == Normalize: module_path = None else: module_path = load_dir_path( model_name_or_path, module_config["path"], token=token, cache_folder=cache_folder, revision=revision, ) module = module_class.load(module_path) modules[module_config["name"]] = module return modules @staticmethod def load(input_path): return SentenceTransformer(input_path) @staticmethod def _get_scheduler(optimizer, scheduler: str, warmup_steps: int, t_total: int): """ Returns the correct learning rate scheduler. Available scheduler: constantlr, warmupconstant, warmuplinear, warmupcosine, warmupcosinewithhardrestarts """ scheduler = scheduler.lower() if scheduler == "constantlr": return transformers.get_constant_schedule(optimizer) elif scheduler == "warmupconstant": return transformers.get_constant_schedule_with_warmup(optimizer, num_warmup_steps=warmup_steps) elif scheduler == "warmuplinear": return transformers.get_linear_schedule_with_warmup( optimizer, num_warmup_steps=warmup_steps, num_training_steps=t_total ) elif scheduler == "warmupcosine": return transformers.get_cosine_schedule_with_warmup( optimizer, num_warmup_steps=warmup_steps, num_training_steps=t_total ) elif scheduler == "warmupcosinewithhardrestarts": return transformers.get_cosine_with_hard_restarts_schedule_with_warmup( optimizer, num_warmup_steps=warmup_steps, num_training_steps=t_total ) else: raise ValueError("Unknown scheduler {}".format(scheduler)) @property def device(self) -> device: """ Get torch.device from module, assuming that the whole module has one device. """ try: return next(self.parameters()).device except StopIteration: # For nn.DataParallel compatibility in PyTorch 1.5 def find_tensor_attributes(module: nn.Module) -> List[Tuple[str, Tensor]]: tuples = [(k, v) for k, v in module.__dict__.items() if torch.is_tensor(v)] return tuples gen = self._named_members(get_members_fn=find_tensor_attributes) first_tuple = next(gen) return first_tuple[1].device @property def tokenizer(self): """ Property to get the tokenizer that is used by this model """ return self._first_module().tokenizer @tokenizer.setter def tokenizer(self, value): """ Property to set the tokenizer that should be used by this model """ self._first_module().tokenizer = value @property def max_seq_length(self): """ Property to get the maximal input sequence length for the model. Longer inputs will be truncated. """ return self._first_module().max_seq_length @max_seq_length.setter def max_seq_length(self, value): """ Property to set the maximal input sequence length for the model. Longer inputs will be truncated. """ self._first_module().max_seq_length = value @property def _target_device(self) -> torch.device: logger.warning( "`SentenceTransformer._target_device` has been removed, please use `SentenceTransformer.device` instead.", ) return self.device @_target_device.setter def _target_device(self, device: Optional[Union[int, str, torch.device]] = None) -> None: self.to(device)
(model_name_or_path: Optional[str] = None, modules: Optional[Iterable[torch.nn.modules.module.Module]] = None, device: Optional[str] = None, prompts: Optional[Dict[str, str]] = None, default_prompt_name: Optional[str] = None, cache_folder: Optional[str] = None, trust_remote_code: bool = False, revision: Optional[str] = None, token: Union[bool, str, NoneType] = None, use_auth_token: Union[bool, str, NoneType] = None, truncate_dim: Optional[int] = None)
9,989
torch.nn.modules.container
__add__
null
def __add__(self, other) -> 'Sequential': if isinstance(other, Sequential): ret = Sequential() for layer in self: ret.append(layer) for layer in other: ret.append(layer) return ret else: raise ValueError('add operator supports only objects ' f'of Sequential class, but {str(type(other))} is given.')
(self, other) -> torch.nn.modules.container.Sequential
9,990
torch.nn.modules.module
_wrapped_call_impl
null
def _wrapped_call_impl(self, *args, **kwargs): if self._compiled_call_impl is not None: return self._compiled_call_impl(*args, **kwargs) # type: ignore[misc] else: return self._call_impl(*args, **kwargs)
(self, *args, **kwargs)
9,991
torch.nn.modules.module
__delattr__
null
def __delattr__(self, name): if name in self._parameters: del self._parameters[name] elif name in self._buffers: del self._buffers[name] self._non_persistent_buffers_set.discard(name) elif name in self._modules: del self._modules[name] else: super().__delattr__(name)
(self, name)
9,992
torch.nn.modules.container
__delitem__
null
def __delitem__(self, idx: Union[slice, int]) -> None: if isinstance(idx, slice): for key in list(self._modules.keys())[idx]: delattr(self, key) else: key = self._get_item_by_idx(self._modules.keys(), idx) delattr(self, key) # To preserve numbering str_indices = [str(i) for i in range(len(self._modules))] self._modules = OrderedDict(list(zip(str_indices, self._modules.values())))
(self, idx: Union[slice, int]) -> NoneType
9,993
torch.nn.modules.container
__dir__
null
@_copy_to_script_wrapper def __dir__(self): keys = super().__dir__() keys = [key for key in keys if not key.isdigit()] return keys
(self)
9,994
torch.nn.modules.module
__getattr__
null
def __getattr__(self, name: str) -> Any: if '_parameters' in self.__dict__: _parameters = self.__dict__['_parameters'] if name in _parameters: return _parameters[name] if '_buffers' in self.__dict__: _buffers = self.__dict__['_buffers'] if name in _buffers: return _buffers[name] if '_modules' in self.__dict__: modules = self.__dict__['_modules'] if name in modules: return modules[name] raise AttributeError(f"'{type(self).__name__}' object has no attribute '{name}'")
(self, name: str) -> Any
9,995
torch.nn.modules.container
__getitem__
null
@_copy_to_script_wrapper def __getitem__(self, idx: Union[slice, int]) -> Union['Sequential', T]: if isinstance(idx, slice): return self.__class__(OrderedDict(list(self._modules.items())[idx])) else: return self._get_item_by_idx(self._modules.values(), idx)
(self, idx: Union[slice, int]) -> Union[torch.nn.modules.container.Sequential, ~T]
9,996
torch.nn.modules.module
__getstate__
null
def __getstate__(self): state = self.__dict__.copy() state.pop("_compiled_call_impl", None) return state
(self)
9,997
torch.nn.modules.container
__iadd__
null
def __iadd__(self, other) -> Self: if isinstance(other, Sequential): offset = len(self) for i, module in enumerate(other): self.add_module(str(i + offset), module) return self else: raise ValueError('add operator supports only objects ' f'of Sequential class, but {str(type(other))} is given.')
(self, other) -> typing_extensions.Self
9,998
torch.nn.modules.container
__imul__
null
def __imul__(self, other: int) -> Self: if not isinstance(other, int): raise TypeError(f"unsupported operand type(s) for *: {type(self)} and {type(other)}") elif (other <= 0): raise ValueError(f"Non-positive multiplication factor {other} for {type(self)}") else: len_original = len(self) offset = len(self) for _ in range(other - 1): for i in range(len_original): self.add_module(str(i + offset), self._modules[str(i)]) offset += len_original return self
(self, other: int) -> typing_extensions.Self
9,999
sentence_transformers.SentenceTransformer
__init__
null
def __init__( self, model_name_or_path: Optional[str] = None, modules: Optional[Iterable[nn.Module]] = None, device: Optional[str] = None, prompts: Optional[Dict[str, str]] = None, default_prompt_name: Optional[str] = None, cache_folder: Optional[str] = None, trust_remote_code: bool = False, revision: Optional[str] = None, token: Optional[Union[bool, str]] = None, use_auth_token: Optional[Union[bool, str]] = None, truncate_dim: Optional[int] = None, ): # Note: self._load_sbert_model can also update `self.prompts` and `self.default_prompt_name` self.prompts = prompts or {} self.default_prompt_name = default_prompt_name self.truncate_dim = truncate_dim self._model_card_vars = {} self._model_card_text = None self._model_config = {} if use_auth_token is not None: warnings.warn( "The `use_auth_token` argument is deprecated and will be removed in v3 of SentenceTransformers.", FutureWarning, ) if token is not None: raise ValueError( "`token` and `use_auth_token` are both specified. Please set only the argument `token`." ) token = use_auth_token if cache_folder is None: cache_folder = os.getenv("SENTENCE_TRANSFORMERS_HOME") if model_name_or_path is not None and model_name_or_path != "": logger.info("Load pretrained SentenceTransformer: {}".format(model_name_or_path)) # Old models that don't belong to any organization basic_transformer_models = [ "albert-base-v1", "albert-base-v2", "albert-large-v1", "albert-large-v2", "albert-xlarge-v1", "albert-xlarge-v2", "albert-xxlarge-v1", "albert-xxlarge-v2", "bert-base-cased-finetuned-mrpc", "bert-base-cased", "bert-base-chinese", "bert-base-german-cased", "bert-base-german-dbmdz-cased", "bert-base-german-dbmdz-uncased", "bert-base-multilingual-cased", "bert-base-multilingual-uncased", "bert-base-uncased", "bert-large-cased-whole-word-masking-finetuned-squad", "bert-large-cased-whole-word-masking", "bert-large-cased", "bert-large-uncased-whole-word-masking-finetuned-squad", "bert-large-uncased-whole-word-masking", "bert-large-uncased", "camembert-base", "ctrl", "distilbert-base-cased-distilled-squad", "distilbert-base-cased", "distilbert-base-german-cased", "distilbert-base-multilingual-cased", "distilbert-base-uncased-distilled-squad", "distilbert-base-uncased-finetuned-sst-2-english", "distilbert-base-uncased", "distilgpt2", "distilroberta-base", "gpt2-large", "gpt2-medium", "gpt2-xl", "gpt2", "openai-gpt", "roberta-base-openai-detector", "roberta-base", "roberta-large-mnli", "roberta-large-openai-detector", "roberta-large", "t5-11b", "t5-3b", "t5-base", "t5-large", "t5-small", "transfo-xl-wt103", "xlm-clm-ende-1024", "xlm-clm-enfr-1024", "xlm-mlm-100-1280", "xlm-mlm-17-1280", "xlm-mlm-en-2048", "xlm-mlm-ende-1024", "xlm-mlm-enfr-1024", "xlm-mlm-enro-1024", "xlm-mlm-tlm-xnli15-1024", "xlm-mlm-xnli15-1024", "xlm-roberta-base", "xlm-roberta-large-finetuned-conll02-dutch", "xlm-roberta-large-finetuned-conll02-spanish", "xlm-roberta-large-finetuned-conll03-english", "xlm-roberta-large-finetuned-conll03-german", "xlm-roberta-large", "xlnet-base-cased", "xlnet-large-cased", ] if not os.path.exists(model_name_or_path): # Not a path, load from hub if "\\" in model_name_or_path or model_name_or_path.count("/") > 1: raise ValueError("Path {} not found".format(model_name_or_path)) if "/" not in model_name_or_path and model_name_or_path.lower() not in basic_transformer_models: # A model from sentence-transformers model_name_or_path = __MODEL_HUB_ORGANIZATION__ + "/" + model_name_or_path if is_sentence_transformer_model(model_name_or_path, token, cache_folder=cache_folder, revision=revision): modules = self._load_sbert_model( model_name_or_path, token=token, cache_folder=cache_folder, revision=revision, trust_remote_code=trust_remote_code, ) else: modules = self._load_auto_model( model_name_or_path, token=token, cache_folder=cache_folder, revision=revision, trust_remote_code=trust_remote_code, ) if modules is not None and not isinstance(modules, OrderedDict): modules = OrderedDict([(str(idx), module) for idx, module in enumerate(modules)]) super().__init__(modules) if device is None: device = get_device_name() logger.info("Use pytorch device_name: {}".format(device)) self.to(device) self.is_hpu_graph_enabled = False if self.default_prompt_name is not None and self.default_prompt_name not in self.prompts: raise ValueError( f"Default prompt name '{self.default_prompt_name}' not found in the configured prompts " f"dictionary with keys {list(self.prompts.keys())!r}." ) if self.prompts: logger.info(f"{len(self.prompts)} prompts are loaded, with the keys: {list(self.prompts.keys())}") if self.default_prompt_name: logger.warning( f"Default prompt name is set to '{self.default_prompt_name}'. " "This prompt will be applied to all `encode()` calls, except if `encode()` " "is called with `prompt` or `prompt_name` parameters." ) # Ideally, INSTRUCTOR models should set `include_prompt=False` in their pooling configuration, but # that would be a breaking change for users currently using the InstructorEmbedding project. # So, instead we hardcode setting it for the main INSTRUCTOR models, and otherwise give a warning if we # suspect the user is using an INSTRUCTOR model. if model_name_or_path in ("hkunlp/instructor-base", "hkunlp/instructor-large", "hkunlp/instructor-xl"): self.set_pooling_include_prompt(include_prompt=False) elif ( model_name_or_path and "/" in model_name_or_path and "instructor" in model_name_or_path.split("/")[1].lower() ): if any([module.include_prompt for module in self if isinstance(module, Pooling)]): logger.warning( "Instructor models require `include_prompt=False` in the pooling configuration. " "Either update the model configuration or call `model.set_pooling_include_prompt(False)` after loading the model." )
(self, model_name_or_path: Optional[str] = None, modules: Optional[Iterable[torch.nn.modules.module.Module]] = None, device: Optional[str] = None, prompts: Optional[Dict[str, str]] = None, default_prompt_name: Optional[str] = None, cache_folder: Optional[str] = None, trust_remote_code: bool = False, revision: Optional[str] = None, token: Union[bool, str, NoneType] = None, use_auth_token: Union[bool, str, NoneType] = None, truncate_dim: Optional[int] = None)
10,000
torch.nn.modules.container
__iter__
null
@_copy_to_script_wrapper def __iter__(self) -> Iterator[Module]: return iter(self._modules.values())
(self) -> Iterator[torch.nn.modules.module.Module]
10,001
torch.nn.modules.container
__len__
null
@_copy_to_script_wrapper def __len__(self) -> int: return len(self._modules)
(self) -> int
10,002
torch.nn.modules.container
__mul__
null
def __mul__(self, other: int) -> 'Sequential': if not isinstance(other, int): raise TypeError(f"unsupported operand type(s) for *: {type(self)} and {type(other)}") elif (other <= 0): raise ValueError(f"Non-positive multiplication factor {other} for {type(self)}") else: combined = Sequential() offset = 0 for _ in range(other): for module in self: combined.add_module(str(offset), module) offset += 1 return combined
(self, other: int) -> torch.nn.modules.container.Sequential
10,003
torch.nn.modules.module
__repr__
null
def __repr__(self): # We treat the extra repr like the sub-module, one item per line extra_lines = [] extra_repr = self.extra_repr() # empty string will be split into list [''] if extra_repr: extra_lines = extra_repr.split('\n') child_lines = [] for key, module in self._modules.items(): mod_str = repr(module) mod_str = _addindent(mod_str, 2) child_lines.append('(' + key + '): ' + mod_str) lines = extra_lines + child_lines main_str = self._get_name() + '(' if lines: # simple one-liner info, which most builtin Modules will use if len(extra_lines) == 1 and not child_lines: main_str += extra_lines[0] else: main_str += '\n ' + '\n '.join(lines) + '\n' main_str += ')' return main_str
(self)
10,004
torch.nn.modules.container
__rmul__
null
def __rmul__(self, other: int) -> 'Sequential': return self.__mul__(other)
(self, other: int) -> torch.nn.modules.container.Sequential
10,005
torch.nn.modules.module
__setattr__
null
def __setattr__(self, name: str, value: Union[Tensor, 'Module']) -> None: def remove_from(*dicts_or_sets): for d in dicts_or_sets: if name in d: if isinstance(d, dict): del d[name] else: d.discard(name) params = self.__dict__.get('_parameters') if isinstance(value, Parameter): if params is None: raise AttributeError( "cannot assign parameters before Module.__init__() call") remove_from(self.__dict__, self._buffers, self._modules, self._non_persistent_buffers_set) self.register_parameter(name, value) elif params is not None and name in params: if value is not None: raise TypeError(f"cannot assign '{torch.typename(value)}' as parameter '{name}' " "(torch.nn.Parameter or None expected)" ) self.register_parameter(name, value) else: modules = self.__dict__.get('_modules') if isinstance(value, Module): if modules is None: raise AttributeError( "cannot assign module before Module.__init__() call") remove_from(self.__dict__, self._parameters, self._buffers, self._non_persistent_buffers_set) for hook in _global_module_registration_hooks.values(): output = hook(self, name, value) if output is not None: value = output modules[name] = value elif modules is not None and name in modules: if value is not None: raise TypeError(f"cannot assign '{torch.typename(value)}' as child module '{name}' " "(torch.nn.Module or None expected)" ) for hook in _global_module_registration_hooks.values(): output = hook(self, name, value) if output is not None: value = output modules[name] = value else: buffers = self.__dict__.get('_buffers') if buffers is not None and name in buffers: if value is not None and not isinstance(value, torch.Tensor): raise TypeError(f"cannot assign '{torch.typename(value)}' as buffer '{name}' " "(torch.Tensor or None expected)" ) for hook in _global_buffer_registration_hooks.values(): output = hook(self, name, value) if output is not None: value = output buffers[name] = value else: super().__setattr__(name, value)
(self, name: str, value: Union[torch.Tensor, torch.nn.modules.module.Module]) -> NoneType
10,006
torch.nn.modules.container
__setitem__
null
def __setitem__(self, idx: int, module: Module) -> None: key: str = self._get_item_by_idx(self._modules.keys(), idx) return setattr(self, key, module)
(self, idx: int, module: torch.nn.modules.module.Module) -> NoneType
10,007
torch.nn.modules.module
__setstate__
null
def __setstate__(self, state): self.__dict__.update(state) # Support loading old checkpoints that don't have the following attrs: if '_forward_pre_hooks' not in self.__dict__: self._forward_pre_hooks = OrderedDict() if '_forward_pre_hooks_with_kwargs' not in self.__dict__: self._forward_pre_hooks_with_kwargs = OrderedDict() if '_forward_hooks_with_kwargs' not in self.__dict__: self._forward_hooks_with_kwargs = OrderedDict() if '_forward_hooks_always_called' not in self.__dict__: self._forward_hooks_always_called = OrderedDict() if '_state_dict_hooks' not in self.__dict__: self._state_dict_hooks = OrderedDict() if '_state_dict_pre_hooks' not in self.__dict__: self._state_dict_pre_hooks = OrderedDict() if '_load_state_dict_pre_hooks' not in self.__dict__: self._load_state_dict_pre_hooks = OrderedDict() if '_load_state_dict_post_hooks' not in self.__dict__: self._load_state_dict_post_hooks = OrderedDict() if '_non_persistent_buffers_set' not in self.__dict__: self._non_persistent_buffers_set = set() if '_is_full_backward_hook' not in self.__dict__: self._is_full_backward_hook = None if '_backward_pre_hooks' not in self.__dict__: self._backward_pre_hooks = OrderedDict()
(self, state)
10,008
torch.nn.modules.module
_apply
null
def _apply(self, fn, recurse=True): if recurse: for module in self.children(): module._apply(fn) def compute_should_use_set_data(tensor, tensor_applied): if torch._has_compatible_shallow_copy_type(tensor, tensor_applied): # If the new tensor has compatible tensor type as the existing tensor, # the current behavior is to change the tensor in-place using `.data =`, # and the future behavior is to overwrite the existing tensor. However, # changing the current behavior is a BC-breaking change, and we want it # to happen in future releases. So for now we introduce the # `torch.__future__.get_overwrite_module_params_on_conversion()` # global flag to let the user control whether they want the future # behavior of overwriting the existing tensor or not. return not torch.__future__.get_overwrite_module_params_on_conversion() else: return False should_use_swap_tensors = torch.__future__.get_swap_module_params_on_conversion() for key, param in self._parameters.items(): if param is None: continue # Tensors stored in modules are graph leaves, and we don't want to # track autograd history of `param_applied`, so we have to use # `with torch.no_grad():` with torch.no_grad(): param_applied = fn(param) p_should_use_set_data = compute_should_use_set_data(param, param_applied) # subclasses may have multiple child tensors so we need to use swap_tensors p_should_use_swap_tensors = should_use_swap_tensors or is_traceable_wrapper_subclass(param_applied) param_grad = param.grad if p_should_use_swap_tensors: try: if param_grad is not None: # Accessing param.grad makes its at::Tensor's use_count 2, which will prevent swapping. # Decrement use count of the gradient by setting to None param.grad = None param_applied = torch.nn.Parameter(param_applied, requires_grad=param.requires_grad) torch.utils.swap_tensors(param, param_applied) except Exception as e: if param_grad is not None: param.grad = param_grad raise RuntimeError(f"_apply(): Couldn't swap {self._get_name()}.{key}") from e out_param = param elif p_should_use_set_data: param.data = param_applied out_param = param else: assert isinstance(param, Parameter) assert param.is_leaf out_param = Parameter(param_applied, param.requires_grad) self._parameters[key] = out_param if param_grad is not None: with torch.no_grad(): grad_applied = fn(param_grad) g_should_use_set_data = compute_should_use_set_data(param_grad, grad_applied) if p_should_use_swap_tensors: grad_applied.requires_grad_(param_grad.requires_grad) try: torch.utils.swap_tensors(param_grad, grad_applied) except Exception as e: raise RuntimeError(f"_apply(): Couldn't swap {self._get_name()}.{key}.grad") from e out_param.grad = param_grad elif g_should_use_set_data: assert out_param.grad is not None out_param.grad.data = grad_applied else: assert param_grad.is_leaf out_param.grad = grad_applied.requires_grad_(param_grad.requires_grad) for key, buf in self._buffers.items(): if buf is not None: self._buffers[key] = fn(buf) return self
(self, fn, recurse=True)
10,009
torch.nn.modules.module
_call_impl
null
def _call_impl(self, *args, **kwargs): forward_call = (self._slow_forward if torch._C._get_tracing_state() else self.forward) # If we don't have any hooks, we want to skip the rest of the logic in # this function, and just call forward. if not (self._backward_hooks or self._backward_pre_hooks or self._forward_hooks or self._forward_pre_hooks or _global_backward_pre_hooks or _global_backward_hooks or _global_forward_hooks or _global_forward_pre_hooks): return forward_call(*args, **kwargs) try: result = None called_always_called_hooks = set() full_backward_hooks, non_full_backward_hooks = [], [] backward_pre_hooks = [] if self._backward_pre_hooks or _global_backward_pre_hooks: backward_pre_hooks = self._get_backward_pre_hooks() if self._backward_hooks or _global_backward_hooks: full_backward_hooks, non_full_backward_hooks = self._get_backward_hooks() if _global_forward_pre_hooks or self._forward_pre_hooks: for hook_id, hook in ( *_global_forward_pre_hooks.items(), *self._forward_pre_hooks.items(), ): if hook_id in self._forward_pre_hooks_with_kwargs: args_kwargs_result = hook(self, args, kwargs) # type: ignore[misc] if args_kwargs_result is not None: if isinstance(args_kwargs_result, tuple) and len(args_kwargs_result) == 2: args, kwargs = args_kwargs_result else: raise RuntimeError( "forward pre-hook must return None or a tuple " f"of (new_args, new_kwargs), but got {args_kwargs_result}." ) else: args_result = hook(self, args) if args_result is not None: if not isinstance(args_result, tuple): args_result = (args_result,) args = args_result bw_hook = None if full_backward_hooks or backward_pre_hooks: bw_hook = hooks.BackwardHook(self, full_backward_hooks, backward_pre_hooks) args = bw_hook.setup_input_hook(args) result = forward_call(*args, **kwargs) if _global_forward_hooks or self._forward_hooks: for hook_id, hook in ( *_global_forward_hooks.items(), *self._forward_hooks.items(), ): # mark that always called hook is run if hook_id in self._forward_hooks_always_called or hook_id in _global_forward_hooks_always_called: called_always_called_hooks.add(hook_id) if hook_id in self._forward_hooks_with_kwargs: hook_result = hook(self, args, kwargs, result) else: hook_result = hook(self, args, result) if hook_result is not None: result = hook_result if bw_hook: if not isinstance(result, (torch.Tensor, tuple)): warnings.warn("For backward hooks to be called," " module output should be a Tensor or a tuple of Tensors" f" but received {type(result)}") result = bw_hook.setup_output_hook(result) # Handle the non-full backward hooks if non_full_backward_hooks: var = result while not isinstance(var, torch.Tensor): if isinstance(var, dict): var = next(v for v in var.values() if isinstance(v, torch.Tensor)) else: var = var[0] grad_fn = var.grad_fn if grad_fn is not None: for hook in non_full_backward_hooks: grad_fn.register_hook(_WrappedHook(hook, self)) self._maybe_warn_non_full_backward_hook(args, result, grad_fn) return result except Exception: # run always called hooks if they have not already been run # For now only forward hooks have the always_call option but perhaps # this functionality should be added to full backward hooks as well. for hook_id, hook in _global_forward_hooks.items(): if hook_id in _global_forward_hooks_always_called and hook_id not in called_always_called_hooks: # type: ignore[possibly-undefined] try: hook_result = hook(self, args, result) # type: ignore[possibly-undefined] if hook_result is not None: result = hook_result except Exception as e: warnings.warn("global module forward hook with ``always_call=True`` raised an exception " f"that was silenced as another error was raised in forward: {str(e)}") continue for hook_id, hook in self._forward_hooks.items(): if hook_id in self._forward_hooks_always_called and hook_id not in called_always_called_hooks: # type: ignore[possibly-undefined] try: if hook_id in self._forward_hooks_with_kwargs: hook_result = hook(self, args, kwargs, result) # type: ignore[possibly-undefined] else: hook_result = hook(self, args, result) # type: ignore[possibly-undefined] if hook_result is not None: result = hook_result except Exception as e: warnings.warn("module forward hook with ``always_call=True`` raised an exception " f"that was silenced as another error was raised in forward: {str(e)}") continue # raise exception raised in try block raise
(self, *args, **kwargs)
10,010
sentence_transformers.SentenceTransformer
_create_model_card
Create an automatic model and stores it in path
def _create_model_card( self, path: str, model_name: Optional[str] = None, train_datasets: Optional[List[str]] = None ): """ Create an automatic model and stores it in path """ if self._model_card_text is not None and len(self._model_card_text) > 0: model_card = self._model_card_text else: tags = ModelCardTemplate.__TAGS__.copy() model_card = ModelCardTemplate.__MODEL_CARD__ if ( len(self._modules) == 2 and isinstance(self._first_module(), Transformer) and isinstance(self._last_module(), Pooling) and self._last_module().get_pooling_mode_str() in ["cls", "max", "mean"] ): pooling_module = self._last_module() pooling_mode = pooling_module.get_pooling_mode_str() model_card = model_card.replace( "{USAGE_TRANSFORMERS_SECTION}", ModelCardTemplate.__USAGE_TRANSFORMERS__ ) pooling_fct_name, pooling_fct = ModelCardTemplate.model_card_get_pooling_function(pooling_mode) model_card = ( model_card.replace("{POOLING_FUNCTION}", pooling_fct) .replace("{POOLING_FUNCTION_NAME}", pooling_fct_name) .replace("{POOLING_MODE}", pooling_mode) ) tags.append("transformers") # Print full model model_card = model_card.replace("{FULL_MODEL_STR}", str(self)) # Add tags model_card = model_card.replace("{TAGS}", "\n".join(["- " + t for t in tags])) datasets_str = "" if train_datasets is not None: datasets_str = "datasets:\n" + "\n".join(["- " + d for d in train_datasets]) model_card = model_card.replace("{DATASETS}", datasets_str) # Add dim info self._model_card_vars["{NUM_DIMENSIONS}"] = self.get_sentence_embedding_dimension() # Replace vars we created while using the model for name, value in self._model_card_vars.items(): model_card = model_card.replace(name, str(value)) # Replace remaining vars with default values for name, value in ModelCardTemplate.__DEFAULT_VARS__.items(): model_card = model_card.replace(name, str(value)) if model_name is not None: model_card = model_card.replace("{MODEL_NAME}", model_name.strip()) with open(os.path.join(path, "README.md"), "w", encoding="utf8") as fOut: fOut.write(model_card.strip())
(self, path: str, model_name: Optional[str] = None, train_datasets: Optional[List[str]] = None)
10,011
sentence_transformers.SentenceTransformer
_encode_multi_process_worker
Internal working process to encode sentences in multi-process setup
@staticmethod def _encode_multi_process_worker(target_device: str, model, input_queue, results_queue): """ Internal working process to encode sentences in multi-process setup """ while True: try: chunk_id, batch_size, sentences, prompt_name, prompt, normalize_embeddings = input_queue.get() embeddings = model.encode( sentences, prompt_name=prompt_name, prompt=prompt, device=target_device, show_progress_bar=False, convert_to_numpy=True, batch_size=batch_size, normalize_embeddings=normalize_embeddings, ) results_queue.put([chunk_id, embeddings]) except queue.Empty: break
(target_device: str, model, input_queue, results_queue)
10,012
sentence_transformers.SentenceTransformer
_eval_during_training
Runs evaluation during the training
def _eval_during_training(self, evaluator, output_path, save_best_model, epoch, steps, callback): """Runs evaluation during the training""" eval_path = output_path if output_path is not None: os.makedirs(output_path, exist_ok=True) eval_path = os.path.join(output_path, "eval") os.makedirs(eval_path, exist_ok=True) if evaluator is not None: score = evaluator(self, output_path=eval_path, epoch=epoch, steps=steps) if callback is not None: callback(score, epoch, steps) if score > self.best_score: self.best_score = score if save_best_model: self.save(output_path)
(self, evaluator, output_path, save_best_model, epoch, steps, callback)
10,013
sentence_transformers.SentenceTransformer
_first_module
Returns the first module of this sequential embedder
def _first_module(self): """Returns the first module of this sequential embedder""" return self._modules[next(iter(self._modules))]
(self)
10,014
torch.nn.modules.module
_get_backward_hooks
Return the backward hooks for use in the call function. It returns two lists, one with the full backward hooks and one with the non-full backward hooks.
def _get_backward_hooks(self): r"""Return the backward hooks for use in the call function. It returns two lists, one with the full backward hooks and one with the non-full backward hooks. """ full_backward_hooks: List[Callable] = [] if (_global_is_full_backward_hook is True): full_backward_hooks += _global_backward_hooks.values() if (self._is_full_backward_hook is True): full_backward_hooks += self._backward_hooks.values() non_full_backward_hooks: List[Callable] = [] if (_global_is_full_backward_hook is False): non_full_backward_hooks += _global_backward_hooks.values() if (self._is_full_backward_hook is False): non_full_backward_hooks += self._backward_hooks.values() return full_backward_hooks, non_full_backward_hooks
(self)
10,015
torch.nn.modules.module
_get_backward_pre_hooks
null
def _get_backward_pre_hooks(self): backward_pre_hooks: List[Callable] = [] backward_pre_hooks += _global_backward_pre_hooks.values() backward_pre_hooks += self._backward_pre_hooks.values() return backward_pre_hooks
(self)
10,016
torch.nn.modules.container
_get_item_by_idx
Get the idx-th item of the iterator.
def _get_item_by_idx(self, iterator, idx) -> T: # type: ignore[misc, type-var] """Get the idx-th item of the iterator.""" size = len(self) idx = operator.index(idx) if not -size <= idx < size: raise IndexError(f'index {idx} is out of range') idx %= size return next(islice(iterator, idx, None))
(self, iterator, idx) -> ~T
10,017
torch.nn.modules.module
_get_name
null
def _get_name(self): return self.__class__.__name__
(self)
10,018
sentence_transformers.SentenceTransformer
_get_scheduler
Returns the correct learning rate scheduler. Available scheduler: constantlr, warmupconstant, warmuplinear, warmupcosine, warmupcosinewithhardrestarts
@staticmethod def _get_scheduler(optimizer, scheduler: str, warmup_steps: int, t_total: int): """ Returns the correct learning rate scheduler. Available scheduler: constantlr, warmupconstant, warmuplinear, warmupcosine, warmupcosinewithhardrestarts """ scheduler = scheduler.lower() if scheduler == "constantlr": return transformers.get_constant_schedule(optimizer) elif scheduler == "warmupconstant": return transformers.get_constant_schedule_with_warmup(optimizer, num_warmup_steps=warmup_steps) elif scheduler == "warmuplinear": return transformers.get_linear_schedule_with_warmup( optimizer, num_warmup_steps=warmup_steps, num_training_steps=t_total ) elif scheduler == "warmupcosine": return transformers.get_cosine_schedule_with_warmup( optimizer, num_warmup_steps=warmup_steps, num_training_steps=t_total ) elif scheduler == "warmupcosinewithhardrestarts": return transformers.get_cosine_with_hard_restarts_schedule_with_warmup( optimizer, num_warmup_steps=warmup_steps, num_training_steps=t_total ) else: raise ValueError("Unknown scheduler {}".format(scheduler))
(optimizer, scheduler: str, warmup_steps: int, t_total: int)
10,019
sentence_transformers.SentenceTransformer
_last_module
Returns the last module of this sequential embedder
def _last_module(self): """Returns the last module of this sequential embedder""" return self._modules[next(reversed(self._modules))]
(self)
10,020
sentence_transformers.SentenceTransformer
_load_auto_model
Creates a simple Transformer + Mean Pooling model and returns the modules
def _load_auto_model( self, model_name_or_path: str, token: Optional[Union[bool, str]], cache_folder: Optional[str], revision: Optional[str] = None, trust_remote_code: bool = False, ): """ Creates a simple Transformer + Mean Pooling model and returns the modules """ logger.warning( "No sentence-transformers model found with name {}. Creating a new one with MEAN pooling.".format( model_name_or_path ) ) transformer_model = Transformer( model_name_or_path, cache_dir=cache_folder, model_args={"token": token, "trust_remote_code": trust_remote_code, "revision": revision}, tokenizer_args={"token": token, "trust_remote_code": trust_remote_code, "revision": revision}, ) pooling_model = Pooling(transformer_model.get_word_embedding_dimension(), "mean") return [transformer_model, pooling_model]
(self, model_name_or_path: str, token: Union[bool, str, NoneType], cache_folder: Optional[str], revision: Optional[str] = None, trust_remote_code: bool = False)
10,021
torch.nn.modules.module
_load_from_state_dict
Copy parameters and buffers from :attr:`state_dict` into only this module, but not its descendants. This is called on every submodule in :meth:`~torch.nn.Module.load_state_dict`. Metadata saved for this module in input :attr:`state_dict` is provided as :attr:`local_metadata`. For state dicts without metadata, :attr:`local_metadata` is empty. Subclasses can achieve class-specific backward compatible loading using the version number at `local_metadata.get("version", None)`. Additionally, :attr:`local_metadata` can also contain the key `assign_to_params_buffers` that indicates whether keys should be assigned their corresponding tensor in the state_dict. .. note:: :attr:`state_dict` is not the same object as the input :attr:`state_dict` to :meth:`~torch.nn.Module.load_state_dict`. So it can be modified. Args: state_dict (dict): a dict containing parameters and persistent buffers. prefix (str): the prefix for parameters and buffers used in this module local_metadata (dict): a dict containing the metadata for this module. See strict (bool): whether to strictly enforce that the keys in :attr:`state_dict` with :attr:`prefix` match the names of parameters and buffers in this module missing_keys (list of str): if ``strict=True``, add missing keys to this list unexpected_keys (list of str): if ``strict=True``, add unexpected keys to this list error_msgs (list of str): error messages should be added to this list, and will be reported together in :meth:`~torch.nn.Module.load_state_dict`
def _load_from_state_dict(self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs): r"""Copy parameters and buffers from :attr:`state_dict` into only this module, but not its descendants. This is called on every submodule in :meth:`~torch.nn.Module.load_state_dict`. Metadata saved for this module in input :attr:`state_dict` is provided as :attr:`local_metadata`. For state dicts without metadata, :attr:`local_metadata` is empty. Subclasses can achieve class-specific backward compatible loading using the version number at `local_metadata.get("version", None)`. Additionally, :attr:`local_metadata` can also contain the key `assign_to_params_buffers` that indicates whether keys should be assigned their corresponding tensor in the state_dict. .. note:: :attr:`state_dict` is not the same object as the input :attr:`state_dict` to :meth:`~torch.nn.Module.load_state_dict`. So it can be modified. Args: state_dict (dict): a dict containing parameters and persistent buffers. prefix (str): the prefix for parameters and buffers used in this module local_metadata (dict): a dict containing the metadata for this module. See strict (bool): whether to strictly enforce that the keys in :attr:`state_dict` with :attr:`prefix` match the names of parameters and buffers in this module missing_keys (list of str): if ``strict=True``, add missing keys to this list unexpected_keys (list of str): if ``strict=True``, add unexpected keys to this list error_msgs (list of str): error messages should be added to this list, and will be reported together in :meth:`~torch.nn.Module.load_state_dict` """ for hook in self._load_state_dict_pre_hooks.values(): hook(state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs) persistent_buffers = {k: v for k, v in self._buffers.items() if k not in self._non_persistent_buffers_set} local_name_params = itertools.chain(self._parameters.items(), persistent_buffers.items()) local_state = {k: v for k, v in local_name_params if v is not None} assign_to_params_buffers = local_metadata.get("assign_to_params_buffers", False) use_swap_tensors = torch.__future__.get_swap_module_params_on_conversion() for name, param in local_state.items(): key = prefix + name if key in state_dict: input_param = state_dict[key] if not torch.overrides.is_tensor_like(input_param): error_msgs.append(f'While copying the parameter named "{key}", ' 'expected torch.Tensor or Tensor-like object from checkpoint but ' f'received {type(input_param)}' ) continue # This is used to avoid copying uninitialized parameters into # non-lazy modules, since they dont have the hook to do the checks # in such case, it will error when accessing the .shape attribute. is_param_lazy = torch.nn.parameter.is_lazy(param) # Backward compatibility: loading 1-dim tensor from 0.3.* to version 0.4+ if not is_param_lazy and len(param.shape) == 0 and len(input_param.shape) == 1: input_param = input_param[0] if not is_param_lazy and input_param.shape != param.shape: # local shape should match the one in checkpoint error_msgs.append('size mismatch for {}: copying a param with shape {} from checkpoint, ' 'the shape in current model is {}.' .format(key, input_param.shape, param.shape)) continue if param.is_meta and not input_param.is_meta and not assign_to_params_buffers: warnings.warn(f'for {key}: copying from a non-meta parameter in the checkpoint to a meta ' 'parameter in the current model, which is a no-op. (Did you mean to ' 'pass `assign=True` to assign items in the state dictionary to their ' 'corresponding key in the module instead of copying them in place?)') try: with torch.no_grad(): if use_swap_tensors: new_input_param = param.module_load(input_param, assign=assign_to_params_buffers) if id(new_input_param) == id(input_param) or id(new_input_param) == id(param): raise RuntimeError("module_load returned one of self or other, please .detach() " "the result if returning one of the inputs in module_load") if (isinstance(param, torch.nn.Parameter)): if not isinstance(new_input_param, torch.nn.Parameter): new_input_param = torch.nn.Parameter(new_input_param, requires_grad=param.requires_grad) else: new_input_param.requires_grad_(param.requires_grad) torch.utils.swap_tensors(param, new_input_param) del new_input_param elif assign_to_params_buffers: # Shape checks are already done above if (isinstance(param, torch.nn.Parameter)): if not isinstance(input_param, torch.nn.Parameter): input_param = torch.nn.Parameter(input_param, requires_grad=param.requires_grad) else: input_param.requires_grad_(param.requires_grad) setattr(self, name, input_param) else: param.copy_(input_param) except Exception as ex: action = "swapping" if use_swap_tensors else "copying" error_msgs.append(f'While {action} the parameter named "{key}", ' f'whose dimensions in the model are {param.size()} and ' f'whose dimensions in the checkpoint are {input_param.size()}, ' f'an exception occurred : {ex.args}.' ) elif strict: missing_keys.append(key) extra_state_key = prefix + _EXTRA_STATE_KEY_SUFFIX if getattr(self.__class__, "set_extra_state", Module.set_extra_state) is not Module.set_extra_state: if extra_state_key in state_dict: self.set_extra_state(state_dict[extra_state_key]) elif strict: missing_keys.append(extra_state_key) elif strict and (extra_state_key in state_dict): unexpected_keys.append(extra_state_key) if strict: for key in state_dict.keys(): if key.startswith(prefix) and key != extra_state_key: input_name = key[len(prefix):] input_name = input_name.split('.', 1)[0] # get the name of param/buffer/child if input_name not in self._modules and input_name not in local_state: unexpected_keys.append(key)
(self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs)
10,022
sentence_transformers.SentenceTransformer
_load_sbert_model
Loads a full sentence-transformers model
def _load_sbert_model( self, model_name_or_path: str, token: Optional[Union[bool, str]], cache_folder: Optional[str], revision: Optional[str] = None, trust_remote_code: bool = False, ): """ Loads a full sentence-transformers model """ # Check if the config_sentence_transformers.json file exists (exists since v2 of the framework) config_sentence_transformers_json_path = load_file_path( model_name_or_path, "config_sentence_transformers.json", token=token, cache_folder=cache_folder, revision=revision, ) if config_sentence_transformers_json_path is not None: with open(config_sentence_transformers_json_path) as fIn: self._model_config = json.load(fIn) if ( "__version__" in self._model_config and "sentence_transformers" in self._model_config["__version__"] and self._model_config["__version__"]["sentence_transformers"] > __version__ ): logger.warning( "You try to use a model that was created with version {}, however, your version is {}. This might cause unexpected behavior or errors. In that case, try to update to the latest version.\n\n\n".format( self._model_config["__version__"]["sentence_transformers"], __version__ ) ) # Set prompts if not already overridden by the __init__ calls if not self.prompts: self.prompts = self._model_config.get("prompts", {}) if not self.default_prompt_name: self.default_prompt_name = self._model_config.get("default_prompt_name", None) # Check if a readme exists model_card_path = load_file_path( model_name_or_path, "README.md", token=token, cache_folder=cache_folder, revision=revision ) if model_card_path is not None: try: with open(model_card_path, encoding="utf8") as fIn: self._model_card_text = fIn.read() except Exception: pass # Load the modules of sentence transformer modules_json_path = load_file_path( model_name_or_path, "modules.json", token=token, cache_folder=cache_folder, revision=revision ) with open(modules_json_path) as fIn: modules_config = json.load(fIn) modules = OrderedDict() for module_config in modules_config: module_class = import_from_string(module_config["type"]) # For Transformer, don't load the full directory, rely on `transformers` instead # But, do load the config file first. if module_class == Transformer and module_config["path"] == "": kwargs = {} for config_name in [ "sentence_bert_config.json", "sentence_roberta_config.json", "sentence_distilbert_config.json", "sentence_camembert_config.json", "sentence_albert_config.json", "sentence_xlm-roberta_config.json", "sentence_xlnet_config.json", ]: config_path = load_file_path( model_name_or_path, config_name, token=token, cache_folder=cache_folder, revision=revision ) if config_path is not None: with open(config_path) as fIn: kwargs = json.load(fIn) break hub_kwargs = {"token": token, "trust_remote_code": trust_remote_code, "revision": revision} if "model_args" in kwargs: kwargs["model_args"].update(hub_kwargs) else: kwargs["model_args"] = hub_kwargs if "tokenizer_args" in kwargs: kwargs["tokenizer_args"].update(hub_kwargs) else: kwargs["tokenizer_args"] = hub_kwargs module = Transformer(model_name_or_path, cache_dir=cache_folder, **kwargs) else: # Normalize does not require any files to be loaded if module_class == Normalize: module_path = None else: module_path = load_dir_path( model_name_or_path, module_config["path"], token=token, cache_folder=cache_folder, revision=revision, ) module = module_class.load(module_path) modules[module_config["name"]] = module return modules
(self, model_name_or_path: str, token: Union[bool, str, NoneType], cache_folder: Optional[str], revision: Optional[str] = None, trust_remote_code: bool = False)
10,023
torch.nn.modules.module
_maybe_warn_non_full_backward_hook
null
def _maybe_warn_non_full_backward_hook(self, inputs, result, grad_fn): if not isinstance(result, torch.Tensor): if not (isinstance(result, tuple) and all(isinstance(r, torch.Tensor) for r in result)): warnings.warn("Using non-full backward hooks on a Module that does not return a " "single Tensor or a tuple of Tensors is deprecated and will be removed " "in future versions. This hook will be missing some of the grad_output. " "Please use register_full_backward_hook to get the documented behavior.") return else: result = (result,) if not isinstance(inputs, torch.Tensor): if not (isinstance(inputs, tuple) and all(isinstance(i, torch.Tensor) for i in inputs)): warnings.warn("Using non-full backward hooks on a Module that does not take as input a " "single Tensor or a tuple of Tensors is deprecated and will be removed " "in future versions. This hook will be missing some of the grad_input. " "Please use register_full_backward_hook to get the documented behavior.") return else: inputs = (inputs,) # At this point we are sure that inputs and result are tuple of Tensors out_grad_fn = {r.grad_fn for r in result if r.grad_fn is not None} if len(out_grad_fn) == 0 or (len(out_grad_fn) == 1 and grad_fn not in out_grad_fn): warnings.warn("Using a non-full backward hook when outputs are nested in python data structure " "is deprecated and will be removed in future versions. This hook will be missing " "some grad_output.") elif len(out_grad_fn) > 1: warnings.warn("Using a non-full backward hook when outputs are generated by different autograd Nodes " "is deprecated and will be removed in future versions. This hook will be missing " "some grad_output. Please use register_full_backward_hook to get the documented behavior.") else: # At this point the grad_output part of the hook will most likely be correct inputs_grad_fn = {i.grad_fn for i in inputs if i.grad_fn is not None} next_functions = {n[0] for n in grad_fn.next_functions} if inputs_grad_fn != next_functions: warnings.warn("Using a non-full backward hook when the forward contains multiple autograd Nodes " "is deprecated and will be removed in future versions. This hook will be missing " "some grad_input. Please use register_full_backward_hook to get the documented " "behavior.")
(self, inputs, result, grad_fn)
10,024
torch.nn.modules.module
_named_members
Help yield various names + members of modules.
def _named_members(self, get_members_fn, prefix='', recurse=True, remove_duplicate: bool = True): r"""Help yield various names + members of modules.""" memo = set() modules = self.named_modules(prefix=prefix, remove_duplicate=remove_duplicate) if recurse else [(prefix, self)] for module_prefix, module in modules: members = get_members_fn(module) for k, v in members: if v is None or v in memo: continue if remove_duplicate: memo.add(v) name = module_prefix + ('.' if module_prefix else '') + k yield name, v
(self, get_members_fn, prefix='', recurse=True, remove_duplicate: bool = True)
10,025
torch.nn.modules.module
_register_load_state_dict_pre_hook
Register a pre-hook for the :meth:`~torch.nn.Module.load_state_dict` method. These hooks will be called with arguments: `state_dict`, `prefix`, `local_metadata`, `strict`, `missing_keys`, `unexpected_keys`, `error_msgs`, before loading `state_dict` into `self`. These arguments are exactly the same as those of `_load_from_state_dict`. If ``with_module`` is ``True``, then the first argument to the hook is an instance of the module. Arguments: hook (Callable): Callable hook that will be invoked before loading the state dict. with_module (bool, optional): Whether or not to pass the module instance to the hook as the first parameter.
def _register_load_state_dict_pre_hook(self, hook, with_module=False): r"""Register a pre-hook for the :meth:`~torch.nn.Module.load_state_dict` method. These hooks will be called with arguments: `state_dict`, `prefix`, `local_metadata`, `strict`, `missing_keys`, `unexpected_keys`, `error_msgs`, before loading `state_dict` into `self`. These arguments are exactly the same as those of `_load_from_state_dict`. If ``with_module`` is ``True``, then the first argument to the hook is an instance of the module. Arguments: hook (Callable): Callable hook that will be invoked before loading the state dict. with_module (bool, optional): Whether or not to pass the module instance to the hook as the first parameter. """ handle = hooks.RemovableHandle(self._load_state_dict_pre_hooks) self._load_state_dict_pre_hooks[handle.id] = _WrappedHook(hook, self if with_module else None) return handle
(self, hook, with_module=False)
10,026
torch.nn.modules.module
_register_state_dict_hook
Register a state-dict hook. These hooks will be called with arguments: `self`, `state_dict`, `prefix`, `local_metadata`, after the `state_dict` of `self` is set. Note that only parameters and buffers of `self` or its children are guaranteed to exist in `state_dict`. The hooks may modify `state_dict` inplace or return a new one.
def _register_state_dict_hook(self, hook): r"""Register a state-dict hook. These hooks will be called with arguments: `self`, `state_dict`, `prefix`, `local_metadata`, after the `state_dict` of `self` is set. Note that only parameters and buffers of `self` or its children are guaranteed to exist in `state_dict`. The hooks may modify `state_dict` inplace or return a new one. """ handle = hooks.RemovableHandle(self._state_dict_hooks) self._state_dict_hooks[handle.id] = hook return handle
(self, hook)
10,027
torch.nn.modules.module
_replicate_for_data_parallel
null
def _replicate_for_data_parallel(self): replica = self.__new__(type(self)) replica.__dict__ = self.__dict__.copy() # replicas do not have parameters themselves, the replicas reference the original # module. replica._parameters = OrderedDict() replica._buffers = replica._buffers.copy() replica._modules = replica._modules.copy() replica._is_replica = True # type: ignore[assignment] return replica
(self)
10,028
sentence_transformers.SentenceTransformer
_save_checkpoint
null
def _save_checkpoint(self, checkpoint_path, checkpoint_save_total_limit, step): # Store new checkpoint self.save(os.path.join(checkpoint_path, str(step))) # Delete old checkpoints if checkpoint_save_total_limit is not None and checkpoint_save_total_limit > 0: old_checkpoints = [] for subdir in os.listdir(checkpoint_path): if subdir.isdigit(): old_checkpoints.append({"step": int(subdir), "path": os.path.join(checkpoint_path, subdir)}) if len(old_checkpoints) > checkpoint_save_total_limit: old_checkpoints = sorted(old_checkpoints, key=lambda x: x["step"]) shutil.rmtree(old_checkpoints[0]["path"])
(self, checkpoint_path, checkpoint_save_total_limit, step)
10,029
torch.nn.modules.module
_save_to_state_dict
Save module state to the `destination` dictionary. The `destination` dictionary will contain the state of the module, but not its descendants. This is called on every submodule in :meth:`~torch.nn.Module.state_dict`. In rare cases, subclasses can achieve class-specific behavior by overriding this method with custom logic. Args: destination (dict): a dict where state will be stored prefix (str): the prefix for parameters and buffers used in this module
def _save_to_state_dict(self, destination, prefix, keep_vars): r"""Save module state to the `destination` dictionary. The `destination` dictionary will contain the state of the module, but not its descendants. This is called on every submodule in :meth:`~torch.nn.Module.state_dict`. In rare cases, subclasses can achieve class-specific behavior by overriding this method with custom logic. Args: destination (dict): a dict where state will be stored prefix (str): the prefix for parameters and buffers used in this module """ for name, param in self._parameters.items(): if param is not None: destination[prefix + name] = param if keep_vars else param.detach() for name, buf in self._buffers.items(): if buf is not None and name not in self._non_persistent_buffers_set: destination[prefix + name] = buf if keep_vars else buf.detach() extra_state_key = prefix + _EXTRA_STATE_KEY_SUFFIX if getattr(self.__class__, "get_extra_state", Module.get_extra_state) is not Module.get_extra_state: destination[extra_state_key] = self.get_extra_state()
(self, destination, prefix, keep_vars)
10,030
torch.nn.modules.module
_slow_forward
null
def _slow_forward(self, *input, **kwargs): tracing_state = torch._C._get_tracing_state() if not tracing_state or isinstance(self.forward, torch._C.ScriptMethod): return self.forward(*input, **kwargs) recording_scopes = torch.jit._trace._trace_module_map is not None if recording_scopes: # type ignore was added because at this point one knows that # torch.jit._trace._trace_module_map is not Optional and has type Dict[Any, Any] name = torch.jit._trace._trace_module_map[self] if self in torch.jit._trace._trace_module_map else None # type: ignore[index, operator] # noqa: B950 if name: tracing_state.push_scope(name) else: recording_scopes = False try: result = self.forward(*input, **kwargs) finally: if recording_scopes: tracing_state.pop_scope() return result
(self, *input, **kwargs)
10,031
sentence_transformers.SentenceTransformer
_text_length
Help function to get the length for the input text. Text can be either a list of ints (which means a single text as input), or a tuple of list of ints (representing several text inputs to the model).
def _text_length(self, text: Union[List[int], List[List[int]]]): """ Help function to get the length for the input text. Text can be either a list of ints (which means a single text as input), or a tuple of list of ints (representing several text inputs to the model). """ if isinstance(text, dict): # {key: value} case return len(next(iter(text.values()))) elif not hasattr(text, "__len__"): # Object has no len() method return 1 elif len(text) == 0 or isinstance(text[0], int): # Empty string or list of ints return len(text) else: return sum([len(t) for t in text]) # Sum of length of individual strings
(self, text: Union[List[int], List[List[int]]])
10,033
torch.nn.modules.module
add_module
Add a child module to the current module. The module can be accessed as an attribute using the given name. Args: name (str): name of the child module. The child module can be accessed from this module using the given name module (Module): child module to be added to the module.
def add_module(self, name: str, module: Optional['Module']) -> None: r"""Add a child module to the current module. The module can be accessed as an attribute using the given name. Args: name (str): name of the child module. The child module can be accessed from this module using the given name module (Module): child module to be added to the module. """ if not isinstance(module, Module) and module is not None: raise TypeError(f"{torch.typename(module)} is not a Module subclass") elif not isinstance(name, str): raise TypeError(f"module name should be a string. Got {torch.typename(name)}") elif hasattr(self, name) and name not in self._modules: raise KeyError(f"attribute '{name}' already exists") elif '.' in name: raise KeyError(f"module name can't contain \".\", got: {name}") elif name == '': raise KeyError("module name can't be empty string \"\"") for hook in _global_module_registration_hooks.values(): output = hook(self, name, module) if output is not None: module = output self._modules[name] = module
(self, name: str, module: Optional[torch.nn.modules.module.Module]) -> NoneType
10,034
torch.nn.modules.container
append
Append a given module to the end. Args: module (nn.Module): module to append
def append(self, module: Module) -> 'Sequential': r"""Append a given module to the end. Args: module (nn.Module): module to append """ self.add_module(str(len(self)), module) return self
(self, module: torch.nn.modules.module.Module) -> torch.nn.modules.container.Sequential
10,035
torch.nn.modules.module
apply
Apply ``fn`` recursively to every submodule (as returned by ``.children()``) as well as self. Typical use includes initializing the parameters of a model (see also :ref:`nn-init-doc`). Args: fn (:class:`Module` -> None): function to be applied to each submodule Returns: Module: self Example:: >>> @torch.no_grad() >>> def init_weights(m): >>> print(m) >>> if type(m) == nn.Linear: >>> m.weight.fill_(1.0) >>> print(m.weight) >>> net = nn.Sequential(nn.Linear(2, 2), nn.Linear(2, 2)) >>> net.apply(init_weights) Linear(in_features=2, out_features=2, bias=True) Parameter containing: tensor([[1., 1.], [1., 1.]], requires_grad=True) Linear(in_features=2, out_features=2, bias=True) Parameter containing: tensor([[1., 1.], [1., 1.]], requires_grad=True) Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) )
def apply(self: T, fn: Callable[['Module'], None]) -> T: r"""Apply ``fn`` recursively to every submodule (as returned by ``.children()``) as well as self. Typical use includes initializing the parameters of a model (see also :ref:`nn-init-doc`). Args: fn (:class:`Module` -> None): function to be applied to each submodule Returns: Module: self Example:: >>> @torch.no_grad() >>> def init_weights(m): >>> print(m) >>> if type(m) == nn.Linear: >>> m.weight.fill_(1.0) >>> print(m.weight) >>> net = nn.Sequential(nn.Linear(2, 2), nn.Linear(2, 2)) >>> net.apply(init_weights) Linear(in_features=2, out_features=2, bias=True) Parameter containing: tensor([[1., 1.], [1., 1.]], requires_grad=True) Linear(in_features=2, out_features=2, bias=True) Parameter containing: tensor([[1., 1.], [1., 1.]], requires_grad=True) Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) ) """ for module in self.children(): module.apply(fn) fn(self) return self
(self: ~T, fn: Callable[[torch.nn.modules.module.Module], NoneType]) -> ~T
10,036
torch.nn.modules.module
bfloat16
Casts all floating point parameters and buffers to ``bfloat16`` datatype. .. note:: This method modifies the module in-place. Returns: Module: self
def bfloat16(self: T) -> T: r"""Casts all floating point parameters and buffers to ``bfloat16`` datatype. .. note:: This method modifies the module in-place. Returns: Module: self """ return self._apply(lambda t: t.bfloat16() if t.is_floating_point() else t)
(self: ~T) -> ~T
10,037
torch.nn.modules.module
buffers
Return an iterator over module buffers. Args: recurse (bool): if True, then yields buffers of this module and all submodules. Otherwise, yields only buffers that are direct members of this module. Yields: torch.Tensor: module buffer Example:: >>> # xdoctest: +SKIP("undefined vars") >>> for buf in model.buffers(): >>> print(type(buf), buf.size()) <class 'torch.Tensor'> (20L,) <class 'torch.Tensor'> (20L, 1L, 5L, 5L)
def buffers(self, recurse: bool = True) -> Iterator[Tensor]: r"""Return an iterator over module buffers. Args: recurse (bool): if True, then yields buffers of this module and all submodules. Otherwise, yields only buffers that are direct members of this module. Yields: torch.Tensor: module buffer Example:: >>> # xdoctest: +SKIP("undefined vars") >>> for buf in model.buffers(): >>> print(type(buf), buf.size()) <class 'torch.Tensor'> (20L,) <class 'torch.Tensor'> (20L, 1L, 5L, 5L) """ for _, buf in self.named_buffers(recurse=recurse): yield buf
(self, recurse: bool = True) -> Iterator[torch.Tensor]
10,038
torch.nn.modules.module
children
Return an iterator over immediate children modules. Yields: Module: a child module
def children(self) -> Iterator['Module']: r"""Return an iterator over immediate children modules. Yields: Module: a child module """ for name, module in self.named_children(): yield module
(self) -> Iterator[torch.nn.modules.module.Module]
10,039
torch.nn.modules.module
compile
Compile this Module's forward using :func:`torch.compile`. This Module's `__call__` method is compiled and all arguments are passed as-is to :func:`torch.compile`. See :func:`torch.compile` for details on the arguments for this function.
def compile(self, *args, **kwargs): """ Compile this Module's forward using :func:`torch.compile`. This Module's `__call__` method is compiled and all arguments are passed as-is to :func:`torch.compile`. See :func:`torch.compile` for details on the arguments for this function. """ self._compiled_call_impl = torch.compile(self._call_impl, *args, **kwargs)
(self, *args, **kwargs)
10,040
torch.nn.modules.module
cpu
Move all model parameters and buffers to the CPU. .. note:: This method modifies the module in-place. Returns: Module: self
def cpu(self: T) -> T: r"""Move all model parameters and buffers to the CPU. .. note:: This method modifies the module in-place. Returns: Module: self """ return self._apply(lambda t: t.cpu())
(self: ~T) -> ~T
10,041
torch.nn.modules.module
cuda
Move all model parameters and buffers to the GPU. This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on GPU while being optimized. .. note:: This method modifies the module in-place. Args: device (int, optional): if specified, all parameters will be copied to that device Returns: Module: self
def cuda(self: T, device: Optional[Union[int, device]] = None) -> T: r"""Move all model parameters and buffers to the GPU. This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on GPU while being optimized. .. note:: This method modifies the module in-place. Args: device (int, optional): if specified, all parameters will be copied to that device Returns: Module: self """ return self._apply(lambda t: t.cuda(device))
(self: ~T, device: Union[int, torch.device, NoneType] = None) -> ~T
10,042
torch.nn.modules.module
double
Casts all floating point parameters and buffers to ``double`` datatype. .. note:: This method modifies the module in-place. Returns: Module: self
def double(self: T) -> T: r"""Casts all floating point parameters and buffers to ``double`` datatype. .. note:: This method modifies the module in-place. Returns: Module: self """ return self._apply(lambda t: t.double() if t.is_floating_point() else t)
(self: ~T) -> ~T
10,043
sentence_transformers.SentenceTransformer
encode
Computes sentence embeddings. :param sentences: the sentences to embed. :param prompt_name: The name of the prompt to use for encoding. Must be a key in the `prompts` dictionary, which is either set in the constructor or loaded from the model configuration. For example if `prompt_name` is ``"query"`` and the `prompts` is ``{"query": "query: ", ...}``, then the sentence "What is the capital of France?" will be encoded as "query: What is the capital of France?" because the sentence is appended to the prompt. If `prompt` is also set, this argument is ignored. :param prompt: The prompt to use for encoding. For example, if the prompt is ``"query: "``, then the sentence "What is the capital of France?" will be encoded as "query: What is the capital of France?" because the sentence is appended to the prompt. If `prompt` is set, `prompt_name` is ignored. :param batch_size: the batch size used for the computation. :param show_progress_bar: Whether to output a progress bar when encode sentences. :param output_value: The type of embeddings to return: "sentence_embedding" to get sentence embeddings, "token_embeddings" to get wordpiece token embeddings, and `None`, to get all output values. Defaults to "sentence_embedding". :param precision: The precision to use for the embeddings. Can be "float32", "int8", "uint8", "binary", or "ubinary". All non-float32 precisions are quantized embeddings. Quantized embeddings are smaller in size and faster to compute, but may have a lower accuracy. They are useful for reducing the size of the embeddings of a corpus for semantic search, among other tasks. Defaults to "float32". :param convert_to_numpy: Whether the output should be a list of numpy vectors. If False, it is a list of PyTorch tensors. :param convert_to_tensor: Whether the output should be one large tensor. Overwrites `convert_to_numpy`. :param device: Which `torch.device` to use for the computation. :param normalize_embeddings: Whether to normalize returned vectors to have length 1. In that case, the faster dot-product (util.dot_score) instead of cosine similarity can be used. :return: By default, a 2d numpy array with shape [num_inputs, output_dimension] is returned. If only one string input is provided, then the output is a 1d array with shape [output_dimension]. If `convert_to_tensor`, a torch Tensor is returned instead. If `self.truncate_dim <= output_dimension` then output_dimension is `self.truncate_dim`.
def encode( self, sentences: Union[str, List[str]], prompt_name: Optional[str] = None, prompt: Optional[str] = None, batch_size: int = 32, show_progress_bar: bool = None, output_value: Optional[Literal["sentence_embedding", "token_embeddings"]] = "sentence_embedding", precision: Literal["float32", "int8", "uint8", "binary", "ubinary"] = "float32", convert_to_numpy: bool = True, convert_to_tensor: bool = False, device: str = None, normalize_embeddings: bool = False, ) -> Union[List[Tensor], ndarray, Tensor]: """ Computes sentence embeddings. :param sentences: the sentences to embed. :param prompt_name: The name of the prompt to use for encoding. Must be a key in the `prompts` dictionary, which is either set in the constructor or loaded from the model configuration. For example if `prompt_name` is ``"query"`` and the `prompts` is ``{"query": "query: ", ...}``, then the sentence "What is the capital of France?" will be encoded as "query: What is the capital of France?" because the sentence is appended to the prompt. If `prompt` is also set, this argument is ignored. :param prompt: The prompt to use for encoding. For example, if the prompt is ``"query: "``, then the sentence "What is the capital of France?" will be encoded as "query: What is the capital of France?" because the sentence is appended to the prompt. If `prompt` is set, `prompt_name` is ignored. :param batch_size: the batch size used for the computation. :param show_progress_bar: Whether to output a progress bar when encode sentences. :param output_value: The type of embeddings to return: "sentence_embedding" to get sentence embeddings, "token_embeddings" to get wordpiece token embeddings, and `None`, to get all output values. Defaults to "sentence_embedding". :param precision: The precision to use for the embeddings. Can be "float32", "int8", "uint8", "binary", or "ubinary". All non-float32 precisions are quantized embeddings. Quantized embeddings are smaller in size and faster to compute, but may have a lower accuracy. They are useful for reducing the size of the embeddings of a corpus for semantic search, among other tasks. Defaults to "float32". :param convert_to_numpy: Whether the output should be a list of numpy vectors. If False, it is a list of PyTorch tensors. :param convert_to_tensor: Whether the output should be one large tensor. Overwrites `convert_to_numpy`. :param device: Which `torch.device` to use for the computation. :param normalize_embeddings: Whether to normalize returned vectors to have length 1. In that case, the faster dot-product (util.dot_score) instead of cosine similarity can be used. :return: By default, a 2d numpy array with shape [num_inputs, output_dimension] is returned. If only one string input is provided, then the output is a 1d array with shape [output_dimension]. If `convert_to_tensor`, a torch Tensor is returned instead. If `self.truncate_dim <= output_dimension` then output_dimension is `self.truncate_dim`. """ if self.device.type == "hpu" and not self.is_hpu_graph_enabled: import habana_frameworks.torch as ht ht.hpu.wrap_in_hpu_graph(self, disable_tensor_cache=True) self.is_hpu_graph_enabled = True self.eval() if show_progress_bar is None: show_progress_bar = ( logger.getEffectiveLevel() == logging.INFO or logger.getEffectiveLevel() == logging.DEBUG ) if convert_to_tensor: convert_to_numpy = False if output_value != "sentence_embedding": convert_to_tensor = False convert_to_numpy = False input_was_string = False if isinstance(sentences, str) or not hasattr( sentences, "__len__" ): # Cast an individual sentence to a list with length 1 sentences = [sentences] input_was_string = True if prompt is None: if prompt_name is not None: try: prompt = self.prompts[prompt_name] except KeyError: raise ValueError( f"Prompt name '{prompt_name}' not found in the configured prompts dictionary with keys {list(self.prompts.keys())!r}." ) elif self.default_prompt_name is not None: prompt = self.prompts.get(self.default_prompt_name, None) else: if prompt_name is not None: logger.warning( "Encode with either a `prompt`, a `prompt_name`, or neither, but not both. " "Ignoring the `prompt_name` in favor of `prompt`." ) extra_features = {} if prompt is not None: sentences = [prompt + sentence for sentence in sentences] # Some models (e.g. INSTRUCTOR, GRIT) require removing the prompt before pooling # Tracking the prompt length allow us to remove the prompt during pooling tokenized_prompt = self.tokenize([prompt]) if "input_ids" in tokenized_prompt: extra_features["prompt_length"] = tokenized_prompt["input_ids"].shape[-1] - 1 if device is None: device = self.device self.to(device) all_embeddings = [] length_sorted_idx = np.argsort([-self._text_length(sen) for sen in sentences]) sentences_sorted = [sentences[idx] for idx in length_sorted_idx] 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] features = self.tokenize(sentences_batch) features = batch_to_device(features, device) features.update(extra_features) with torch.no_grad(): out_features = self.forward(features) out_features["sentence_embedding"] = truncate_embeddings( out_features["sentence_embedding"], self.truncate_dim ) if output_value == "token_embeddings": embeddings = [] for token_emb, attention in zip(out_features[output_value], out_features["attention_mask"]): last_mask_id = len(attention) - 1 while last_mask_id > 0 and attention[last_mask_id].item() == 0: last_mask_id -= 1 embeddings.append(token_emb[0 : last_mask_id + 1]) elif output_value is None: # Return all outputs embeddings = [] for sent_idx in range(len(out_features["sentence_embedding"])): row = {name: out_features[name][sent_idx] for name in out_features} embeddings.append(row) else: # Sentence embeddings embeddings = out_features[output_value] embeddings = embeddings.detach() if normalize_embeddings: embeddings = torch.nn.functional.normalize(embeddings, p=2, dim=1) # fixes for #522 and #487 to avoid oom problems on gpu with large datasets if convert_to_numpy: embeddings = embeddings.cpu() all_embeddings.extend(embeddings) all_embeddings = [all_embeddings[idx] for idx in np.argsort(length_sorted_idx)] if precision and precision != "float32": all_embeddings = quantize_embeddings(all_embeddings, precision=precision) if convert_to_tensor: if len(all_embeddings): if isinstance(all_embeddings, np.ndarray): all_embeddings = torch.from_numpy(all_embeddings) else: all_embeddings = torch.stack(all_embeddings) else: all_embeddings = torch.Tensor() elif convert_to_numpy: if not isinstance(all_embeddings, np.ndarray): all_embeddings = np.asarray([emb.numpy() for emb in all_embeddings]) elif isinstance(all_embeddings, np.ndarray): all_embeddings = [torch.from_numpy(embedding) for embedding in all_embeddings] if input_was_string: all_embeddings = all_embeddings[0] return all_embeddings
(self, sentences: Union[str, List[str]], prompt_name: Optional[str] = None, prompt: Optional[str] = None, batch_size: int = 32, show_progress_bar: Optional[bool] = None, output_value: Optional[Literal['sentence_embedding', 'token_embeddings']] = 'sentence_embedding', precision: Literal['float32', 'int8', 'uint8', 'binary', 'ubinary'] = 'float32', convert_to_numpy: bool = True, convert_to_tensor: bool = False, device: Optional[str] = None, normalize_embeddings: bool = False) -> Union[List[torch.Tensor], numpy.ndarray, torch.Tensor]