code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def MetersToTile( self, mx, my, zoom, ): '''Returns tile for given mercator coordinates''' (px, py) = self.MetersToPixels(mx, my, zoom) return self.PixelsToTile(px, py)
Returns tile for given mercator coordinates
MetersToTile
python
commenthol/gdal2tiles-leaflet
gdal2tiles-multiprocess.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles-multiprocess.py
MIT
def TileBounds( self, tx, ty, zoom, ): '''Returns bounds of the given tile in EPSG:900913 coordinates''' (minx, miny) = self.PixelsToMeters(tx * self.tileSize, ty * self.tileSize, zoom) (maxx, maxy) = self.PixelsToMeters((tx + 1) * self.ti...
Returns bounds of the given tile in EPSG:900913 coordinates
TileBounds
python
commenthol/gdal2tiles-leaflet
gdal2tiles-multiprocess.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles-multiprocess.py
MIT
def TileLatLonBounds( self, tx, ty, zoom, ): '''Returns bounds of the given tile in latutude/longitude using WGS84 datum''' bounds = self.TileBounds(tx, ty, zoom) (minLat, minLon) = self.MetersToLatLon(bounds[0], bounds[1]) (maxLat, maxLon) = self...
Returns bounds of the given tile in latutude/longitude using WGS84 datum
TileLatLonBounds
python
commenthol/gdal2tiles-leaflet
gdal2tiles-multiprocess.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles-multiprocess.py
MIT
def Resolution(self, zoom): '''Resolution (meters/pixel) for given zoom level (measured at Equator)''' # return (2 * math.pi * 6378137) / (self.tileSize * 2**zoom) return self.initialResolution / 2 ** zoom
Resolution (meters/pixel) for given zoom level (measured at Equator)
Resolution
python
commenthol/gdal2tiles-leaflet
gdal2tiles-multiprocess.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles-multiprocess.py
MIT
def ZoomForPixelSize(self, pixelSize): '''Maximal scaledown zoom of the pyramid closest to the pixelSize.''' for i in range(MAXZOOMLEVEL): if pixelSize > self.Resolution(i): if i != 0: return i - 1 else: return 0 # We ...
Maximal scaledown zoom of the pyramid closest to the pixelSize.
ZoomForPixelSize
python
commenthol/gdal2tiles-leaflet
gdal2tiles-multiprocess.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles-multiprocess.py
MIT
def GoogleTile( self, tx, ty, zoom, ): '''Converts TMS tile coordinates to Google Tile coordinates''' # coordinate origin is moved from bottom-left to top-left corner of the extent return (tx, 2 ** zoom - 1 - ty)
Converts TMS tile coordinates to Google Tile coordinates
GoogleTile
python
commenthol/gdal2tiles-leaflet
gdal2tiles-multiprocess.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles-multiprocess.py
MIT
def QuadTree( self, tx, ty, zoom, ): '''Converts TMS tile coordinates to Microsoft QuadTree''' quadKey = '' ty = 2 ** zoom - 1 - ty for i in range(zoom, 0, -1): digit = 0 mask = 1 << i - 1 if tx & mask != 0: ...
Converts TMS tile coordinates to Microsoft QuadTree
QuadTree
python
commenthol/gdal2tiles-leaflet
gdal2tiles-multiprocess.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles-multiprocess.py
MIT
def LonLatToPixels( self, lon, lat, zoom, ): '''Converts lon/lat to pixel coordinates in given zoom of the EPSG:4326 pyramid''' res = self.resFact / 2 ** zoom px = (180 + lon) / res py = (90 + lat) / res return (px, py)
Converts lon/lat to pixel coordinates in given zoom of the EPSG:4326 pyramid
LonLatToPixels
python
commenthol/gdal2tiles-leaflet
gdal2tiles-multiprocess.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles-multiprocess.py
MIT
def PixelsToTile(self, px, py): '''Returns coordinates of the tile covering region in pixel coordinates''' tx = int(math.ceil(px / float(self.tileSize)) - 1) ty = int(math.ceil(py / float(self.tileSize)) - 1) return (tx, ty)
Returns coordinates of the tile covering region in pixel coordinates
PixelsToTile
python
commenthol/gdal2tiles-leaflet
gdal2tiles-multiprocess.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles-multiprocess.py
MIT
def LonLatToTile( self, lon, lat, zoom, ): '''Returns the tile for zoom which covers given lon/lat coordinates''' (px, py) = self.LonLatToPixels(lon, lat, zoom) return self.PixelsToTile(px, py)
Returns the tile for zoom which covers given lon/lat coordinates
LonLatToTile
python
commenthol/gdal2tiles-leaflet
gdal2tiles-multiprocess.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles-multiprocess.py
MIT
def Resolution(self, zoom): '''Resolution (arc/pixel) for given zoom level (measured at Equator)''' return self.resFact / 2 ** zoom # return 180 / float( 1 << (8+zoom) )
Resolution (arc/pixel) for given zoom level (measured at Equator)
Resolution
python
commenthol/gdal2tiles-leaflet
gdal2tiles-multiprocess.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles-multiprocess.py
MIT
def TileBounds( self, tx, ty, zoom, ): '''Returns bounds of the given tile''' res = self.resFact / 2 ** zoom return (tx * self.tileSize * res - 180, ty * self.tileSize * res - 90, (tx + 1) * self.tileSize * res - 180, (ty +...
Returns bounds of the given tile
TileBounds
python
commenthol/gdal2tiles-leaflet
gdal2tiles-multiprocess.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles-multiprocess.py
MIT
def TileLatLonBounds( self, tx, ty, zoom, ): '''Returns bounds of the given tile in the SWNE form''' b = self.TileBounds(tx, ty, zoom) return (b[1], b[0], b[3], b[2])
Returns bounds of the given tile in the SWNE form
TileLatLonBounds
python
commenthol/gdal2tiles-leaflet
gdal2tiles-multiprocess.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles-multiprocess.py
MIT
def __init__( self, width, height, tilesize=256, tileformat='jpg', ): """Initialization of the Zoomify tile tree""" self.tilesize = tilesize self.tileformat = tileformat imagesize = (width, height) tiles = (math.ceil(width / tilesi...
Initialization of the Zoomify tile tree
__init__
python
commenthol/gdal2tiles-leaflet
gdal2tiles-multiprocess.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles-multiprocess.py
MIT
def tilefilename( self, x, y, z, ): """Returns filename for tile with given coordinates""" tileIndex = x + y * self.tierSizeInTiles[z][0] \ + self.tileCountUpToTier[z] return os.path.join('TileGroup%.0f' % math.floor(tileIndex ...
Returns filename for tile with given coordinates
tilefilename
python
commenthol/gdal2tiles-leaflet
gdal2tiles-multiprocess.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles-multiprocess.py
MIT
def process(self): """The main processing function, runs all the main steps of processing""" # Opening and preprocessing of the input file self.open_input() # Generation of main metadata files and HTML viewers self.generate_metadata() # Generation of the lowest tiles...
The main processing function, runs all the main steps of processing
process
python
commenthol/gdal2tiles-leaflet
gdal2tiles-multiprocess.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles-multiprocess.py
MIT
def error(self, msg, details=''): """Print an error message and stop the processing""" if details: self.parser.error(msg + ''' ''' + details) else: self.parser.error(msg)
Print an error message and stop the processing
error
python
commenthol/gdal2tiles-leaflet
gdal2tiles-multiprocess.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles-multiprocess.py
MIT
def optparse_init(self): """Prepare the option parser for input (argv)""" from optparse import OptionParser, OptionGroup usage = 'Usage: %prog [options] input_file(s) [output]' p = OptionParser(usage, version='%prog ' + __version__) p.add_option( '-p', '-...
Prepare the option parser for input (argv)
optparse_init
python
commenthol/gdal2tiles-leaflet
gdal2tiles-multiprocess.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles-multiprocess.py
MIT
def open_input(self): """Initialization of the input raster, reprojection if necessary""" gdal.UseExceptions() gdal.AllRegister() if not self.options.verbose: gdal.PushErrorHandler('CPLQuietErrorHandler') # Initialize necessary GDAL drivers self.out_drv = g...
Initialization of the input raster, reprojection if necessary
open_input
python
commenthol/gdal2tiles-leaflet
gdal2tiles-multiprocess.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles-multiprocess.py
MIT
def generate_metadata(self): """Generation of main metadata files and HTML viewers (metadata related to particular tiles are generated during the tile processing).""" if not os.path.exists(self.output): os.makedirs(self.output) if self.options.profile == 'mercator': (s...
Generation of main metadata files and HTML viewers (metadata related to particular tiles are generated during the tile processing).
generate_metadata
python
commenthol/gdal2tiles-leaflet
gdal2tiles-multiprocess.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles-multiprocess.py
MIT
def generate_base_tiles(self, cpu): """Generation of the base tiles (the lowest in the pyramid) directly from the input raster""" if self.options.verbose: # mx, my = self.out_gt[0], self.out_gt[3] # OriginX, OriginY # px, py = self.mercator.MetersToPixels( mx, my, self.tmaxz) ...
Generation of the base tiles (the lowest in the pyramid) directly from the input raster
generate_base_tiles
python
commenthol/gdal2tiles-leaflet
gdal2tiles-multiprocess.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles-multiprocess.py
MIT
def generate_overview_tiles(self, cpu, tz): """Generation of the overview tiles (higher in the pyramid) based on existing tiles""" tilebands = self.dataBandsCount + 1 # Usage of existing tiles: from 4 underlying tiles generate one as overview. tcount = 0 for z in range(self.tm...
Generation of the overview tiles (higher in the pyramid) based on existing tiles
generate_overview_tiles
python
commenthol/gdal2tiles-leaflet
gdal2tiles-multiprocess.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles-multiprocess.py
MIT
def geo_query( self, ds, ulx, uly, lrx, lry, querysize=0, ): """For given dataset and query in cartographic coordinates returns parameters for ReadRaster() in raster coordinates and x/y shifts (for border tiles). If the querysize is...
For given dataset and query in cartographic coordinates returns parameters for ReadRaster() in raster coordinates and x/y shifts (for border tiles). If the querysize is not given, the extent is returned in the native resolution of dataset ds.
geo_query
python
commenthol/gdal2tiles-leaflet
gdal2tiles-multiprocess.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles-multiprocess.py
MIT
def scale_query_to_tile( self, dsquery, dstile, tilefilename='', ): """Scales down query dataset to the tile dataset""" querysize = dsquery.RasterXSize tilesize = dstile.RasterXSize tilebands = dstile.RasterCount if self.options.resamplin...
Scales down query dataset to the tile dataset
scale_query_to_tile
python
commenthol/gdal2tiles-leaflet
gdal2tiles-multiprocess.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles-multiprocess.py
MIT
def generate_tilemapresource(self): """ Template for tilemapresource.xml. Returns filled string. Expected variables: title, north, south, east, west, isepsg4326, projection, publishurl, zoompixels, tilesize, tileformat, profile """ args = {} args['title'] = s...
Template for tilemapresource.xml. Returns filled string. Expected variables: title, north, south, east, west, isepsg4326, projection, publishurl, zoompixels, tilesize, tileformat, profile
generate_tilemapresource
python
commenthol/gdal2tiles-leaflet
gdal2tiles-multiprocess.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles-multiprocess.py
MIT
def generate_kml( self, tx, ty, tz, children=[], **args ): """ Template for the KML. Returns filled string. """ (args['tx'], args['ty'], args['tz']) = (tx, ty, tz) args['tileformat'] = self.tileext if 'tilesize' not...
Template for the KML. Returns filled string.
generate_kml
python
commenthol/gdal2tiles-leaflet
gdal2tiles-multiprocess.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles-multiprocess.py
MIT
def generate_googlemaps(self): """ Template for googlemaps.html implementing Overlay of tiles for 'mercator' profile. It returns filled string. Expected variables: title, googlemapskey, north, south, east, west, minzoom, maxzoom, tilesize, tileformat, publishurl """ args...
Template for googlemaps.html implementing Overlay of tiles for 'mercator' profile. It returns filled string. Expected variables: title, googlemapskey, north, south, east, west, minzoom, maxzoom, tilesize, tileformat, publishurl
generate_googlemaps
python
commenthol/gdal2tiles-leaflet
gdal2tiles-multiprocess.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles-multiprocess.py
MIT
def generate_openlayers(self): """ Template for openlayers.html implementing overlay of available Spherical Mercator layers. It returns filled string. Expected variables: title, bingkey, north, south, east, west, minzoom, maxzoom, tilesize, tileformat, publishurl """ ar...
Template for openlayers.html implementing overlay of available Spherical Mercator layers. It returns filled string. Expected variables: title, bingkey, north, south, east, west, minzoom, maxzoom, tilesize, tileformat, publishurl
generate_openlayers
python
commenthol/gdal2tiles-leaflet
gdal2tiles-multiprocess.py
https://github.com/commenthol/gdal2tiles-leaflet/blob/master/gdal2tiles-multiprocess.py
MIT
def build_dataset(tokenizer, config): ''' We assume that we have preprocessed the dataset appropriately such that the sample is organized as follows: {"positive": prompt + answer_positive, "negative": prompt + answer_negative}, where the positive response is preferred. ''' def tokenize(sample): ...
We assume that we have preprocessed the dataset appropriately such that the sample is organized as follows: {"positive": prompt + answer_positive, "negative": prompt + answer_negative}, where the positive response is preferred.
build_dataset
python
OptimalScale/LMFlow
contrib/rlhflow/reward_modeling.py
https://github.com/OptimalScale/LMFlow/blob/master/contrib/rlhflow/reward_modeling.py
Apache-2.0
def tokenize( self, dataset, add_special_tokens=True, *args, **kwargs ) -> Dataset: """ Tokenize the full dataset. Parameters ------------ dataset : lmflow.datasets.Dataset. args : Optional. Positional argu...
Tokenize the full dataset. Parameters ------------ dataset : lmflow.datasets.Dataset. args : Optional. Positional arguments. kwargs : Optional. Keyword arguments. Returns ------------ tokenized_d...
tokenize
python
OptimalScale/LMFlow
contrib/tool-finetune/function_call_finetune.py
https://github.com/OptimalScale/LMFlow/blob/master/contrib/tool-finetune/function_call_finetune.py
Apache-2.0
def update_ema(target_params, source_params, rate=0.99): """ Update target parameters to be closer to those of source parameters using an exponential moving average. :param target_params: the target parameter sequence. :param source_params: the source parameter sequence. :param rate: the EMA ra...
Update target parameters to be closer to those of source parameters using an exponential moving average. :param target_params: the target parameter sequence. :param source_params: the source parameter sequence. :param rate: the EMA rate (closer to 1 means slower).
update_ema
python
OptimalScale/LMFlow
experimental/LISA-diffusion/diffusion_dpo/train_diffusion_dpo_lisa.py
https://github.com/OptimalScale/LMFlow/blob/master/experimental/LISA-diffusion/diffusion_dpo/train_diffusion_dpo_lisa.py
Apache-2.0
def group_by_keys_nothrow(data, keys=base_plus_ext, lcase=True, suffixes=None, handler=None): """Return function over iterator that groups key, value pairs into samples. :param keys: function that splits the key into key and extension (base_plus_ext) :param lcase: convert suffixes to lower case (Default va...
Return function over iterator that groups key, value pairs into samples. :param keys: function that splits the key into key and extension (base_plus_ext) :param lcase: convert suffixes to lower case (Default value = True)
group_by_keys_nothrow
python
OptimalScale/LMFlow
experimental/LISA-diffusion/latent_consistency_model/train_lcm_distill_sd_wds_lisa.py
https://github.com/OptimalScale/LMFlow/blob/master/experimental/LISA-diffusion/latent_consistency_model/train_lcm_distill_sd_wds_lisa.py
Apache-2.0
def guidance_scale_embedding(w, embedding_dim=512, dtype=torch.float32): """ See https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298 Args: timesteps (`torch.Tensor`): generate embedding vectors at these timesteps embedding_dim (...
See https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298 Args: timesteps (`torch.Tensor`): generate embedding vectors at these timesteps embedding_dim (`int`, *optional*, defaults to 512): dimension of the embeddings to ...
guidance_scale_embedding
python
OptimalScale/LMFlow
experimental/LISA-diffusion/latent_consistency_model/train_lcm_distill_sd_wds_lisa.py
https://github.com/OptimalScale/LMFlow/blob/master/experimental/LISA-diffusion/latent_consistency_model/train_lcm_distill_sd_wds_lisa.py
Apache-2.0
def parse_argument(sys_argv): """Parses arguments from command line. Args: sys_argv: the list of arguments (strings) from command line. Returns: A struct whose member corresponds to the required (optional) variable. For example, ``` args = parse_argument(['main.py' '-...
Parses arguments from command line. Args: sys_argv: the list of arguments (strings) from command line. Returns: A struct whose member corresponds to the required (optional) variable. For example, ``` args = parse_argument(['main.py' '--input', 'a.txt', '--num', '10']) ...
parse_argument
python
OptimalScale/LMFlow
scripts/data_preprocess/add_end_mark.py
https://github.com/OptimalScale/LMFlow/blob/master/scripts/data_preprocess/add_end_mark.py
Apache-2.0
def raw2textonly(fin): """ Converts raw text to text-only format. Args: fin: the input file description of the raw text file. Returns: a dict with "text-only" format. """ data_dict = { "type": "text_only", "instances": [ { "text": line.strip() } for line in fin ]...
Converts raw text to text-only format. Args: fin: the input file description of the raw text file. Returns: a dict with "text-only" format.
raw2textonly
python
OptimalScale/LMFlow
scripts/data_preprocess/raw2textonly.py
https://github.com/OptimalScale/LMFlow/blob/master/scripts/data_preprocess/raw2textonly.py
Apache-2.0
def _check_instance_format(self): """ Checks if data (instances) have required fields. Raises messages with hints if not matched. """ fields = self.backend_dataset.features correct_fields = INSTANCE_FIELDS_MAP[self.type] if not set(correct_fields).issubset(set(fi...
Checks if data (instances) have required fields. Raises messages with hints if not matched.
_check_instance_format
python
OptimalScale/LMFlow
src/lmflow/datasets/dataset.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/datasets/dataset.py
Apache-2.0
def from_dict(self, dict_obj: dict, *args, **kwargs): r""" Create a Dataset object from a dictionary. Return a Dataset given a dict with format: { "type": TYPE, "instances": [ { "key_1": VALUE_1.1, ...
Create a Dataset object from a dictionary. Return a Dataset given a dict with format: { "type": TYPE, "instances": [ { "key_1": VALUE_1.1, "key_2": VALUE_1.2, ... ...
from_dict
python
OptimalScale/LMFlow
src/lmflow/datasets/dataset.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/datasets/dataset.py
Apache-2.0
def create_from_dict(cls, dict_obj, *args, **kwargs): r""" Returns -------- Returns a Dataset object given a dict. """ empty_data_args = DatasetArguments(dataset_path=None) dataset = Dataset(empty_data_args) return dataset.from_dict(dict_obj)
Returns -------- Returns a Dataset object given a dict.
create_from_dict
python
OptimalScale/LMFlow
src/lmflow/datasets/dataset.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/datasets/dataset.py
Apache-2.0
def to_dict(self): r""" Returns --------- Return a dict represents the dataset: { "type": TYPE, "instances": [ { "key_1": VALUE_1.1, "key_2": VALUE_1.2, ...
Returns --------- Return a dict represents the dataset: { "type": TYPE, "instances": [ { "key_1": VALUE_1.1, "key_2": VALUE_1.2, ... }, ...
to_dict
python
OptimalScale/LMFlow
src/lmflow/datasets/dataset.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/datasets/dataset.py
Apache-2.0
def map(self, *args, **kwargs): r""" Parameters ------------ args : Optional. Positional arguments. kwargs : Optional. Keyword arguments. Returns --------- self : Dataset object. """ # If the dataset uses ...
Parameters ------------ args : Optional. Positional arguments. kwargs : Optional. Keyword arguments. Returns --------- self : Dataset object.
map
python
OptimalScale/LMFlow
src/lmflow/datasets/dataset.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/datasets/dataset.py
Apache-2.0
def save( self, file_path: str, format: str="json" ): r""" Save the dataset to a json file. Parameters ------------ file_path : str. The path to the file where the dataset will be saved. """ if format == "json": ...
Save the dataset to a json file. Parameters ------------ file_path : str. The path to the file where the dataset will be saved.
save
python
OptimalScale/LMFlow
src/lmflow/datasets/dataset.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/datasets/dataset.py
Apache-2.0
def sample(self, n: int, seed: int=42): r""" Sample n instances from the dataset. Parameters ------------ n : int. The number of instances to sample from the dataset. Returns --------- sample_dataset : Dataset object. A new datas...
Sample n instances from the dataset. Parameters ------------ n : int. The number of instances to sample from the dataset. Returns --------- sample_dataset : Dataset object. A new dataset object containing the sampled instances.
sample
python
OptimalScale/LMFlow
src/lmflow/datasets/dataset.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/datasets/dataset.py
Apache-2.0
def train_test_split(self, test_size: float=0.2, shuffle: bool=True, seed: int=42): r""" Split the dataset into training and testing sets. Parameters ------------ test_size : float, default=0.2. The proportion of the dataset that will be used for testing. Re...
Split the dataset into training and testing sets. Parameters ------------ test_size : float, default=0.2. The proportion of the dataset that will be used for testing. Returns --------- train_dataset : Dataset object. A new dataset objec...
train_test_split
python
OptimalScale/LMFlow
src/lmflow/datasets/dataset.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/datasets/dataset.py
Apache-2.0
def drop_instances(self, indices: list): r""" Drop instances from the dataset. Parameters ------------ indices : list. A list of indices of the instances to drop from the dataset. """ if self.backend == "huggingface": self.backend_dataset ...
Drop instances from the dataset. Parameters ------------ indices : list. A list of indices of the instances to drop from the dataset.
drop_instances
python
OptimalScale/LMFlow
src/lmflow/datasets/dataset.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/datasets/dataset.py
Apache-2.0
def sanity_check( self, drop_invalid: bool=True, ): r""" Perform a sanity check on the dataset. """ if self.backend == "huggingface": self.hf_dataset_sanity_check(drop_invalid) else: raise NotImplementedError( f'Current...
Perform a sanity check on the dataset.
sanity_check
python
OptimalScale/LMFlow
src/lmflow/datasets/dataset.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/datasets/dataset.py
Apache-2.0
def hf_dataset_sanity_check( self, drop_invalid: bool=True, ): r""" Perform a sanity check on the HuggingFace dataset. """ if self.backend_dataset is None or len(self.backend_dataset) == 0: raise ValueError("Dataset is empty.") if self.type == 'te...
Perform a sanity check on the HuggingFace dataset.
hf_dataset_sanity_check
python
OptimalScale/LMFlow
src/lmflow/datasets/dataset.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/datasets/dataset.py
Apache-2.0
def preprocess_llama_from_llava_plain( sources, tokenizer: transformers.PreTrainedTokenizer, has_image: bool = False): """ This function just add the image in the front of text. And don't add any prompt. Args: sources: The input data with text and image. tokenizer: The tokeni...
This function just add the image in the front of text. And don't add any prompt. Args: sources: The input data with text and image. tokenizer: The tokenizer to process text. has_image: Whether the input data has image. Returns: The input_ids and labels for the model. ...
preprocess_llama_from_llava_plain
python
OptimalScale/LMFlow
src/lmflow/datasets/multi_modal_dataset.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/datasets/multi_modal_dataset.py
Apache-2.0
def preprocess_llama_from_llava_v1( sources, tokenizer: transformers.PreTrainedTokenizer, has_image: bool = False): """ This function add the prompt and then put the image after the prompt. So it needs additional code to generate the target label. Args: sources: The input data with t...
This function add the prompt and then put the image after the prompt. So it needs additional code to generate the target label. Args: sources: The input data with text and image. tokenizer: The tokenizer to process text. has_image: Whether the input data has image. Returns: ...
preprocess_llama_from_llava_v1
python
OptimalScale/LMFlow
src/lmflow/datasets/multi_modal_dataset.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/datasets/multi_modal_dataset.py
Apache-2.0
def __init__( self, model_args, tune_strategy='normal', ds_config=None, device="gpu", use_accelerator=False, *args, **kwargs ): """ Initializes a HFDecoderModel instance. :param model_args: dictionary with model arguments such a...
Initializes a HFDecoderModel instance. :param model_args: dictionary with model arguments such as model name, path, revision, etc. :param tune_strategy: tuning strategy: normal, none, lora or adapter :param ds_config: deepspeed configuration for distributed training
__init__
python
OptimalScale/LMFlow
src/lmflow/models/hf_decoder_model.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/models/hf_decoder_model.py
Apache-2.0
def encode(self, input: Union[str, List[str]], *args, **kwargs ) -> Union[List[int], List[List[int]]]: """ Perform encoding process of the tokenizer. Parameters ------------ inputs : str or list. The text sequence. args : Optional. ...
Perform encoding process of the tokenizer. Parameters ------------ inputs : str or list. The text sequence. args : Optional. Positional arguments. kwargs : Optional. Keyword arguments. Re...
encode
python
OptimalScale/LMFlow
src/lmflow/models/hf_decoder_model.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/models/hf_decoder_model.py
Apache-2.0
def decode(self, input, *args, **kwargs ) -> Union[str, List[str]]: """ Perform decoding process of the tokenizer. Parameters ------------ inputs : list or tensor. The token sequence. args : Optional. Positional arguments. ...
Perform decoding process of the tokenizer. Parameters ------------ inputs : list or tensor. The token sequence. args : Optional. Positional arguments. kwargs : Optional. Keyword arguments. ...
decode
python
OptimalScale/LMFlow
src/lmflow/models/hf_decoder_model.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/models/hf_decoder_model.py
Apache-2.0
def inference( self, inputs, release_gpu: bool = False, use_vllm: bool = False, **kwargs ): """ Perform generation process of the model. Parameters ------------ inputs : The sequence used as a prompt for the generatio...
Perform generation process of the model. Parameters ------------ inputs : The sequence used as a prompt for the generation or as model inputs to the model. When using vllm inference, this should be a string or a list of strings. When using normal...
inference
python
OptimalScale/LMFlow
src/lmflow/models/hf_decoder_model.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/models/hf_decoder_model.py
Apache-2.0
def __inference(self, inputs, *args, **kwargs): """ Perform generation process of the model. Parameters ------------ inputs : The **tokenized** sequence used as a prompt for the generation or as model inputs to the model. args : Optional. ...
Perform generation process of the model. Parameters ------------ inputs : The **tokenized** sequence used as a prompt for the generation or as model inputs to the model. args : Optional. Positional arguments. kwargs : Op...
__inference
python
OptimalScale/LMFlow
src/lmflow/models/hf_decoder_model.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/models/hf_decoder_model.py
Apache-2.0
def __vllm_inference( self, inputs: Union[str, List[str]], sampling_params: Optional['SamplingParams'] = None, **kwargs, ) -> List[VLLMInferenceResultWithInput]: """Perform VLLM inference process of the model. Parameters ---------- inputs : Union[str...
Perform VLLM inference process of the model. Parameters ---------- inputs : Union[str, List[str]] Prompt(s), string or a list of strings. sampling_params : Optional[SamplingParams], optional vllm SamplingParams object, by default None. Returns --...
__vllm_inference
python
OptimalScale/LMFlow
src/lmflow/models/hf_decoder_model.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/models/hf_decoder_model.py
Apache-2.0
def prepare_inputs_for_inference( self, dataset: Dataset, apply_chat_template: bool = True, enable_distributed_inference: bool = False, use_vllm: bool = False, **kwargs, ) -> Union[List[str], "ray.data.Dataset", Dict[str, torch.Tensor]]: """ Prepare in...
Prepare inputs for inference. Parameters ------------ dataset : lmflow.datasets.Dataset. The dataset used for inference. args : Optional. Positional arguments. kwargs : Optional. Keyword arguments. ...
prepare_inputs_for_inference
python
OptimalScale/LMFlow
src/lmflow/models/hf_decoder_model.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/models/hf_decoder_model.py
Apache-2.0
def save(self, dir, save_full_model=False, *args, **kwargs): """ Perform generation process of the model. Parameters ------------ dir : The directory to save model and tokenizer save_full_model : Optional. Whether to save full mod...
Perform generation process of the model. Parameters ------------ dir : The directory to save model and tokenizer save_full_model : Optional. Whether to save full model. kwargs : Optional. Keyword arguments. ...
save
python
OptimalScale/LMFlow
src/lmflow/models/hf_decoder_model.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/models/hf_decoder_model.py
Apache-2.0
def encode(self, input: Union[str, List[str]], *args, **kwargs ) -> Union[List[int], List[List[int]]]: """ Perform encoding process of the tokenizer. Parameters ------------ inputs : str or list. The text sequence. args : Optional. Positional arg...
Perform encoding process of the tokenizer. Parameters ------------ inputs : str or list. The text sequence. args : Optional. Positional arguments. kwargs : Optional. Keyword arguments. Returns ------------ o...
encode
python
OptimalScale/LMFlow
src/lmflow/models/hf_encoder_decoder_model.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/models/hf_encoder_decoder_model.py
Apache-2.0
def decode(self, input, *args, **kwargs ) -> Union[str, List[str]]: """ Perform decoding process of the tokenizer. Parameters ------------ inputs : list. The token sequence. args : Optional. Positional arguments. kwargs : Optional. ...
Perform decoding process of the tokenizer. Parameters ------------ inputs : list. The token sequence. args : Optional. Positional arguments. kwargs : Optional. Keyword arguments. Returns ------------ outputs...
decode
python
OptimalScale/LMFlow
src/lmflow/models/hf_encoder_decoder_model.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/models/hf_encoder_decoder_model.py
Apache-2.0
def inference(self, inputs, *args, **kwargs): """ Perform generation process of the model. Parameters ------------ inputs : The sequence used as a prompt for the generation or as model inputs to the model. args : Optional. Positional arguments. ...
Perform generation process of the model. Parameters ------------ inputs : The sequence used as a prompt for the generation or as model inputs to the model. args : Optional. Positional arguments. kwargs : Optional. Keyword arguments....
inference
python
OptimalScale/LMFlow
src/lmflow/models/hf_encoder_decoder_model.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/models/hf_encoder_decoder_model.py
Apache-2.0
def save(self, dir, save_full_model=False, *args, **kwargs): """ Perform generation process of the model. Parameters ------------ dir : The directory to save model and tokenizer save_full_model : Optional. Whether to save full model. kwa...
Perform generation process of the model. Parameters ------------ dir : The directory to save model and tokenizer save_full_model : Optional. Whether to save full model. kwargs : Optional. Keyword arguments. Returns ...
save
python
OptimalScale/LMFlow
src/lmflow/models/hf_encoder_decoder_model.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/models/hf_encoder_decoder_model.py
Apache-2.0
def get_max_length(self): """ Return max acceptable input length in terms of tokens. """ if "tokenizer" not in self.tokenizer.__dict__: return self.tokenizer.model_max_length else: # for the multi-modality processor, # the max length is stored ...
Return max acceptable input length in terms of tokens.
get_max_length
python
OptimalScale/LMFlow
src/lmflow/models/hf_encoder_decoder_model.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/models/hf_encoder_decoder_model.py
Apache-2.0
def __init__( self, model_args: ModelArguments, do_train: bool, ds_config=None, device: Optional[str]="gpu", use_accelerator: bool=False, hf_auto_model_additional_args: Optional[Dict]=None, *args, **kwargs ): """Initializes a HFModel in...
Initializes a HFModel instance. Parameters ---------- model_args : Dictionary with model arguments such as model name, path, revision, etc. do_train : bool To prepare the model for training or inference. ds_config : optional Deepspeed configu...
__init__
python
OptimalScale/LMFlow
src/lmflow/models/hf_model_mixin.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/models/hf_model_mixin.py
Apache-2.0
def __prepare_model_config( self, model_args: ModelArguments, hf_auto_model_additional_args: Optional[Dict]=None, ): """Prepare model configuration for hf auto register, Parameters ---------- model_args : ModelArguments LMFlow model arguments. ...
Prepare model configuration for hf auto register, Parameters ---------- model_args : ModelArguments LMFlow model arguments. hf_auto_model_additional_args : Optional[Dict], optional Special configurations such as `num_labels` in `AutoModelForSequenceClassification`...
__prepare_model_config
python
OptimalScale/LMFlow
src/lmflow/models/hf_model_mixin.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/models/hf_model_mixin.py
Apache-2.0
def __model_module_inject( self, model_args: ModelArguments, ) -> None: """Override some model modules with custom implementations. Current implementations: - Position interpolation (model_args.do_rope_scaling): replace llama embeddings with condense emb...
Override some model modules with custom implementations. Current implementations: - Position interpolation (model_args.do_rope_scaling): replace llama embeddings with condense embeddings.
__model_module_inject
python
OptimalScale/LMFlow
src/lmflow/models/hf_model_mixin.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/models/hf_model_mixin.py
Apache-2.0
def deactivate_model_for_inference( self, use_vllm: bool=False, ): """Deactivate the model and release the resources. NOTE: Currently, VLLM doesn't have an official way to do this, and the implementation below cannot release all gpu resources by our observation. ...
Deactivate the model and release the resources. NOTE: Currently, VLLM doesn't have an official way to do this, and the implementation below cannot release all gpu resources by our observation. Thus this method is just a placeholder for future implementation. See: [Github issue]...
deactivate_model_for_inference
python
OptimalScale/LMFlow
src/lmflow/models/hf_model_mixin.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/models/hf_model_mixin.py
Apache-2.0
def __init__( self, model_args: ModelArguments, tune_strategy: str='normal', ds_config=None, device="gpu", use_accelerator=False, *args, **kwargs ): """ Initializes a HFTextRegressionModel instance. :param model_args: dictionary...
Initializes a HFTextRegressionModel instance. :param model_args: dictionary with model arguments such as model name, path, revision, etc. :param tune_strategy: tuning strategy: normal, none, lora or adapter :param ds_config: deepspeed configuration for distributed training
__init__
python
OptimalScale/LMFlow
src/lmflow/models/hf_text_regression_model.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/models/hf_text_regression_model.py
Apache-2.0
def __inference( self, inputs, **kwargs ): """ Perform generation process of the model. Parameters ------------ inputs : The **tokenized** sequence used as a prompt for the generation or as model inputs to the model. kwargs :...
Perform generation process of the model. Parameters ------------ inputs : The **tokenized** sequence used as a prompt for the generation or as model inputs to the model. kwargs : Optional. Keyword arguments. Returns -----...
__inference
python
OptimalScale/LMFlow
src/lmflow/models/hf_text_regression_model.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/models/hf_text_regression_model.py
Apache-2.0
def __vllm_inference( self, inputs: Union[str, List[str]], sampling_params: Optional['SamplingParams'] = None, **kwargs, ) -> Union[List[List[str]], List[List[List[int]]]]: """Perform VLLM inference process of the model. Parameters ---------- inputs ...
Perform VLLM inference process of the model. Parameters ---------- inputs : Union[str, List[str]] Prompt(s), string or a list of strings. sampling_params : Optional[SamplingParams], optional vllm SamplingParams object, by default None. Returns --...
__vllm_inference
python
OptimalScale/LMFlow
src/lmflow/models/hf_text_regression_model.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/models/hf_text_regression_model.py
Apache-2.0
def __init__( self, model_args, *args, **kwargs ): """ Initializes a TextRegressionModel instance. :param model_args: dictionary with model arguments such as model name, path, revision, etc. """ self.inference_func = None
Initializes a TextRegressionModel instance. :param model_args: dictionary with model arguments such as model name, path, revision, etc.
__init__
python
OptimalScale/LMFlow
src/lmflow/models/text_regression_model.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/models/text_regression_model.py
Apache-2.0
def inference(self, inputs: Dataset): """ Gets regression results of a given dataset. :inputs: Dataset object, only accept type "text_only". """ if self.inference_func is not None: return self.inference_func(inputs) else: pass
Gets regression results of a given dataset. :inputs: Dataset object, only accept type "text_only".
inference
python
OptimalScale/LMFlow
src/lmflow/models/text_regression_model.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/models/text_regression_model.py
Apache-2.0
def __init__(self, config: Blip2Config, image_encoder_name_or_path=None, qformer_name_or_path=None, language_model_name_or_path=None, low_resource=False,): ''' TODO update the docs Args: config: ...
TODO update the docs Args: config: # the below varaible are used to overwrite the model in config image_encoder_name_or_path: qformer_name_or_path: language_model_name_or_path: Returns:
__init__
python
OptimalScale/LMFlow
src/lmflow/models/vision2seq_model.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/models/vision2seq_model.py
Apache-2.0
def register_prompt_cache(self, prompt_ids, prompt_keys_values): """ Udpate the prompt id and embedding for reuse in the future Args: prompt_ids (torch.LongTensor): The id of the prompt. prompt_keys_values (torch.FloatTensor): The embedding of the prompt. Return...
Udpate the prompt id and embedding for reuse in the future Args: prompt_ids (torch.LongTensor): The id of the prompt. prompt_keys_values (torch.FloatTensor): The embedding of the prompt. Returns: None
register_prompt_cache
python
OptimalScale/LMFlow
src/lmflow/models/vision2seq_model.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/models/vision2seq_model.py
Apache-2.0
def save_prompt_cache(self, path): """ Save prompt embedding and id. Args: path: The path to save the prompt embedding and id. Returns: None """ torch.save( dict( prompt_ids=self.prompt_ids, prompt_key...
Save prompt embedding and id. Args: path: The path to save the prompt embedding and id. Returns: None
save_prompt_cache
python
OptimalScale/LMFlow
src/lmflow/models/vision2seq_model.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/models/vision2seq_model.py
Apache-2.0
def generate( self, pixel_values: torch.FloatTensor, input_ids: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.LongTensor] = None, image_token_indexes: Optional[List] = [0], one_sample_multiple_images: Optional[bool] = False, images: Optional[to...
Overrides `generate` function to be able to use the model as a conditional generator. Args: pixel_values (`torch.FloatTensor` of shape (batch_size, num_channels, height, width)): Input images to be processed. input_ids (`torch.LongTensor` of shape (batch_size, s...
generate
python
OptimalScale/LMFlow
src/lmflow/models/vision2seq_model.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/models/vision2seq_model.py
Apache-2.0
def prepare_inputs_labels_for_multimodal( self, input_ids, attention_mask, past_key_values, labels, images, language_projection=None, language_model=None, **kwargs ): ''' Copy from the LLAVA code base. Should be polished. ''' vision_tower = sel...
Copy from the LLAVA code base. Should be polished.
prepare_inputs_labels_for_multimodal
python
OptimalScale/LMFlow
src/lmflow/models/vision_encoder/clip_encoder.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/models/vision_encoder/clip_encoder.py
Apache-2.0
def step(self, closure=None): """Performs a single optimization step. Arguments: closure (callable, optional): A closure that reevaluates the model and returns the loss. """ loss = None if closure is not None: loss = closure() for ...
Performs a single optimization step. Arguments: closure (callable, optional): A closure that reevaluates the model and returns the loss.
step
python
OptimalScale/LMFlow
src/lmflow/optim/adabelief.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/optim/adabelief.py
Apache-2.0
def step(self, closure = None): r"""Performs a single optimization step. Arguments: closure: A closure that reevaluates the model and returns the loss. """ loss = None if closure is not None: loss = closure() for group, base_lr in zip(self.param_...
Performs a single optimization step. Arguments: closure: A closure that reevaluates the model and returns the loss.
step
python
OptimalScale/LMFlow
src/lmflow/optim/adabound.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/optim/adabound.py
Apache-2.0
def step(self, closure: Callable=None): """ Performs a single optimization step. Arguments: closure (:obj:`Callable`, `optional`): A closure that reevaluates the model and returns the loss. """ loss = None if closure is not None: loss = closure() ...
Performs a single optimization step. Arguments: closure (:obj:`Callable`, `optional`): A closure that reevaluates the model and returns the loss.
step
python
OptimalScale/LMFlow
src/lmflow/optim/dummy.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/optim/dummy.py
Apache-2.0
def zeropower_via_newtonschulz5(G: Tensor, steps: int) -> Tensor: """ Newton-Schulz iteration to compute the zeroth power / orthogonalization of G. We opt to use a quintic iteration whose coefficients are selected to maximize the slope at zero. For the purpose of minimizing steps, it turns out to be emp...
Newton-Schulz iteration to compute the zeroth power / orthogonalization of G. We opt to use a quintic iteration whose coefficients are selected to maximize the slope at zero. For the purpose of minimizing steps, it turns out to be empirically effective to keep increasing the slope at zero even beyond t...
zeropower_via_newtonschulz5
python
OptimalScale/LMFlow
src/lmflow/optim/muon.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/optim/muon.py
Apache-2.0
def step(self, closure=None): """ Performs a single optimization step. Args: closure (callable, optional): A closure that reevaluates the model and returns the loss. """ loss = None if closure is not None: loss = closure() ...
Performs a single optimization step. Args: closure (callable, optional): A closure that reevaluates the model and returns the loss.
step
python
OptimalScale/LMFlow
src/lmflow/optim/muon.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/optim/muon.py
Apache-2.0
def convert_to_paired_dataset( self, source_dataset: Dataset, sampling_paired_method: str="random", length_penalty: float=0.0, margin_scale: float=1.0, use_fast: bool=False, ) -> Dataset: """Convert a scored one to multiple (text_to_scored_textlist) to a paire...
Convert a scored one to multiple (text_to_scored_textlist) to a paired dataset by rejection sampling.
convert_to_paired_dataset
python
OptimalScale/LMFlow
src/lmflow/pipeline/dpov2_aligner.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/pipeline/dpov2_aligner.py
Apache-2.0
def _calc_reward_with_length_penalty( self, rewards: List[float], lengths: List[int], length_penalty: float, ) -> List[float]: """When length_penalty > 0, penalize the longer sequence by subtracting length_penalty * length from the reward. Vice versa when length_pe...
When length_penalty > 0, penalize the longer sequence by subtracting length_penalty * length from the reward. Vice versa when length_penalty < 0.
_calc_reward_with_length_penalty
python
OptimalScale/LMFlow
src/lmflow/pipeline/dpov2_aligner.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/pipeline/dpov2_aligner.py
Apache-2.0
def sampling_paired_idx_from_rewards( self, rewards: List[float], sampling_paired_method: str="random", use_fast: bool=False, ) -> Tuple[int, int]: """Prepare the dataset for DPO training by rejection sampling. We implement different strategies to select pairs, includ...
Prepare the dataset for DPO training by rejection sampling. We implement different strategies to select pairs, including random: randomly select two instances max_min: best v.s. worst max_max: best v.s. second best max_random: best v.s. random from the remaining
sampling_paired_idx_from_rewards
python
OptimalScale/LMFlow
src/lmflow/pipeline/dpov2_aligner.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/pipeline/dpov2_aligner.py
Apache-2.0
def get_paired_dataset( data_root: str, data_dir: str, sanity_check: bool = False, cache_dir: Optional[str] = None, num_proc=24, ) -> Dataset: """Load dataset and convert it to the necessary format. The dataset is converted to a dictionary with the following structure: ...
Load dataset and convert it to the necessary format. The dataset is converted to a dictionary with the following structure: { 'prompt': List[str], 'chosen': List[str], 'rejected': List[str], } Prompts are structured as follows: "Question: " + <prompt> + " Answer: "
get_paired_dataset
python
OptimalScale/LMFlow
src/lmflow/pipeline/dpo_aligner.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/pipeline/dpo_aligner.py
Apache-2.0
def evaluate( self, model, dataset: Dataset, metric = "accuracy", verbose=True, ): """ Perform Evaluation for a model Parameters ------------ model : TunableModel object. TunableModel to perform inference dataset :...
Perform Evaluation for a model Parameters ------------ model : TunableModel object. TunableModel to perform inference dataset : Dataset object.
evaluate
python
OptimalScale/LMFlow
src/lmflow/pipeline/evaluator.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/pipeline/evaluator.py
Apache-2.0
def _evaluate_nll( self, model, dataset: Dataset, verbose=True, ): """ Evaluates negative log likelihood of the model over a dataset. NLL = -1/N sum_{i=1}^N sum_{j=1}^|w_i| ln(p(w_{i,j}|context_window)), where N is the number of data samples, w_{i,j}...
Evaluates negative log likelihood of the model over a dataset. NLL = -1/N sum_{i=1}^N sum_{j=1}^|w_i| ln(p(w_{i,j}|context_window)), where N is the number of data samples, w_{i,j} is the j-th token in i-th sample. Here "context_window" = p(w_{i,start}, w_{i,start+1}, ..., p_{i...
_evaluate_nll
python
OptimalScale/LMFlow
src/lmflow/pipeline/evaluator.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/pipeline/evaluator.py
Apache-2.0
def group_text(self, tokenized_datasets, model_max_length): """ Groups texts together to form blocks of maximum length `model_max_length` and returns the processed data as a dictionary. """ data_args = self.data_args finetuner_args = self.finetuner_args if data_a...
Groups texts together to form blocks of maximum length `model_max_length` and returns the processed data as a dictionary.
group_text
python
OptimalScale/LMFlow
src/lmflow/pipeline/finetuner.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/pipeline/finetuner.py
Apache-2.0
def tune(self, model: Union[HFDecoderModel, HFTextRegressionModel, HFEncoderDecoderModel], dataset: Dataset, transform_dataset_in_place=True, data_collator=None): """ Perform tuning for a model Parameters ------------ model : T...
Perform tuning for a model Parameters ------------ model : TunableModel object. TunableModel to perform tuning. dataset: dataset to train model.
tune
python
OptimalScale/LMFlow
src/lmflow/pipeline/finetuner.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/pipeline/finetuner.py
Apache-2.0
def create_dataloader(self, dataset: Dataset): r"""Batchlize dataset and format it to dataloader. Args: dataset (Dataset): the dataset object Output: dataloader (batchlize): the dataloader object dataset_size (int): the length of the dataset """ ...
Batchlize dataset and format it to dataloader. Args: dataset (Dataset): the dataset object Output: dataloader (batchlize): the dataloader object dataset_size (int): the length of the dataset
create_dataloader
python
OptimalScale/LMFlow
src/lmflow/pipeline/inferencer.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/pipeline/inferencer.py
Apache-2.0
def inference( self, model, dataset: Dataset, max_new_tokens: int=100, temperature: float=0.0, prompt_structure: str='{input}', remove_image_flag: bool=False, chatbot_type: str="mini_gpt", ): """ Perform inference for a model P...
Perform inference for a model Parameters ------------ model : TunableModel object. TunableModel to perform inference dataset : Dataset object. Returns: output_dataset: Dataset object.
inference
python
OptimalScale/LMFlow
src/lmflow/pipeline/inferencer.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/pipeline/inferencer.py
Apache-2.0
def score_to_prob(scores: torch.Tensor, temperature: float = 0., top_p: float = 1.,) -> torch.Tensor: """Convert scores (NOT softmaxed tensor) to probabilities with support for temperature, top-p sampling, and argmax. Parameters ---------- sc...
Convert scores (NOT softmaxed tensor) to probabilities with support for temperature, top-p sampling, and argmax. Parameters ---------- scores : torch.Tensor Input scores. temperature : float, optional Temperature parameter for controlling randomness. Higher value...
score_to_prob
python
OptimalScale/LMFlow
src/lmflow/pipeline/inferencer.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/pipeline/inferencer.py
Apache-2.0
def predict_next_token(model: HFDecoderModel, input_ids: torch.Tensor, num_new_tokens: int = 1): """Predict the next token given the input_ids. """ output = model.inference(input_ids, use_accelerator=True, max_new_tokens=num_new...
Predict the next token given the input_ids.
predict_next_token
python
OptimalScale/LMFlow
src/lmflow/pipeline/inferencer.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/pipeline/inferencer.py
Apache-2.0
def autoregressive_sampling(self, input_ids: torch.Tensor, model: HFDecoderModel, temperature: float = 0., num_new_tokens: int = 5) -> Dict: """Ref: [arXiv:2211.17192v2](https://ar...
Ref: [arXiv:2211.17192v2](https://arxiv.org/abs/2211.17192) Section 2.2
autoregressive_sampling
python
OptimalScale/LMFlow
src/lmflow/pipeline/inferencer.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/pipeline/inferencer.py
Apache-2.0
def inference( self, model: HFDecoderModel, input: str, max_new_tokens: int=1024, ): """ Perform inference for a model Parameters ------------ model : HFDecoderModel object. TunableModel to perform inference input : str. ...
Perform inference for a model Parameters ------------ model : HFDecoderModel object. TunableModel to perform inference input : str. The input text (i.e., the prompt) for the model. max_new_tokens : int. The maximum numb...
inference
python
OptimalScale/LMFlow
src/lmflow/pipeline/inferencer.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/pipeline/inferencer.py
Apache-2.0
def _initialize_trainer(self, model, tokenizer, training_args): """ This function takes the model and tokenizer as the input and initialize the trainer. """ trainer = RaftTrainer( model=model, args=training_args, train_dataset=Dataset.from_dict({"text"...
This function takes the model and tokenizer as the input and initialize the trainer.
_initialize_trainer
python
OptimalScale/LMFlow
src/lmflow/pipeline/raft_aligner.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/pipeline/raft_aligner.py
Apache-2.0
def _load_dataset( self, selected_dataset, model, tokenizer, model_args, data_args, training_args, ): ''' This function prepares the dataset for every iteration. ''' raw_datasets = selected_dataset if training_args.do_t...
This function prepares the dataset for every iteration.
_load_dataset
python
OptimalScale/LMFlow
src/lmflow/pipeline/raft_aligner.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/pipeline/raft_aligner.py
Apache-2.0
def _load_input_dataset(self, dataset, tokenizer): """ Load input dataset (i.e. prompt/question dataset) for training. Args: dataset: A Dataset object. The dataset to be loaded. Returns: dataloader (`torch.utils.data.DataLoader`): ...
Load input dataset (i.e. prompt/question dataset) for training. Args: dataset: A Dataset object. The dataset to be loaded. Returns: dataloader (`torch.utils.data.DataLoader`): The dataloader for the dataset.
_load_input_dataset
python
OptimalScale/LMFlow
src/lmflow/pipeline/raft_aligner.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/pipeline/raft_aligner.py
Apache-2.0
def align(self, model, dataset, reward_model): """ Perform alignment for a model Parameters ------------ model : BaseModel object. dataset: Dataset object. Input dataset for model to generate outputs. The input and output will then be feed int...
Perform alignment for a model Parameters ------------ model : BaseModel object. dataset: Dataset object. Input dataset for model to generate outputs. The input and output will then be feed into reward model to get the reward for align...
align
python
OptimalScale/LMFlow
src/lmflow/pipeline/raft_aligner.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/pipeline/raft_aligner.py
Apache-2.0
def __call__(self, batch: Dict[str, np.ndarray]): """batch: Dict[str, np.ndarray] Example (batch size=2): {'input': array(['...','...'], dtype=object), 'output': array([array(["...", "..."], dtype=object), array(['...','...'], dtype=object)], dtype=object...
batch: Dict[str, np.ndarray] Example (batch size=2): {'input': array(['...','...'], dtype=object), 'output': array([array(["...", "..."], dtype=object), array(['...','...'], dtype=object)], dtype=object), 'input_ids': array([[[128000, 128006, 882, ......
__call__
python
OptimalScale/LMFlow
src/lmflow/pipeline/rm_inferencer.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/pipeline/rm_inferencer.py
Apache-2.0
def inference( self, model: HFDecoderModel, dataset: Dataset, enable_decode_inference_result: bool = True, release_gpu: bool = False, inference_args: Optional[InferencerArguments] = None, enable_distributed_inference: bool = False, **kwargs, ) -> Lis...
Perform inference using the provided model and dataset. Will save inference results if `save_results` is set to True in `inferencer_args`. Parameters ---------- model : HFDecoderModel LMFlow HFDecoderModel object dataset : Dataset LMFlow Dataset object ...
inference
python
OptimalScale/LMFlow
src/lmflow/pipeline/vllm_inferencer.py
https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/pipeline/vllm_inferencer.py
Apache-2.0