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 build_all_layer_point_grids( n_per_side: int, n_layers: int, scale_per_layer: int ) -> List[np.ndarray]: """Generates point grids for all crop layers.""" points_by_layer = [] for i in range(n_layers + 1): n_points = int(n_per_side / (scale_per_layer**i)) points_by_layer.append(build_...
Generates point grids for all crop layers.
build_all_layer_point_grids
python
FutureUniant/Tailor
app/src/algorithm/base/sam2/sam2/utils/amg.py
https://github.com/FutureUniant/Tailor/blob/master/app/src/algorithm/base/sam2/sam2/utils/amg.py
Apache-2.0
def generate_crop_boxes( im_size: Tuple[int, ...], n_layers: int, overlap_ratio: float ) -> Tuple[List[List[int]], List[int]]: """ Generates a list of crop boxes of different sizes. Each layer has (2**i)**2 boxes for the ith layer. """ crop_boxes, layer_idxs = [], [] im_h, im_w = im_size ...
Generates a list of crop boxes of different sizes. Each layer has (2**i)**2 boxes for the ith layer.
generate_crop_boxes
python
FutureUniant/Tailor
app/src/algorithm/base/sam2/sam2/utils/amg.py
https://github.com/FutureUniant/Tailor/blob/master/app/src/algorithm/base/sam2/sam2/utils/amg.py
Apache-2.0
def remove_small_regions( mask: np.ndarray, area_thresh: float, mode: str ) -> Tuple[np.ndarray, bool]: """ Removes small disconnected regions and holes in a mask. Returns the mask and an indicator of if the mask has been modified. """ import cv2 # type: ignore assert mode in ["holes", "is...
Removes small disconnected regions and holes in a mask. Returns the mask and an indicator of if the mask has been modified.
remove_small_regions
python
FutureUniant/Tailor
app/src/algorithm/base/sam2/sam2/utils/amg.py
https://github.com/FutureUniant/Tailor/blob/master/app/src/algorithm/base/sam2/sam2/utils/amg.py
Apache-2.0
def batched_mask_to_box(masks: torch.Tensor) -> torch.Tensor: """ Calculates boxes in XYXY format around masks. Return [0,0,0,0] for an empty mask. For input shape C1xC2x...xHxW, the output shape is C1xC2x...x4. """ # torch.max below raises an error on empty inputs, just skip in this case if tor...
Calculates boxes in XYXY format around masks. Return [0,0,0,0] for an empty mask. For input shape C1xC2x...xHxW, the output shape is C1xC2x...x4.
batched_mask_to_box
python
FutureUniant/Tailor
app/src/algorithm/base/sam2/sam2/utils/amg.py
https://github.com/FutureUniant/Tailor/blob/master/app/src/algorithm/base/sam2/sam2/utils/amg.py
Apache-2.0
def mask_to_box(masks: torch.Tensor): """ compute bounding box given an input mask Inputs: - masks: [B, 1, H, W] masks, dtype=torch.Tensor Returns: - box_coords: [B, 1, 4], contains (x, y) coordinates of top left and bottom right box corners, dtype=torch.Tensor """ B, _, h, w = masks.s...
compute bounding box given an input mask Inputs: - masks: [B, 1, H, W] masks, dtype=torch.Tensor Returns: - box_coords: [B, 1, 4], contains (x, y) coordinates of top left and bottom right box corners, dtype=torch.Tensor
mask_to_box
python
FutureUniant/Tailor
app/src/algorithm/base/sam2/sam2/utils/misc.py
https://github.com/FutureUniant/Tailor/blob/master/app/src/algorithm/base/sam2/sam2/utils/misc.py
Apache-2.0
def load_video_frames( video_path, image_size, offload_video_to_cpu, img_mean=(0.485, 0.456, 0.406), img_std=(0.229, 0.224, 0.225), async_loading_frames=False, compute_device=torch.device("cuda"), ): """ Load the video frames from a directory of JPEG files ("<frame_index>.jpg" format...
Load the video frames from a directory of JPEG files ("<frame_index>.jpg" format). The frames are resized to image_size x image_size and are loaded to GPU if `offload_video_to_cpu` is `False` and to CPU if `offload_video_to_cpu` is `True`. You can load a frame asynchronously by setting `async_loading...
load_video_frames
python
FutureUniant/Tailor
app/src/algorithm/base/sam2/sam2/utils/misc.py
https://github.com/FutureUniant/Tailor/blob/master/app/src/algorithm/base/sam2/sam2/utils/misc.py
Apache-2.0
def fill_holes_in_mask_scores(mask, max_area): """ A post processor to fill small holes in mask scores with area under `max_area`. """ # Holes are those connected components in background with area <= self.max_area # (background regions are those with mask scores <= 0) assert max_area > 0, "max_...
A post processor to fill small holes in mask scores with area under `max_area`.
fill_holes_in_mask_scores
python
FutureUniant/Tailor
app/src/algorithm/base/sam2/sam2/utils/misc.py
https://github.com/FutureUniant/Tailor/blob/master/app/src/algorithm/base/sam2/sam2/utils/misc.py
Apache-2.0
def concat_points(old_point_inputs, new_points, new_labels): """Add new points and labels to previous point inputs (add at the end).""" if old_point_inputs is None: points, labels = new_points, new_labels else: points = torch.cat([old_point_inputs["point_coords"], new_points], dim=1) ...
Add new points and labels to previous point inputs (add at the end).
concat_points
python
FutureUniant/Tailor
app/src/algorithm/base/sam2/sam2/utils/misc.py
https://github.com/FutureUniant/Tailor/blob/master/app/src/algorithm/base/sam2/sam2/utils/misc.py
Apache-2.0
def transform_coords( self, coords: torch.Tensor, normalize=False, orig_hw=None ) -> torch.Tensor: """ Expects a torch tensor with length 2 in the last dimension. The coordinates can be in absolute image or normalized coordinates, If the coords are in absolute image coordinates, norm...
Expects a torch tensor with length 2 in the last dimension. The coordinates can be in absolute image or normalized coordinates, If the coords are in absolute image coordinates, normalize should be set to True and original image size is required. Returns Un-normalized coordinates in...
transform_coords
python
FutureUniant/Tailor
app/src/algorithm/base/sam2/sam2/utils/transforms.py
https://github.com/FutureUniant/Tailor/blob/master/app/src/algorithm/base/sam2/sam2/utils/transforms.py
Apache-2.0
def transform_boxes( self, boxes: torch.Tensor, normalize=False, orig_hw=None ) -> torch.Tensor: """ Expects a tensor of shape Bx4. The coordinates can be in absolute image or normalized coordinates, if the coords are in absolute image coordinates, normalize should be set to True and...
Expects a tensor of shape Bx4. The coordinates can be in absolute image or normalized coordinates, if the coords are in absolute image coordinates, normalize should be set to True and original image size is required.
transform_boxes
python
FutureUniant/Tailor
app/src/algorithm/base/sam2/sam2/utils/transforms.py
https://github.com/FutureUniant/Tailor/blob/master/app/src/algorithm/base/sam2/sam2/utils/transforms.py
Apache-2.0
def _extract_face(self, img, box, image_size, save_path=None): """ extract face :param img: A PIL Image. :param box: Four-element bounding box. :param image_size: raw image size :param save_path: Save path for extracted face image. (default: {None}) :return: ...
extract face :param img: A PIL Image. :param box: Four-element bounding box. :param image_size: raw image size :param save_path: Save path for extracted face image. (default: {None}) :return:
_extract_face
python
FutureUniant/Tailor
app/src/algorithm/video_cut_face/face_analysis.py
https://github.com/FutureUniant/Tailor/blob/master/app/src/algorithm/video_cut_face/face_analysis.py
Apache-2.0
def open_project(cls, tailor_path, **kwargs): """ :param tailor_path: :param kwargs save: Save specifically refers to saving project image, which also means opening the project for the first time project_image_path: When the proj...
:param tailor_path: :param kwargs save: Save specifically refers to saving project image, which also means opening the project for the first time project_image_path: When the project has been recorded in project_info table, ...
open_project
python
FutureUniant/Tailor
app/src/project/__init__.py
https://github.com/FutureUniant/Tailor/blob/master/app/src/project/__init__.py
Apache-2.0
def __init__( self, id=0, operation_id="", act_time=Timer.get_timestamp(integer=True, string=False), parameter=None, output=None, video=None, file=None, ): """ :param id: :param operation_id: ...
:param id: :param operation_id: :param act_time: :param parameter: :param output: :param video: :param file:
__init__
python
FutureUniant/Tailor
app/src/project/model/action.py
https://github.com/FutureUniant/Tailor/blob/master/app/src/project/model/action.py
Apache-2.0
def __init__( self, id=-1, name="", path="", sort=0, ): """ :param id: :param name: :param path: :param sort: """ self.id = id self.name = name self.path = path self.sort = so...
:param id: :param name: :param path: :param sort:
__init__
python
FutureUniant/Tailor
app/src/project/model/video.py
https://github.com/FutureUniant/Tailor/blob/master/app/src/project/model/video.py
Apache-2.0
def compare_images(image1_path, image2_path): """ :param image1_path: :param image2_path: :return: 0 : image1 and image2 are normal, but different 1 : image1 and image2 are normal, and same -1 : image1 is damaged -2 : image2 is damaged -3 : ...
:param image1_path: :param image2_path: :return: 0 : image1 and image2 are normal, but different 1 : image1 and image2 are normal, and same -1 : image1 is damaged -2 : image2 is damaged -3 : image1 and image2 are all damaged
compare_images
python
FutureUniant/Tailor
app/src/utils/imager.py
https://github.com/FutureUniant/Tailor/blob/master/app/src/utils/imager.py
Apache-2.0
def write_log(self, content, log_level=logging.INFO): """ :param content: The format specification of the content : type: total stage: current stage: total step: current step: remark type: interval: No actual progress, simulate progre...
:param content: The format specification of the content : type: total stage: current stage: total step: current step: remark type: interval: No actual progress, simulate progress based on time intervals. When it...
write_log
python
FutureUniant/Tailor
app/src/utils/logger.py
https://github.com/FutureUniant/Tailor/blob/master/app/src/utils/logger.py
Apache-2.0
def register(self, target=None, name=None, force=False): """Register a module. A record will be added to `self._module_dict`, whose key is the class name or the specified name, and value is the class itself. It can be used as a decorator or a normal function. Args: ...
Register a module. A record will be added to `self._module_dict`, whose key is the class name or the specified name, and value is the class itself. It can be used as a decorator or a normal function. Args: target (callable| class | None): The target for register. ...
register
python
FutureUniant/Tailor
app/src/utils/register.py
https://github.com/FutureUniant/Tailor/blob/master/app/src/utils/register.py
Apache-2.0
def _create_bindings(self, sequence: Optional[str] = None): """ set necessary bindings for functionality of widget, will overwrite other bindings """ if sequence is None or sequence == "<Enter>": self._canvas.bind("<Enter>", self._on_enter) self._text_label.bind("<Enter>", self._...
set necessary bindings for functionality of widget, will overwrite other bindings
_create_bindings
python
FutureUniant/Tailor
app/tailorwidgets/tailor_menu_bar.py
https://github.com/FutureUniant/Tailor/blob/master/app/tailorwidgets/tailor_menu_bar.py
Apache-2.0
def _update_font(self): """ pass font to tkinter widgets with applied font scaling and update grid with workaround """ self._text_label.configure(font=self._apply_font_scaling(self._font)) # Workaround to force grid to be resized when text changes size. # Otherwise grid will lag and onl...
pass font to tkinter widgets with applied font scaling and update grid with workaround
_update_font
python
FutureUniant/Tailor
app/tailorwidgets/tailor_menu_bar.py
https://github.com/FutureUniant/Tailor/blob/master/app/tailorwidgets/tailor_menu_bar.py
Apache-2.0
def unbind(self, sequence: str = None, funcid: str = None): """ called on the tkinter.Label and tkinter.Canvas """ if funcid is not None: raise ValueError("'funcid' argument can only be None, because there is a bug in" + " tkinter and its not clear whether the in...
called on the tkinter.Label and tkinter.Canvas
unbind
python
FutureUniant/Tailor
app/tailorwidgets/tailor_menu_bar.py
https://github.com/FutureUniant/Tailor/blob/master/app/tailorwidgets/tailor_menu_bar.py
Apache-2.0
def __init__(self, master: any, values: List, fg_color: Optional[Union[str, Tuple[str, str]]] = None, text_color: Optional[Union[str, Tuple[str, str]]] = None, button_fg_color: Optional[Union[str, Tuple[str, str]]] = None, ...
:param master: :param values: example: [{ "text": "The first multiple choice question", "options": [(key: which is for showing, val: which is for app using)] }...{}] :param fg_color: ...
__init__
python
FutureUniant/Tailor
app/tailorwidgets/tailor_multi_radios_dialog.py
https://github.com/FutureUniant/Tailor/blob/master/app/tailorwidgets/tailor_multi_radios_dialog.py
Apache-2.0
def update_data(self): """ update the data when values are changes """ for i in self.frame: if self.checkbox and i[1] == 0: continue if self.write: self.data[i]["value"] = self.frame[i].get() else: self.data[i]["value"] ...
update the data when values are changes
update_data
python
FutureUniant/Tailor
app/tailorwidgets/tailor_table.py
https://github.com/FutureUniant/Tailor/blob/master/app/tailorwidgets/tailor_table.py
Apache-2.0
def edit_row(self, row, value=None, **kwargs): """ edit all parameters of a single row """ start_idx = 0 if self.checkbox: start_idx = 1 for i in range(start_idx, self.real_columns): self.frame[row, i].configure(**kwargs) self.data[row, i]["args"].upda...
edit all parameters of a single row
edit_row
python
FutureUniant/Tailor
app/tailorwidgets/tailor_table.py
https://github.com/FutureUniant/Tailor/blob/master/app/tailorwidgets/tailor_table.py
Apache-2.0
def edit_column(self, column, value=None, **kwargs): """ edit all parameters of a single column """ for i in range(self.rows): self.frame[i, column].configure(**kwargs) self.data[i, column]["args"].update(kwargs) if value: self.insert(i, column, value)...
edit all parameters of a single column
edit_column
python
FutureUniant/Tailor
app/tailorwidgets/tailor_table.py
https://github.com/FutureUniant/Tailor/blob/master/app/tailorwidgets/tailor_table.py
Apache-2.0
def insert(self, row, column, value, **kwargs): """ insert value in a specific block [row, column] """ if self.write: self.frame[row, column].delete(0, END) self.frame[row, column].insert(0, value) self.frame[row, column].configure(**kwargs) else: ...
insert value in a specific block [row, column]
insert
python
FutureUniant/Tailor
app/tailorwidgets/tailor_table.py
https://github.com/FutureUniant/Tailor/blob/master/app/tailorwidgets/tailor_table.py
Apache-2.0
def delete(self, row, column, **kwargs): """ delete a value from a specific block [row, column] """ if self.write: self.frame[row, column].delete(0, END) self.frame[row, column].configure(**kwargs) else: self.frame[row, column].configure(text="", **kwargs) ...
delete a value from a specific block [row, column]
delete
python
FutureUniant/Tailor
app/tailorwidgets/tailor_table.py
https://github.com/FutureUniant/Tailor/blob/master/app/tailorwidgets/tailor_table.py
Apache-2.0
def _detect_color_of_master(self, master_widget=None) -> Union[str, Tuple[str, str]]: """ detect foreground color of master widget for bg_color and transparent color """ if master_widget is None: master_widget = self.master if isinstance(master_widget, (windows.widgets.core_widget_...
detect foreground color of master widget for bg_color and transparent color
_detect_color_of_master
python
FutureUniant/Tailor
app/tailorwidgets/tailor_tree_view.py
https://github.com/FutureUniant/Tailor/blob/master/app/tailorwidgets/tailor_tree_view.py
Apache-2.0
def _check_font_type(self, font: any): """ check font type when passed to widget """ if isinstance(font, CTkFont): return font elif type(font) == tuple and len(font) == 1: warnings.warn(f"{type(self).__name__} Warning: font {font} given without size, will be extended wit...
check font type when passed to widget
_check_font_type
python
FutureUniant/Tailor
app/tailorwidgets/tailor_tree_view.py
https://github.com/FutureUniant/Tailor/blob/master/app/tailorwidgets/tailor_tree_view.py
Apache-2.0
def _async_raise(tid, exctype): """raises the exception, performs cleanup if needed""" tid = ctypes.c_long(tid) if not inspect.isclass(exctype): exctype = type(exctype) res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exctype)) if res == 0: raise ValueError("inv...
raises the exception, performs cleanup if needed
_async_raise
python
FutureUniant/Tailor
app/tailorwidgets/tailor_video_player.py
https://github.com/FutureUniant/Tailor/blob/master/app/tailorwidgets/tailor_video_player.py
Apache-2.0
def decode(self, samples, images, sd_version: str, sub_batch_size: int): """ sub_batch_size: How many images to decode in a single pass. See https://github.com/huchenlei/ComfyUI-layerdiffuse/pull/4 for more context. """ sd_version = StableDiffusionVersion(sd_version) ...
sub_batch_size: How many images to decode in a single pass. See https://github.com/huchenlei/ComfyUI-layerdiffuse/pull/4 for more context.
decode
python
huchenlei/ComfyUI-layerdiffuse
layered_diffusion.py
https://github.com/huchenlei/ComfyUI-layerdiffuse/blob/master/layered_diffusion.py
Apache-2.0
def load_file_from_url( url: str, *, model_dir: str, progress: bool = True, file_name: Optional[str] = None, ) -> str: """Download a file from `url` into `model_dir`, using the file present if possible. Returns the path to the downloaded file. """ os.makedirs(model_dir, exist_ok=Tru...
Download a file from `url` into `model_dir`, using the file present if possible. Returns the path to the downloaded file.
load_file_from_url
python
huchenlei/ComfyUI-layerdiffuse
lib_layerdiffusion/utils.py
https://github.com/huchenlei/ComfyUI-layerdiffuse/blob/master/lib_layerdiffusion/utils.py
Apache-2.0
def to_lora_patch_dict(state_dict: dict) -> dict: """ Convert raw lora state_dict to patch_dict that can be applied on modelpatcher.""" patch_dict = {} for k, w in state_dict.items(): model_key, patch_type, weight_index = k.split('::') if model_key not in patch_dict: patch_di...
Convert raw lora state_dict to patch_dict that can be applied on modelpatcher.
to_lora_patch_dict
python
huchenlei/ComfyUI-layerdiffuse
lib_layerdiffusion/utils.py
https://github.com/huchenlei/ComfyUI-layerdiffuse/blob/master/lib_layerdiffusion/utils.py
Apache-2.0
def copy( doc_links_config: Path = typer.Argument(..., help="Path to the doc links config"), absolute_paths: bool = typer.Option( False, help="Whether to use absolute paths for the source files" ), ): """Copy documentation files as specified in the doc links config. This function reads the ...
Copy documentation files as specified in the doc links config. This function reads the doc links configuration file and copies the specified files from their source locations to the destination paths. It can handle both relative and absolute paths based on the `absolute_paths` parameter. Args: ...
copy
python
oumi-ai/oumi
docs/_manage_doclinks.py
https://github.com/oumi-ai/oumi/blob/master/docs/_manage_doclinks.py
Apache-2.0
def clean( doc_links_config: Path = typer.Argument(..., help="Path to the doc links config"), absolute_paths: bool = typer.Option( False, help="Whether to use absolute paths for the destination files" ), ): """Delete destination files specified in the doc links config. This function reads t...
Delete destination files specified in the doc links config. This function reads the doc links configuration file and deletes the specified destination files. It can handle both relative and absolute paths based on the `absolute_paths` parameter. Args: doc_links_config (Path): Path to the doc l...
clean
python
oumi-ai/oumi
docs/_manage_doclinks.py
https://github.com/oumi-ai/oumi/blob/master/docs/_manage_doclinks.py
Apache-2.0
def summarize_module( module_name: str = typer.Argument(..., help="The name of the module to inspect"), filter_type: Optional[list[str]] = typer.Option( None, help="Filter for object types (class, method, attribute, function)" ), output_file: Optional[str] = typer.Option( None, help="Fil...
Generate a markdown table of objects defined in a Python module. Args: module_name: The name of the module to inspect. filter_type: Optional filter for object types. Can be 'class', 'method', 'attribute', 'function', or a list of these. output_file: Optional file path to save th...
summarize_module
python
oumi-ai/oumi
docs/_summarize_module.py
https://github.com/oumi-ai/oumi/blob/master/docs/_summarize_module.py
Apache-2.0
def summarize_configs( config_folder: str = typer.Argument(..., help="The folder containing config files"), config_class: str = typer.Argument( ..., help="The class to instantiate configs (format: module.ClassName)" ), output_file: Optional[str] = typer.Option( None, help="File path to s...
Generate a markdown table summarizing config files in a folder. Args: config_folder: The folder containing config files. config_class: The class to instantiate configs (format: module.ClassName). output_file: Optional file path to save the generated markdown. Returns: A string ...
summarize_configs
python
oumi-ai/oumi
docs/_summarize_module.py
https://github.com/oumi-ai/oumi/blob/master/docs/_summarize_module.py
Apache-2.0
def _get_object_docstring(obj, summary: bool = True) -> str: """Get the docstring of an object.""" docstring = inspect.getdoc(obj) or "No description available" if summary: return docstring.split("\n")[0] return docstring
Get the docstring of an object.
_get_object_docstring
python
oumi-ai/oumi
docs/_summarize_module.py
https://github.com/oumi-ai/oumi/blob/master/docs/_summarize_module.py
Apache-2.0
def _get_object_type(obj) -> str: """Get the type of an object.""" if inspect.isclass(obj): return "class" elif inspect.isfunction(obj): return "function" elif inspect.ismodule(obj): return "module" elif isinstance(obj, property): return "property" elif inspect.is...
Get the type of an object.
_get_object_type
python
oumi-ai/oumi
docs/_summarize_module.py
https://github.com/oumi-ai/oumi/blob/master/docs/_summarize_module.py
Apache-2.0
def _is_child_of(obj, parent_class) -> bool: """Check if an object is a child of a parent class.""" return ( inspect.isclass(obj) and issubclass(obj, parent_class) and obj != parent_class )
Check if an object is a child of a parent class.
_is_child_of
python
oumi-ai/oumi
docs/_summarize_module.py
https://github.com/oumi-ai/oumi/blob/master/docs/_summarize_module.py
Apache-2.0
def _is_defined_in_module(obj, module): """Check if an object is defined in the given module.""" try: return inspect.getmodule(obj) == module except AttributeError: # Some objects might not have a module, assume they're not defined in the module return False
Check if an object is defined in the given module.
_is_defined_in_module
python
oumi-ai/oumi
docs/_summarize_module.py
https://github.com/oumi-ai/oumi/blob/master/docs/_summarize_module.py
Apache-2.0
def show_logo(): """Display the Oumi platform logo in a panel.""" logo_text = r""" ____ _ _ __ __ _____ / __ \| | | | \/ |_ _| | | | | | | | \ / | | | | | | | | | | |\/| | | | | |__| | |__| | | | |_| |_ \____/ \____/|_| |_|_____|""" tagline = ( "Everything you need to bui...
Display the Oumi platform logo in a panel.
show_logo
python
oumi-ai/oumi
scripts/demo.py
https://github.com/oumi-ai/oumi/blob/master/scripts/demo.py
Apache-2.0
def display_yaml_config(config: dict, title: str = "Configuration"): """Display a YAML configuration in a panel with syntax highlighting. Args: config: The configuration dictionary to display title: The title for the panel """ yaml_str = yaml.dump(config) console.print( Pane...
Display a YAML configuration in a panel with syntax highlighting. Args: config: The configuration dictionary to display title: The title for the panel
display_yaml_config
python
oumi-ai/oumi
scripts/demo.py
https://github.com/oumi-ai/oumi/blob/master/scripts/demo.py
Apache-2.0
def run_command( command: str, capture_output: bool = False ) -> subprocess.CompletedProcess: """Run a shell command and return the result. Args: command: The command to run capture_output: Whether to capture the command output Returns: The completed process object """ ...
Run a shell command and return the result. Args: command: The command to run capture_output: Whether to capture the command output Returns: The completed process object
run_command
python
oumi-ai/oumi
scripts/demo.py
https://github.com/oumi-ai/oumi/blob/master/scripts/demo.py
Apache-2.0
def select_from_choices( prompt: str, choices: list[dict[str, str]], default: str = "1", show_descriptions: bool = True, ) -> tuple[str, str]: """Display numbered choices and get user selection. Args: prompt: The prompt to display to the user choices: List of choice dictionaries...
Display numbered choices and get user selection. Args: prompt: The prompt to display to the user choices: List of choice dictionaries with name, description (optional), and value, or dictionary of choice descriptions to values, or list of choices default: Default choice numb...
select_from_choices
python
oumi-ai/oumi
scripts/demo.py
https://github.com/oumi-ai/oumi/blob/master/scripts/demo.py
Apache-2.0
def num_bytes_to_str(bytes: Union[int, float]) -> str: """Returns a human-readable string for a number of bytes.""" if bytes < 1000: return f"{bytes} B" elif bytes < 1e6: return f"{bytes / 1000:.1f} KB" elif bytes < 1e9: return f"{bytes / 1e6:.1f} MB" else: return f"{...
Returns a human-readable string for a number of bytes.
num_bytes_to_str
python
oumi-ai/oumi
scripts/memcalc.py
https://github.com/oumi-ai/oumi/blob/master/scripts/memcalc.py
Apache-2.0
def get_seq_len(config: TrainingConfig, model_config: ModelConfig) -> int: """Gets the maximum sequence length supported by the model.""" seq_len = model_config.seq_len if config.model.model_max_length is not None: seq_len = config.model.model_max_length return seq_len
Gets the maximum sequence length supported by the model.
get_seq_len
python
oumi-ai/oumi
scripts/memcalc.py
https://github.com/oumi-ai/oumi/blob/master/scripts/memcalc.py
Apache-2.0
def get_standardized_model_config(hf_model_config) -> ModelConfig: """Gets a standardized model config given a HF model config. Each HF config may use different field names for the same property. This function converts them to a standardized format for use throughout the script. """ if isinstance(h...
Gets a standardized model config given a HF model config. Each HF config may use different field names for the same property. This function converts them to a standardized format for use throughout the script.
get_standardized_model_config
python
oumi-ai/oumi
scripts/memcalc.py
https://github.com/oumi-ai/oumi/blob/master/scripts/memcalc.py
Apache-2.0
def get_data_bytes( config: TrainingConfig, model_config: ModelConfig, bytes_per_unit: int ) -> int: """Gets the total number of bytes used by the data batch.""" batch_size = config.training.per_device_train_batch_size model_max_length = get_seq_len(config, model_config) return batch_size * model_ma...
Gets the total number of bytes used by the data batch.
get_data_bytes
python
oumi-ai/oumi
scripts/memcalc.py
https://github.com/oumi-ai/oumi/blob/master/scripts/memcalc.py
Apache-2.0
def get_model_bytes(model: torch.nn.Module, bytes_per_unit: int) -> int: """Gets the total number of bytes used by the loaded model.""" num_total_params = count_model_parameters(model).all_params print(f"- Model parameter count: {num_total_params:,}") return num_total_params * bytes_per_unit
Gets the total number of bytes used by the loaded model.
get_model_bytes
python
oumi-ai/oumi
scripts/memcalc.py
https://github.com/oumi-ai/oumi/blob/master/scripts/memcalc.py
Apache-2.0
def get_optim_bytes(config: TrainingConfig, model_bytes: int) -> int: """Gets the total number of bytes used by the optimizer.""" optim = config.training.optimizer if optim in ["adamw_torch", "adamw_torch_fused"]: multiplier = 2 elif optim == "adafactor": multiplier = 0.3 elif optim ...
Gets the total number of bytes used by the optimizer.
get_optim_bytes
python
oumi-ai/oumi
scripts/memcalc.py
https://github.com/oumi-ai/oumi/blob/master/scripts/memcalc.py
Apache-2.0
def get_gradient_bytes(config: TrainingConfig, model_bytes: int) -> int: """Gets the total number of bytes used by gradients.""" print("- The size of the gradient is the same as that for model weights.") if config.training.gradient_accumulation_steps > 1: print( "- If gradient accumulati...
Gets the total number of bytes used by gradients.
get_gradient_bytes
python
oumi-ai/oumi
scripts/memcalc.py
https://github.com/oumi-ai/oumi/blob/master/scripts/memcalc.py
Apache-2.0
def get_activation_bytes( config: TrainingConfig, model_config: ModelConfig, bytes_per_unit: int ) -> int: """Gets the total number of bytes used by activations.""" vocab_size = model_config.vocab_size num_layers = model_config.num_layers hidden_dim = model_config.hidden_dim seq_len = get_seq_le...
Gets the total number of bytes used by activations.
get_activation_bytes
python
oumi-ai/oumi
scripts/memcalc.py
https://github.com/oumi-ai/oumi/blob/master/scripts/memcalc.py
Apache-2.0
def main(args): """Runs the DataLoader benchmark in distributed mode.""" if is_distributed(): logger.info("Benchmarking in distributed mode...") init_distributed() else: logger.info("Running benchmark in single-process mode.") # # Run benchmarks # all_results = [] ...
Runs the DataLoader benchmark in distributed mode.
main
python
oumi-ai/oumi
scripts/benchmarks/benchmark_dataloader.py
https://github.com/oumi-ai/oumi/blob/master/scripts/benchmarks/benchmark_dataloader.py
Apache-2.0
def _generate_config_combinations( variable_params: dict[str, list[Any]], ) -> list[dict[str, Any]]: """Generates a list of configs based on a list of variable parameters.""" keys, values = zip(*variable_params.items()) configurations = [dict(zip(keys, v)) for v in itertools.product(*values)] return...
Generates a list of configs based on a list of variable parameters.
_generate_config_combinations
python
oumi-ai/oumi
scripts/benchmarks/benchmark_dataloader.py
https://github.com/oumi-ai/oumi/blob/master/scripts/benchmarks/benchmark_dataloader.py
Apache-2.0
def _load_dataset(dataset_fn, *args, **kwargs) -> tuple[float, Any]: """Measures the time taken to initialize a dataset using the given dataset function. Parameters: dataset_fn (callable): The function used to create the dataset. *args: Variable length argument list to be passed to the dataset ...
Measures the time taken to initialize a dataset using the given dataset function. Parameters: dataset_fn (callable): The function used to create the dataset. *args: Variable length argument list to be passed to the dataset function. **kwargs: Arbitrary keyword arguments to be passed to the ...
_load_dataset
python
oumi-ai/oumi
scripts/benchmarks/benchmark_dataloader.py
https://github.com/oumi-ai/oumi/blob/master/scripts/benchmarks/benchmark_dataloader.py
Apache-2.0
def _benchmark_dataloader_epoch( dataset, batch_size: int = 1, num_dataloader_workers: int = 0, pin_memory: bool = False, model_fwd_bwd_ms: float = 0.0, use_distributed_sampler: bool = False, max_steps: Optional[int] = None, **kwargs, ) -> dict[str, Any]: """Measures the time taken t...
Measures the time taken to iterate over a DataLoader for one epoch.
_benchmark_dataloader_epoch
python
oumi-ai/oumi
scripts/benchmarks/benchmark_dataloader.py
https://github.com/oumi-ai/oumi/blob/master/scripts/benchmarks/benchmark_dataloader.py
Apache-2.0
def benchmark_barrier(device_info, num_iterations: int = 1): """Benchmarks the time taken to execute a barrier operation.""" start_time = time.perf_counter() sleep_time_seconds = 1 for _ in range(num_iterations): barrier() time.sleep(sleep_time_seconds) end_time = time.perf_counter()...
Benchmarks the time taken to execute a barrier operation.
benchmark_barrier
python
oumi-ai/oumi
scripts/benchmarks/benchmark_nccl.py
https://github.com/oumi-ai/oumi/blob/master/scripts/benchmarks/benchmark_nccl.py
Apache-2.0
def benchmark_ddp(device_info, num_iterations: int = 1): """Benchmarks the time taken to execute a forward and backward pass with DDP.""" rank = device_info.local_rank device = f"cuda:{rank}" model = MLPEncoder().to(device) ddp_model = DDP(model, device_ids=[rank]) optimizer = torch.optim.SGD(...
Benchmarks the time taken to execute a forward and backward pass with DDP.
benchmark_ddp
python
oumi-ai/oumi
scripts/benchmarks/benchmark_nccl.py
https://github.com/oumi-ai/oumi/blob/master/scripts/benchmarks/benchmark_nccl.py
Apache-2.0
def benchmark_all_reduce(device_info, num_iterations: int = 1, tensor_size=1000000): """Benchmarks the time taken to execute an all-reduce operation.""" tensor = torch.randn(tensor_size).to(device_info.local_rank) start_time = time.time() for _ in range(num_iterations): dist.all_reduce(tensor, ...
Benchmarks the time taken to execute an all-reduce operation.
benchmark_all_reduce
python
oumi-ai/oumi
scripts/benchmarks/benchmark_nccl.py
https://github.com/oumi-ai/oumi/blob/master/scripts/benchmarks/benchmark_nccl.py
Apache-2.0
def main(args): """Main function for the benchmark script.""" if is_distributed(): logger.info("Benchmarking in distributed mode...") init_distributed() else: logger.info("Running benchmark in single-process mode.") # # Run tests # device_info = get_device_rank_info(...
Main function for the benchmark script.
main
python
oumi-ai/oumi
scripts/benchmarks/benchmark_nccl.py
https://github.com/oumi-ai/oumi/blob/master/scripts/benchmarks/benchmark_nccl.py
Apache-2.0
def _load_sft_dataset( dataset_name: str, *, dataset_path: Optional[str], dataset_subset: Optional[str], dataset_split: Optional[str], tokenizer: Optional[BaseTokenizer] = None, processor_name: Optional[str] = None, trust_remote_code: bool = False, dataset_kwargs: Optional[dict[str, ...
Loads a custom SFT dataset with the specified name and subset.
_load_sft_dataset
python
oumi-ai/oumi
scripts/datasets/save_conversations.py
https://github.com/oumi-ai/oumi/blob/master/scripts/datasets/save_conversations.py
Apache-2.0
def parse_cli() -> tuple[ParsedArgs, list[str]]: """Parses command line arguments and returns the configuration filename.""" parser = argparse.ArgumentParser() parser.add_argument( "-c", "--config", default=None, help="Path to the configuration file", ) parser.add_arg...
Parses command line arguments and returns the configuration filename.
parse_cli
python
oumi-ai/oumi
scripts/datasets/pretokenize/process_dataset.py
https://github.com/oumi-ai/oumi/blob/master/scripts/datasets/pretokenize/process_dataset.py
Apache-2.0
def save_conversations_for_dataset( output_path: str, dataset_name="yahma/alpaca-cleaned", num_samples: int = 10 ): """Save the conversations to a file. Args: output_path (str): The path to save the conversations. dataset_name (str): The name of the dataset to use. num_samples (int)...
Save the conversations to a file. Args: output_path (str): The path to save the conversations. dataset_name (str): The name of the dataset to use. num_samples (int): The number of samples to save.
save_conversations_for_dataset
python
oumi-ai/oumi
scripts/examples/batch_inference/bulk_infer.py
https://github.com/oumi-ai/oumi/blob/master/scripts/examples/batch_inference/bulk_infer.py
Apache-2.0
def compare_predictions(prediction_files: list[str], idx: int): """Compares the predictions from different files at a given index. Args: prediction_files (list[str]): The paths to the prediction files. idx (int): The index of the prediction to compare. """ for target_file in prediction_...
Compares the predictions from different files at a given index. Args: prediction_files (list[str]): The paths to the prediction files. idx (int): The index of the prediction to compare.
compare_predictions
python
oumi-ai/oumi
scripts/examples/batch_inference/bulk_infer.py
https://github.com/oumi-ai/oumi/blob/master/scripts/examples/batch_inference/bulk_infer.py
Apache-2.0
def _read_line(file_path: str, idx: int) -> str: """Reads a single line from a file as a raw string.""" with open(file_path) as f: for i, line in enumerate(f): if i == idx: return line raise RuntimeError(f"Index out of range: {idx}")
Reads a single line from a file as a raw string.
_read_line
python
oumi-ai/oumi
scripts/examples/batch_inference/bulk_infer.py
https://github.com/oumi-ai/oumi/blob/master/scripts/examples/batch_inference/bulk_infer.py
Apache-2.0
def run_batch(file_path: str) -> str: """Runs batch prediction on the conversations in `file_path`. Args: file_path (str): the path to a jsonl file of conversations. Returns: str: the id of the batch job. """ config = InferenceConfig( model=ModelParams(model_name="gpt-4o-mi...
Runs batch prediction on the conversations in `file_path`. Args: file_path (str): the path to a jsonl file of conversations. Returns: str: the id of the batch job.
run_batch
python
oumi-ai/oumi
scripts/examples/batch_inference/bulk_infer.py
https://github.com/oumi-ai/oumi/blob/master/scripts/examples/batch_inference/bulk_infer.py
Apache-2.0
def _load_dataset(num_examples: Optional[int]) -> TextSftJsonLinesDataset: """Load the facebook/anli dataset, formatted as a classification problem.""" anli_dataset = datasets.load_dataset("facebook/anli", split="test_r3") evaluation_dataset = [] for anli_example in anli_dataset: assert isinstan...
Load the facebook/anli dataset, formatted as a classification problem.
_load_dataset
python
oumi-ai/oumi
scripts/examples/evaluation/custom_evaluation.py
https://github.com/oumi-ai/oumi/blob/master/scripts/examples/evaluation/custom_evaluation.py
Apache-2.0
def _extract_prediction(response: str) -> int: """Converts a response to a label: [0, 1], or -1 if inconclusive.""" is_unsupported = "<|unsupported|>" in response is_supported = "<|supported|>" in response if is_unsupported == is_supported: return -1 return 0 if is_supported else 1
Converts a response to a label: [0, 1], or -1 if inconclusive.
_extract_prediction
python
oumi-ai/oumi
scripts/examples/evaluation/custom_evaluation.py
https://github.com/oumi-ai/oumi/blob/master/scripts/examples/evaluation/custom_evaluation.py
Apache-2.0
def get_new_inputs(source: str, processed: str) -> list[str]: """Returns a list of new files in the source directory.""" source_filenames = {f.name for f in Path(source).rglob("*")} processed_filenames = {f.name for f in Path(processed).rglob("*")} return list(source_filenames - processed_filenames)
Returns a list of new files in the source directory.
get_new_inputs
python
oumi-ai/oumi
scripts/inference/gcp_inference.py
https://github.com/oumi-ai/oumi/blob/master/scripts/inference/gcp_inference.py
Apache-2.0
def main(): """Runs inference on new files in the input directory.""" parallelism = 1 if len(sys.argv) > 1: parallelism = int(sys.argv[1]) os.environ["VLLM_WORKER_MULTIPROC_METHOD"] = "spawn" print("Checking for new files...") new_files = get_new_inputs(_INPUT_DIR, _OUTPUT_DIR) yaml_...
Runs inference on new files in the input directory.
main
python
oumi-ai/oumi
scripts/inference/gcp_inference.py
https://github.com/oumi-ai/oumi/blob/master/scripts/inference/gcp_inference.py
Apache-2.0
def main() -> None: """Run inference against vLLM model hosted as an OpenAI API.""" openai_api_key = "EMPTY" IP = os.environ["THIS_IP_ADDRESS"] openai_api_base = f"http://{IP}:8000/v1" client = OpenAI( # defaults to os.environ.get("OPENAI_API_KEY") api_key=openai_api_key, bas...
Run inference against vLLM model hosted as an OpenAI API.
main
python
oumi-ai/oumi
scripts/polaris/jobs/python/vllm_inference.py
https://github.com/oumi-ai/oumi/blob/master/scripts/polaris/jobs/python/vllm_inference.py
Apache-2.0
def main(): """Run parallelized inference against a vLLM server.""" locust.log.setup_logging("INFO") random.seed(RANDOM_SEED) IP = os.environ["THIS_IP_ADDRESS"] openai_api_base = f"http://{IP}:8000/v1" client = OpenAI( base_url=openai_api_base, ) models = client.models.list() ...
Run parallelized inference against a vLLM server.
main
python
oumi-ai/oumi
scripts/polaris/jobs/python/vllm_parallel_inference.py
https://github.com/oumi-ai/oumi/blob/master/scripts/polaris/jobs/python/vllm_parallel_inference.py
Apache-2.0
def run_inference(self): """Runs inference by pulling indices from queue shared by all workers.""" global output_queue global input_queue global REQUEST_TIMES global failed_request_counts while True: index = input_queue.get() ...
Runs inference by pulling indices from queue shared by all workers.
run_inference
python
oumi-ai/oumi
scripts/polaris/jobs/python/vllm_parallel_inference.py
https://github.com/oumi-ai/oumi/blob/master/scripts/polaris/jobs/python/vllm_parallel_inference.py
Apache-2.0
def evaluate(config: EvaluationConfig) -> list[dict[str, Any]]: """Evaluates a model using the provided configuration. Args: config: The desired configuration for evaluation. Returns: A list of evaluation results (one for each task). Each evaluation result is a dictionary of metric...
Evaluates a model using the provided configuration. Args: config: The desired configuration for evaluation. Returns: A list of evaluation results (one for each task). Each evaluation result is a dictionary of metric names and their corresponding values.
evaluate
python
oumi-ai/oumi
src/oumi/evaluate.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/evaluate.py
Apache-2.0
def parse_cli(): """Parses command line arguments and return the configuration filename.""" parser = argparse.ArgumentParser() parser.add_argument( "-c", "--config", default=None, help="Path to the configuration file" ) args, arg_list = parser.parse_known_args() return args.config, arg_l...
Parses command line arguments and return the configuration filename.
parse_cli
python
oumi-ai/oumi
src/oumi/evaluate_async.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/evaluate_async.py
Apache-2.0
def main() -> None: """Main entry point for running aynsc Oumi evals. Evaluation arguments are fetched from the following sources, ordered by decreasing priority: 1. [Optional] Arguments provided as CLI arguments, in dotfile format 2. [Optional] Arguments provided in a yaml config file 3. Defau...
Main entry point for running aynsc Oumi evals. Evaluation arguments are fetched from the following sources, ordered by decreasing priority: 1. [Optional] Arguments provided as CLI arguments, in dotfile format 2. [Optional] Arguments provided in a yaml config file 3. Default arguments values defined...
main
python
oumi-ai/oumi
src/oumi/evaluate_async.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/evaluate_async.py
Apache-2.0
def _get_checkpoints(checkpoint_dir: Path) -> list[Path]: """Returns all checkpoints in the target directory.""" # Modified from HF's transformers.trainer_utils.get_last_checkpoint(). re_checkpoint = re.compile(r"^" + _PREFIX_CHECKPOINT_DIR + r"\-(\d+)$") return [ path for path in checkp...
Returns all checkpoints in the target directory.
_get_checkpoints
python
oumi-ai/oumi
src/oumi/evaluate_async.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/evaluate_async.py
Apache-2.0
def evaluate_async(config: AsyncEvaluationConfig) -> None: """Runs an async evaluation for a model using the provided configuration. Overview: This is a utility method for running evaluations iteratively over a series of checkpoints. This method can be run in parallel with a training job to ...
Runs an async evaluation for a model using the provided configuration. Overview: This is a utility method for running evaluations iteratively over a series of checkpoints. This method can be run in parallel with a training job to compute metrics per checkpoint without wasting valuable time ...
evaluate_async
python
oumi-ai/oumi
src/oumi/evaluate_async.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/evaluate_async.py
Apache-2.0
def _get_engine(config: InferenceConfig) -> BaseInferenceEngine: """Returns the inference engine based on the provided config.""" if config.engine is None: logger.warning( "No inference engine specified. Using the default 'native' engine." ) return build_inference_engine( ...
Returns the inference engine based on the provided config.
_get_engine
python
oumi-ai/oumi
src/oumi/infer.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/infer.py
Apache-2.0
def infer_interactive( config: InferenceConfig, *, input_image_bytes: Optional[list[bytes]] = None, system_prompt: Optional[str] = None, ) -> None: """Interactively provide the model response for a user-provided input.""" # Create engine up front to avoid reinitializing it for each input. in...
Interactively provide the model response for a user-provided input.
infer_interactive
python
oumi-ai/oumi
src/oumi/infer.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/infer.py
Apache-2.0
def infer( config: InferenceConfig, inputs: Optional[list[str]] = None, inference_engine: Optional[BaseInferenceEngine] = None, *, input_image_bytes: Optional[list[bytes]] = None, system_prompt: Optional[str] = None, ) -> list[Conversation]: """Runs batch inference for a model using the prov...
Runs batch inference for a model using the provided configuration. Args: config: The configuration to use for inference. inputs: A list of inputs for inference. inference_engine: The engine to use for inference. If unspecified, the engine will be inferred from `config`. ...
infer
python
oumi-ai/oumi
src/oumi/infer.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/infer.py
Apache-2.0
def judge_dataset(config: JudgeConfig, dataset: BaseSftDataset) -> list[dict[str, Any]]: """Judge a dataset. This function evaluates a given dataset using a specified Judge configuration. The function performs the following steps: 1. Initializes the Judge with the provided configuration. ...
Judge a dataset. This function evaluates a given dataset using a specified Judge configuration. The function performs the following steps: 1. Initializes the Judge with the provided configuration. 2. Iterates through the dataset to extract conversation inputs. 3. Uses the Judge to eva...
judge_dataset
python
oumi-ai/oumi
src/oumi/judge.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/judge.py
Apache-2.0
def judge_conversations( config: JudgeConfig, judge_inputs: list[Conversation] ) -> list[dict[str, Any]]: """Judge a list of conversations. This function evaluates a list of conversations using the specified Judge. The function performs the following steps: 1. Initializes the Judge with the p...
Judge a list of conversations. This function evaluates a list of conversations using the specified Judge. The function performs the following steps: 1. Initializes the Judge with the provided configuration. 2. Uses the Judge to evaluate each conversation input. 3. Collects and returns...
judge_conversations
python
oumi-ai/oumi
src/oumi/judge.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/judge.py
Apache-2.0
def _find_checkpoint_to_resume_from( resume_from_checkpoint: Optional[str], try_resume_from_last_checkpoint: bool, output_dir: str, ) -> Optional[str]: """Finds and returns the last checkpoint path to be passed to Trainer.""" checkpoint_path = None if resume_from_checkpoint: checkpoint_p...
Finds and returns the last checkpoint path to be passed to Trainer.
_find_checkpoint_to_resume_from
python
oumi-ai/oumi
src/oumi/train.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/train.py
Apache-2.0
def _create_training_dirs(config: TrainingConfig) -> None: """Creates misc directories referenced in config.""" _ensure_dir_exists(config.training.output_dir, "training.output_dir") telemetry_dir = config.training.telemetry_dir if telemetry_dir: _ensure_dir_exists(telemetry_dir, "training.teleme...
Creates misc directories referenced in config.
_create_training_dirs
python
oumi-ai/oumi
src/oumi/train.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/train.py
Apache-2.0
def _log_training_info(config: TrainingConfig) -> None: """Logs misc infos about training config/devices/etc. Writes to files.""" telemetry_dir = config.training.telemetry_dir if telemetry_dir and is_world_process_zero(): device_rank_info = get_device_rank_info() save_json( { ...
Logs misc infos about training config/devices/etc. Writes to files.
_log_training_info
python
oumi-ai/oumi
src/oumi/train.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/train.py
Apache-2.0
def _finalize_training_config(config: TrainingConfig) -> TrainingConfig: """Updates TrainingConfig using dynamic/runtime info.""" if config.training.dataloader_num_workers == "auto": # Resolve "auto" to an actual number. num_workers = estimate_dataloader_num_workers() logger.info( ...
Updates TrainingConfig using dynamic/runtime info.
_finalize_training_config
python
oumi-ai/oumi
src/oumi/train.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/train.py
Apache-2.0
def _verl_train( partial_trainer: Callable[[], BaseTrainer], checkpoint_location: Optional[str] ): """Runs verl training. This function initializes Ray, and then initializes and kicks off the trainer in a remote Ray function. """ try: import ray # pyright: ignore[reportMissingImports] ...
Runs verl training. This function initializes Ray, and then initializes and kicks off the trainer in a remote Ray function.
_verl_train
python
oumi-ai/oumi
src/oumi/train.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/train.py
Apache-2.0
def train( config: TrainingConfig, additional_model_kwargs: Optional[dict[str, Any]] = None, additional_trainer_kwargs: Optional[dict[str, Any]] = None, ) -> None: """Trains a model using the provided configuration.""" _START_TIME = time.time() _create_training_dirs(config) _log_training_in...
Trains a model using the provided configuration.
train
python
oumi-ai/oumi
src/oumi/train.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/train.py
Apache-2.0
def infer( config: InferenceConfig, inputs: list[str] | None = None, inference_engine: BaseInferenceEngine | None = None, *, input_image_bytes: list[bytes] | None = None, ) -> list[Conversation]: """Runs batch inference for a model using the provided configuration. Args: config: The...
Runs batch inference for a model using the provided configuration. Args: config: The configuration to use for inference. inputs: A list of inputs for inference. inference_engine: The engine to use for inference. If unspecified, the engine will be inferred from `config`. ...
infer
python
oumi-ai/oumi
src/oumi/__init__.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/__init__.py
Apache-2.0
def judge_conversations( config: JudgeConfig, judge_inputs: list[Conversation] ) -> list[dict[str, Any]]: """Judge a list of conversations. This function evaluates a list of conversations using the specified Judge. The function performs the following steps: 1. Initializes the Judge with the p...
Judge a list of conversations. This function evaluates a list of conversations using the specified Judge. The function performs the following steps: 1. Initializes the Judge with the provided configuration. 2. Uses the Judge to evaluate each conversation input. 3. Collects and returns...
judge_conversations
python
oumi-ai/oumi
src/oumi/__init__.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/__init__.py
Apache-2.0
def judge_dataset(config: JudgeConfig, dataset: BaseSftDataset) -> list[dict[str, Any]]: """Judge a dataset. This function evaluates a given dataset using a specified Judge configuration. The function performs the following steps: 1. Initializes the Judge with the provided configuration. ...
Judge a dataset. This function evaluates a given dataset using a specified Judge configuration. The function performs the following steps: 1. Initializes the Judge with the provided configuration. 2. Iterates through the dataset to extract conversation inputs. 3. Uses the Judge to eva...
judge_dataset
python
oumi-ai/oumi
src/oumi/__init__.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/__init__.py
Apache-2.0
def build_training_callbacks( config: TrainingConfig, model: torch.nn.Module, profiler: Optional[Any] ) -> list[BaseTrainerCallback]: """Builds the training callbacks for the given training config and model. This function creates a list of callback objects to be used during training. It includes callba...
Builds the training callbacks for the given training config and model. This function creates a list of callback objects to be used during training. It includes callbacks for performance metrics, profiling, telemetry, and Model Flops Utilization (MFU) logging based on the provided configuration. Args: ...
build_training_callbacks
python
oumi-ai/oumi
src/oumi/builders/callbacks.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/builders/callbacks.py
Apache-2.0
def build_data_collator( collator_name: str, tokenizer: BaseTokenizer, *, max_length: Optional[int], label_ignore_index: Optional[int] = constants.LABEL_IGNORE_INDEX, debug: bool = False, **kwargs, ) -> Callable: """Builds a data collator based on the given collator name. Args: ...
Builds a data collator based on the given collator name. Args: collator_name: The name of the collator to build. Supported values are: - "text_with_padding": Uses `TextCollatorWithPadding`. - "text_completions_only_with_padding": Uses `TextCompletionsCol...
build_data_collator
python
oumi-ai/oumi
src/oumi/builders/collators.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/builders/collators.py
Apache-2.0
def build_collator_from_config( config: TrainingConfig, tokenizer: Optional[BaseTokenizer], debug: bool = False ) -> Optional[Callable]: """Creates data collator if specified in config.""" train_split = config.data.get_split(DatasetSplit.TRAIN) if not train_split.collator_name: return None c...
Creates data collator if specified in config.
build_collator_from_config
python
oumi-ai/oumi
src/oumi/builders/collators.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/builders/collators.py
Apache-2.0
def build_dataset_mixture( data_params: DataParams, tokenizer: Optional[BaseTokenizer], dataset_split: DatasetSplit, seq_length: Optional[int] = None, seed: Optional[int] = None, ) -> Union[DatasetType, PretrainingAsyncTextDataset]: """Builds a dataset for the specified split. Args: ...
Builds a dataset for the specified split. Args: data_params: The data params. tokenizer: The tokenizer object to use for preprocessing. dataset_split: The split of the dataset to load. seq_length: The length each example will be packed to. This is only used if packing is...
build_dataset_mixture
python
oumi-ai/oumi
src/oumi/builders/data.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/builders/data.py
Apache-2.0
def build_dataset( dataset_name: str, tokenizer: Optional[BaseTokenizer], seed: Optional[int] = None, stream: bool = False, pack: bool = False, use_torchdata: Optional[bool] = None, **kwargs, ) -> Union[DatasetType, PretrainingAsyncTextDataset]: """Builds a dataset from a dataset name. ...
Builds a dataset from a dataset name. Please refer to `DatasetParams` & `DatasetSplitParams` for a description of the all the arguments.
build_dataset
python
oumi-ai/oumi
src/oumi/builders/data.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/builders/data.py
Apache-2.0
def _mix_datasets( dataset_list: list[DatasetType], mixture_proportions: Sequence[Optional[float]], mixture_strategy: str, seed: Optional[int], ) -> DatasetType: """Joins multiple datasets using the provided `mixture_strategy`.""" if any([proportion is None for proportion in mixture_proportions]...
Joins multiple datasets using the provided `mixture_strategy`.
_mix_datasets
python
oumi-ai/oumi
src/oumi/builders/data.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/builders/data.py
Apache-2.0
def _build_iterable_dataset_sampler( dataset: datasets.IterableDataset, n: int ) -> Callable: """Returns a generator that supports oversampling an IterableDataset.""" def _generator(): generation_count = 0 while generation_count < n: for generation in dataset: ge...
Returns a generator that supports oversampling an IterableDataset.
_build_iterable_dataset_sampler
python
oumi-ai/oumi
src/oumi/builders/data.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/builders/data.py
Apache-2.0
def _load_dataset( dataset_params: DatasetParams, stream: bool, tokenizer: Optional[BaseTokenizer] = None, ) -> Union[ datasets.DatasetDict, datasets.Dataset, datasets.IterableDatasetDict, datasets.IterableDataset, ]: """Loads a dataset with the specified name and subset. Note: ...
Loads a dataset with the specified name and subset. Note: For custom map datasets, streaming is only partially supported: - The full dataset is downloaded (or loaded from disk), and loaded in memory. - However, transformations are applied lazily in streaming mode. The raw datas...
_load_dataset
python
oumi-ai/oumi
src/oumi/builders/data.py
https://github.com/oumi-ai/oumi/blob/master/src/oumi/builders/data.py
Apache-2.0