response
stringlengths
1
33.1k
instruction
stringlengths
22
582k
Adds all current event devices to the global dict of event devices. Returns: The number of event devices connected, at the time UKIP was started. Raises: TypeError: If there is an error in converting the PID/VID of a USB device. ValueError: If there is an error in converting the PID/VID of a USB device. Runtim...
def init_device_list() -> int: """Adds all current event devices to the global dict of event devices. Returns: The number of event devices connected, at the time UKIP was started. Raises: TypeError: If there is an error in converting the PID/VID of a USB device. ValueError: If there is an error in co...
Saves given data as a .pkl (pickle) file Paramters: data(dict): Dictionary containing all the necessary data to save
def save_data(data): """ Saves given data as a .pkl (pickle) file Paramters: data(dict): Dictionary containing all the necessary data to save """ # Open data file, create it if it does not exist with open('data.pkl', 'wb') as data_file: pickle.dump(data, data_file)
Loads saved pkl file and returns the stored data Returns(dict): Dictionary containing all the saved data
def load_data() -> dict: """ Loads saved pkl file and returns the stored data Returns(dict): Dictionary containing all the saved data """ try: with open('data.pkl', 'rb') as data_file: # Open data file data = pickle.load(data_file) return data except (Value...
Get the model hash dictionary
def load_model_hash_data(dictionary): '''Get the model hash dictionary''' with open(dictionary, 'r') as d: return json.load(d)
Attempts to decrypt VIP model link with given input code
def vip_downloads(password, link_type=VIP_REPO): """Attempts to decrypt VIP model link with given input code""" try: kdf = PBKDF2HMAC( algorithm=hashes.SHA256(), length=32, salt=link_type[0], iterations=390000,) key = base64.urlsafe_b64encode...
Apply model to a given mixture. Args: shifts (int): if > 0, will shift in time `mix` by a random amount between 0 and 0.5 sec and apply the oppositve shift to the output. This is repeated `shifts` time and all predictions are averaged. This effectively makes the model time equivariant and i...
def apply_model(model, mix, shifts=1, split=True, overlap=0.25, transition_power=1., static_shifts=1, set_progress_bar=None, device=None, progress=False, ...
Rescale initial weight scale. It is unclear why it helps but it certainly does.
def rescale_conv(conv, reference): """Rescale initial weight scale. It is unclear why it helps but it certainly does. """ std = conv.weight.std().detach() scale = (std / reference)**0.5 conv.weight.data /= scale if conv.bias is not None: conv.bias.data /= scale
Element-wise arctangent function of y/x. Returns a new tensor with signed angles in radians. It is an alternative implementation of torch.atan2 Args: y (Tensor): First input tensor x (Tensor): Second input tensor [shape=y.shape] Returns: Tensor: [shape=y.shape].
def atan2(y, x): r"""Element-wise arctangent function of y/x. Returns a new tensor with signed angles in radians. It is an alternative implementation of torch.atan2 Args: y (Tensor): First input tensor x (Tensor): Second input tensor [shape=y.shape] Returns: Tensor: [shape=...
Computes the norm value of a torch Tensor, assuming that it comes as real and imaginary part in its last dimension. Args: x (Tensor): Input Tensor of shape [shape=(..., 2)] Returns: Tensor: shape as x excluding the last dimension.
def _norm(x: torch.Tensor) -> torch.Tensor: r"""Computes the norm value of a torch Tensor, assuming that it comes as real and imaginary part in its last dimension. Args: x (Tensor): Input Tensor of shape [shape=(..., 2)] Returns: Tensor: shape as x excluding the last dimension. """...
Element-wise multiplication of two complex Tensors described through their real and imaginary parts. The result is added to the `out` tensor
def _mul_add(a: torch.Tensor, b: torch.Tensor, out: Optional[torch.Tensor] = None) -> torch.Tensor: """Element-wise multiplication of two complex Tensors described through their real and imaginary parts. The result is added to the `out` tensor""" # check `out` and allocate it if needed target_shape...
Element-wise multiplication of two complex Tensors described through their real and imaginary parts can work in place in case out is a only
def _mul(a: torch.Tensor, b: torch.Tensor, out: Optional[torch.Tensor] = None) -> torch.Tensor: """Element-wise multiplication of two complex Tensors described through their real and imaginary parts can work in place in case out is a only""" target_shape = torch.Size([max(sa, sb) for (sa, sb) in zip(a.s...
Element-wise multiplicative inverse of a Tensor with complex entries described through their real and imaginary parts. can work in place in case out is z
def _inv(z: torch.Tensor, out: Optional[torch.Tensor] = None) -> torch.Tensor: """Element-wise multiplicative inverse of a Tensor with complex entries described through their real and imaginary parts. can work in place in case out is z""" ez = _norm(z) if out is None or out.shape != z.shape: ...
Element-wise complex conjugate of a Tensor with complex entries described through their real and imaginary parts. can work in place in case out is z
def _conj(z, out: Optional[torch.Tensor] = None) -> torch.Tensor: """Element-wise complex conjugate of a Tensor with complex entries described through their real and imaginary parts. can work in place in case out is z""" if out is None or out.shape != z.shape: out = torch.zeros_like(z) out[....
Invert 1x1 or 2x2 matrices Will generate errors if the matrices are singular: user must handle this through his own regularization schemes. Args: M (Tensor): [shape=(..., nb_channels, nb_channels, 2)] matrices to invert: must be square along dimensions -3 and -2 Returns: invM (Tensor): [shape=M.shape...
def _invert(M: torch.Tensor, out: Optional[torch.Tensor] = None) -> torch.Tensor: """ Invert 1x1 or 2x2 matrices Will generate errors if the matrices are singular: user must handle this through his own regularization schemes. Args: M (Tensor): [shape=(..., nb_channels, nb_channels, 2)] ...
Expectation maximization algorithm, for refining source separation estimates. This algorithm allows to make source separation results better by enforcing multichannel consistency for the estimates. This usually means a better perceptual quality in terms of spatial artifacts. The implementation follows the details pre...
def expectation_maximization( y: torch.Tensor, x: torch.Tensor, iterations: int = 2, eps: float = 1e-10, batch_size: int = 200, ): r"""Expectation maximization algorithm, for refining source separation estimates. This algorithm allows to make source separation results better by enfo...
Wiener-based separation for multichannel audio. The method uses the (possibly multichannel) spectrograms of the sources to separate the (complex) Short Term Fourier Transform of the mix. Separation is done in a sequential way by: * Getting an initial estimate. This can be done in two ways: either by directly usin...
def wiener( targets_spectrograms: torch.Tensor, mix_stft: torch.Tensor, iterations: int = 1, softmask: bool = False, residual: bool = False, scale_factor: float = 10.0, eps: float = 1e-10, ): """Wiener-based separation for multichannel audio. The method uses the (possibly multichann...
Compute the empirical covariance for a source. Args: y_j (Tensor): complex stft of the source. [shape=(nb_frames, nb_bins, nb_channels, 2)]. Returns: Cj (Tensor): [shape=(nb_frames, nb_bins, nb_channels, nb_channels, 2)] just y_j * conj(y_j.T): empirical covariance for each TF bin.
def _covariance(y_j): """ Compute the empirical covariance for a source. Args: y_j (Tensor): complex stft of the source. [shape=(nb_frames, nb_bins, nb_channels, 2)]. Returns: Cj (Tensor): [shape=(nb_frames, nb_bins, nb_channels, nb_channels, 2)] just y_j * conj...
Tiny wrapper around F.pad, just to allow for reflect padding on small input. If this is the case, we insert extra 0 padding to the right before the reflection happen.
def pad1d(x: torch.Tensor, paddings: tp.Tuple[int, int], mode: str = 'constant', value: float = 0.): """Tiny wrapper around F.pad, just to allow for reflect padding on small input. If this is the case, we insert extra 0 padding to the right before the reflection happen.""" x0 = x length = x.shape[-1] ...
Linear upsampling, the output will be `stride` times longer.
def upsample(x, stride): """ Linear upsampling, the output will be `stride` times longer. """ batch, channels, time = x.size() weight = th.arange(stride, device=x.device, dtype=th.float) / stride x = x.view(batch, channels, time, 1) out = x[..., :-1, :] * (1 - weight) + x[..., 1:, :] * weigh...
Downsample x by decimation.
def downsample(x, stride): """ Downsample x by decimation. """ return x[:, :, ::stride]
`name` must be a bag of models name or a pretrained signature from the remote AWS model repo or the specified local repo if `repo` is not None.
def get_model(name: str, repo: tp.Optional[Path] = None): """`name` must be a bag of models name or a pretrained signature from the remote AWS model repo or the specified local repo if `repo` is not None. """ if name == 'demucs_unittest': return demucs_unittest() model_repo: Mo...
Load local model package or pre-trained model.
def get_model_from_args(args): """ Load local model package or pre-trained model. """ return get_model(name=args.name, repo=args.repo)
Return the quantizer given the XP quantization args.
def get_quantizer(model, args, optimizer=None): """Return the quantizer given the XP quantization args.""" quantizer = None if args.diffq: quantizer = DiffQuantizer( model, min_size=args.min_size, group_size=args.group_size) if optimizer is not None: quantizer.setup_...
Load a model from the given serialized model, either given as a dict (already loaded) or a path to a file on disk.
def load_model(path_or_package, strict=False): """Load a model from the given serialized model, either given as a dict (already loaded) or a path to a file on disk.""" if isinstance(path_or_package, dict): package = path_or_package elif isinstance(path_or_package, (str, Path)): with war...
Get the state from a model, potentially with quantization applied. If `half` is True, model are stored as half precision, which shouldn't impact performance but half the state size.
def get_state(model, quantizer, half=False): """Get the state from a model, potentially with quantization applied. If `half` is True, model are stored as half precision, which shouldn't impact performance but half the state size.""" if quantizer is None: dtype = torch.half if half else None ...
Set the state on a given model.
def set_state(model, state, quantizer=None): """Set the state on a given model.""" if state.get('__quantized'): if quantizer is not None: quantizer.restore_quantized_state(model, state['quantized']) else: restore_quantized_state(model, state) else: model...
Save the given value on disk, along with a sha256 hash. Should be used with the output of either `serialize_model` or `get_state`.
def save_with_checksum(content, path): """Save the given value on disk, along with a sha256 hash. Should be used with the output of either `serialize_model` or `get_state`.""" buf = io.BytesIO() torch.save(content, buf) sig = hashlib.sha256(buf.getvalue()).hexdigest()[:8] path = path.parent / (...
Context manager that swaps the state of a model, e.g: # model is in old state with swap_state(model, new_state): # model in new state # model back to old state
def swap_state(model, state): """ Context manager that swaps the state of a model, e.g: # model is in old state with swap_state(model, new_state): # model in new state # model back to old state """ old_state = copy_state(model.state_dict()) model.load_state_dict(...
The input of normlization will be (M, C, K), where M is batch size, C is channel size and K is sequence length.
def chose_norm(norm_type, channel_size): """The input of normlization will be (M, C, K), where M is batch size, C is channel size and K is sequence length. """ if norm_type == "gLN": return GlobalLayerNorm(channel_size) elif norm_type == "cLN": return ChannelwiseLayerNorm(channel_...
The input of normlization will be (M, C, K), where M is batch size, C is channel size and K is sequence length.
def chose_norm(norm_type, channel_size): """The input of normlization will be (M, C, K), where M is batch size, C is channel size and K is sequence length. """ if norm_type == "gLN": return GlobalLayerNorm(channel_size) elif norm_type == "cLN": return ChannelwiseLayerNorm(channel_...
:param d_model: dimension of the model :param height: height of the positions :param width: width of the positions :return: d_model*height*width position matrix
def create_2d_sin_embedding(d_model, height, width, device="cpu", max_period=10000): """ :param d_model: dimension of the model :param height: height of the positions :param width: width of the positions :return: d_model*height*width position matrix """ if d_model % 4 != 0: raise Val...
When the input of the Decoder has length T1 and the output T2 The mask matrix has shape (T2, T1)
def get_elementary_mask( T1, T2, mask_type, sparse_attn_window, global_window, mask_random_seed, sparsity, device, ): """ When the input of the Decoder has length T1 and the output T2 The mask matrix has shape (T2, T1) """ assert mask_type in ["diag", "jmask", "random...
Return a SparseCSRTensor mask that is a combination of elementary masks mask_type can be a combination of multiple masks: for instance "diag_jmask_random"
def get_mask( T1, T2, mask_type, sparse_attn_window, global_window, mask_random_seed, sparsity, device, ): """ Return a SparseCSRTensor mask that is a combination of elementary masks mask_type can be a combination of multiple masks: for instance "diag_jmask_random" """ ...
Given input of size [*OT, T], output Tensor of size [*OT, F, K] with K the kernel size, by extracting frames with the given stride. This will pad the input so that `F = ceil(T / K)`. see https://github.com/pytorch/pytorch/issues/60466
def unfold(a, kernel_size, stride): """Given input of size [*OT, T], output Tensor of size [*OT, F, K] with K the kernel size, by extracting frames with the given stride. This will pad the input so that `F = ceil(T / K)`. see https://github.com/pytorch/pytorch/issues/60466 """ *shape, length =...
Center trim `tensor` with respect to `reference`, along the last dimension. `reference` can also be a number, representing the length to trim to. If the size difference != 0 mod 2, the extra sample is removed on the right side.
def center_trim(tensor: torch.Tensor, reference: tp.Union[torch.Tensor, int]): """ Center trim `tensor` with respect to `reference`, along the last dimension. `reference` can also be a number, representing the length to trim to. If the size difference != 0 mod 2, the extra sample is removed on the right...
Exponential Moving Average callback. Returns a single function that can be called to repeatidly update the EMA with a dict of metrics. The callback will return the new averaged dict of metrics. Note that for `beta=1`, this is just plain averaging.
def EMA(beta: float = 1): """ Exponential Moving Average callback. Returns a single function that can be called to repeatidly update the EMA with a dict of metrics. The callback will return the new averaged dict of metrics. Note that for `beta=1`, this is just plain averaging. """ fix: ...
Given `num` bytes, return human readable size. Taken from https://stackoverflow.com/a/1094933
def sizeof_fmt(num: float, suffix: str = 'B'): """ Given `num` bytes, return human readable size. Taken from https://stackoverflow.com/a/1094933 """ for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']: if abs(num) < 1024.0: return "%3.1f%s%s" % (num, unit, suffix) ...
Average `metric` which should be a float across all hosts. `count` should be the weight for this particular host (i.e. number of examples).
def average_metric(metric, count=1.): """ Average `metric` which should be a float across all hosts. `count` should be the weight for this particular host (i.e. number of examples). """ metric = th.tensor([count, count * metric], dtype=th.float32, device='cuda') distributed.all_reduce(metric, op...
Return a port number that is most likely free. This could suffer from a race condition although it should be quite rare.
def free_port(host='', low=20000, high=40000): """ Return a port number that is most likely free. This could suffer from a race condition although it should be quite rare. """ sock = socket.socket() while True: port = random.randint(low, high) try: sock.bind((host...
Given `num` bytes, return human readable size. Taken from https://stackoverflow.com/a/1094933
def sizeof_fmt(num, suffix='B'): """ Given `num` bytes, return human readable size. Taken from https://stackoverflow.com/a/1094933 """ for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']: if abs(num) < 1024.0: return "%3.1f%s%s" % (num, unit, suffix) num /= 1024.0...
Given `seconds` seconds, return human readable duration.
def human_seconds(seconds, display='.2f'): """ Given `seconds` seconds, return human readable duration. """ value = seconds * 1e6 ratios = [1e3, 1e3, 60, 60, 24] names = ['us', 'ms', 's', 'min', 'hrs', 'days'] last = names.pop(0) for name, ratio in zip(names, ratios): if value /...
Apply model to a given mixture. Args: shifts (int): if > 0, will shift in time `mix` by a random amount between 0 and 0.5 sec and apply the oppositve shift to the output. This is repeated `shifts` time and all predictions are averaged. This effectively makes the model time equivariant and i...
def apply_model_v1(model, mix, shifts=None, split=False, progress=False, set_progress_bar=None): """ Apply model to a given mixture. Args: shifts (int): if > 0, will shift in time `mix` by a random amount between 0 and 0.5 sec and apply the oppositve shift to the output. This is repeate...
Apply model to a given mixture. Args: shifts (int): if > 0, will shift in time `mix` by a random amount between 0 and 0.5 sec and apply the oppositve shift to the output. This is repeated `shifts` time and all predictions are averaged. This effectively makes the model time equivariant and i...
def apply_model_v2(model, mix, shifts=None, split=False, overlap=0.25, transition_power=1., progress=False, set_progress_bar=None): """ Apply model to a given mixture. Args: shifts (int): if > 0, will shift in time `mix` by a random amount between 0 and 0.5 sec and appl...
Determines secondary stem
def secondary_stem(stem:str): """Determines secondary stem""" stem = stem if stem else NO_STEM if stem in STEM_PAIR_MAPPER.keys(): for key, value in STEM_PAIR_MAPPER.items(): if stem in key: secondary_stem = value else: secondary_stem = stem.re...
Internal function.
def _require(tkroot): '''Internal function.''' global TkdndVersion try: import os.path import platform if platform.system()=="Darwin": tkdnd_platform_rep = "osx_arm" if platform.processor() == ARM or ARM in platform.platform() else "osx64" elif platform.system()...
Normalize audio
def normalize(wave, is_normalize=False): """Normalize audio""" maxv = np.abs(wave).max() if maxv > 1.0: if is_normalize: print("Above clipping threshold.") wave /= maxv return wave
Ensure that the audio array is in the (channels, samples) format. Parameters: audio_array (ndarray): Input audio array. Returns: ndarray: Transposed audio array if necessary.
def auto_transpose(audio_array:np.ndarray): """ Ensure that the audio array is in the (channels, samples) format. Parameters: audio_array (ndarray): Input audio array. Returns: ndarray: Transposed audio array if necessary. """ # If the second dimension is 2 (indicating ste...
Detect silence at the beginning of an audio signal. :param audio: np.array, audio signal :param sr: int, sample rate :param silence_threshold: float, magnitude threshold below which is considered silence :param frame_length: int, the number of samples to consider for each check :return: float, duration of the leading...
def detect_leading_silence(audio, sr, silence_threshold=0.007, frame_length=1024): """ Detect silence at the beginning of an audio signal. :param audio: np.array, audio signal :param sr: int, sample rate :param silence_threshold: float, magnitude threshold below which is considered silence :par...
Adjust the leading silence of the target_audio to match the leading silence of the reference_audio. :param target_audio: np.array, audio signal that will have its silence adjusted :param reference_audio: np.array, audio signal used as a reference :param sr: int, sample rate :param silence_threshold: float, magnitude t...
def adjust_leading_silence(target_audio, reference_audio, silence_threshold=0.01, frame_length=1024): """ Adjust the leading silence of the target_audio to match the leading silence of the reference_audio. :param target_audio: np.array, audio signal that will have its silence adjusted :param reference_...
This fixture creates a directory structure to enable reload parameter tests The fixture has the following structure: root ├── [app, app_first, app_second, app_third] │   ├── css │   │   └── main.css │   ├── js │   │   └── main.js │   ├── src │   │   └── main.py │   └── sub │   └── sub.py ├── ext │   └── ext.jpg ├─...
def reload_directory_structure(tmp_path_factory: pytest.TempPathFactory): """ This fixture creates a directory structure to enable reload parameter tests The fixture has the following structure: root ├── [app, app_first, app_second, app_third] │   ├── css │   │   └── main.css │   ├── js...
Find an unused localhost port from 1024-65535 and return it.
def _unused_port(socket_type: int) -> int: """Find an unused localhost port from 1024-65535 and return it.""" with contextlib.closing(socket.socket(type=socket_type)) as sock: sock.bind(("127.0.0.1", 0)) return sock.getsockname()[1]
Test that one can specify the use_colors option when using the default logging config.
def test_log_config_default( mocked_logging_config_module: MagicMock, use_colors: bool | None, expected: bool | None, logging_config: dict[str, Any], ) -> None: """ Test that one can specify the use_colors option when using the default logging config. """ config = Config(app=asgi_app...
Test that one can load a json config from disk.
def test_log_config_json( mocked_logging_config_module: MagicMock, logging_config: dict[str, Any], json_logging_config: str, mocker: MockerFixture, ) -> None: """ Test that one can load a json config from disk. """ mocked_open = mocker.patch("uvicorn.config.open", mocker.mock_open(read_d...
Test that one can load a yaml config from disk.
def test_log_config_yaml( mocked_logging_config_module: MagicMock, logging_config: dict[str, Any], yaml_logging_config: str, mocker: MockerFixture, config_filename: str, ) -> None: """ Test that one can load a yaml config from disk. """ mocked_open = mocker.patch("uvicorn.config.open...
Test that one can load a configparser config from disk.
def test_log_config_file( mocked_logging_config_module: MagicMock, config_file: str | configparser.RawConfigParser | typing.IO[Any], ) -> None: """ Test that one can load a configparser config from disk. """ config = Config(app=asgi_app, log_config=config_file) config.load() mocked_logg...
Test that one can load environment variables using an env file.
def test_env_file( web_concurrency: int, forwarded_allow_ips: str, caplog: pytest.LogCaptureFixture, tmp_path: Path, ) -> None: """ Test that one can load environment variables using an env file. """ fp = tmp_path / ".env" content = f"WEB_CONCURRENCY={web_concurrency}\n" f"FORWARDED_...
Replace `sig` handling with a normal exception via `signal
def capture_signal_sync(sig: signal.Signals) -> Generator[list[int], None, None]: """Replace `sig` handling with a normal exception via `signal""" witness: list[int] = [] original_handler = signal.signal(sig, lambda signum, frame: witness.append(signum)) yield witness signal.signal(sig, original_han...
Replace `sig` handling with a normal exception via `asyncio
def capture_signal_async(sig: signal.Signals) -> Generator[list[int], None, None]: # pragma: py-win32 """Replace `sig` handling with a normal exception via `asyncio""" witness: list[int] = [] original_handler = signal.getsignal(sig) asyncio.get_running_loop().add_signal_handler(sig, witness.append, sig...
Changes working directory and returns to previous on exit.
def as_cwd(path: Path): """Changes working directory and returns to previous on exit.""" prev_cwd = Path.cwd() os.chdir(path) try: yield finally: os.chdir(prev_cwd)
A basic sanity check. Simply run the supervisor against a no-op server, and signal for it to quit immediately.
def test_multiprocess_run() -> None: """ A basic sanity check. Simply run the supervisor against a no-op server, and signal for it to quit immediately. """ config = Config(app=app, workers=2) supervisor = Multiprocess(config, target=run, sockets=[]) supervisor.signal_handler(sig=signal....
Called in the parent process, to instantiate a new child process instance. The child is not yet started at this point. * config - The Uvicorn configuration instance. * target - A callable that accepts a list of sockets. In practice this will be the `Server.run()` method. * sockets - A list of sockets to pas...
def get_subprocess( config: Config, target: Callable[..., None], sockets: list[socket], ) -> SpawnProcess: """ Called in the parent process, to instantiate a new child process instance. The child is not yet started at this point. * config - The Uvicorn configuration instance. * target -...
Called when the child process starts. * config - The Uvicorn configuration instance. * target - A callable that accepts a list of sockets. In practice this will be the `Server.run()` method. * sockets - A list of sockets to pass to the server. Sockets are bound once by the parent process, and th...
def subprocess_started( config: Config, target: Callable[..., None], sockets: list[socket], stdin_fileno: int | None, ) -> None: """ Called when the child process starts. * config - The Uvicorn configuration instance. * target - A callable that accepts a list of sockets. In practice thi...
Return an ASGI message, with any body-type content omitted and replaced with a placeholder.
def message_with_placeholders(message: Any) -> Any: """ Return an ASGI message, with any body-type content omitted and replaced with a placeholder. """ new_message = message.copy() for attr in PLACEHOLDER_FORMAT.keys(): if message.get(attr) is not None: content = message[att...
Builds a scope and request message into a WSGI environ object.
def build_environ(scope: HTTPScope, message: ASGIReceiveEvent, body: io.BytesIO) -> Environ: """ Builds a scope and request message into a WSGI environ object. """ script_name = scope.get("root_path", "").encode("utf8").decode("latin1") path_info = scope["path"].encode("utf8").decode("latin1") i...
Load a config file and merge it into the default options.
def cfg_from_file(filename): """Load a config file and merge it into the default options.""" import yaml with open(filename, 'r') as fopen: yaml_config = AttrDict(yaml.load(fopen)) merge_dicts(yaml_config, __C)
Set config keys via list (e.g., from command line).
def cfg_from_list(args_list): """Set config keys via list (e.g., from command line).""" from ast import literal_eval assert len(args_list) % 2 == 0, 'Specify values or keys for args' for key, value in zip(args_list[0::2], args_list[1::2]): key_list = key.split('.') cfg = __C for...
case 1: CHECKPOINT.RESUME = False and TRAIN.PARAMS_FILE is not none: load params_file case 2: CHECKPOINT.RESUME = True and TRAIN.PARAMS_FILE is not none: case 2a: if checkpoint exist: use checkpoint case 2b: if checkpoint not exist: use params_file case 3: CHECKPOINT.RESUME = True and TRAIN.PARAMS_FILE is...
def load_model_from_params_file(model): """ case 1: CHECKPOINT.RESUME = False and TRAIN.PARAMS_FILE is not none: load params_file case 2: CHECKPOINT.RESUME = True and TRAIN.PARAMS_FILE is not none: case 2a: if checkpoint exist: use checkpoint case 2b: if checkpoint not exist: use pa...
Get the learning rate at iteration it according to the cfg.SOLVER settings.
def get_lr_at_iter(it): """Get the learning rate at iteration it according to the cfg.SOLVER settings. """ lr = get_lr_func()(it) lr = np.float32(lr) """ Warmup hacks (gradual linear): Example: cfg.SOLVER.WARMUP.WARMUP_START_LR: 0.1 cfg.SOLVER.WARMUP.WARMUP_END_ITER: 5005 * 5 ...
For cfg.SOLVER.LR_POLICY = 'steps_with_lrs' Change the learning rate to specified values at specified iterations. Example: cfg.SOLVER.MAX_ITER: 90 cfg.SOLVER.STEPS: [0, 60, 80] cfg.SOLVER.LRS: [0.02, 0.002, 0.0002] for cur_iter in [0, 59] use 0.02 in [60, 79] use 0.002 in [8...
def lr_func_steps_with_lrs(cur_iter): """ For cfg.SOLVER.LR_POLICY = 'steps_with_lrs' Change the learning rate to specified values at specified iterations. Example: cfg.SOLVER.MAX_ITER: 90 cfg.SOLVER.STEPS: [0, 60, 80] cfg.SOLVER.LRS: [0.02, 0.002, 0.0002] for cur_iter in...
For cfg.SOLVER.LR_POLICY = 'steps_with_relative_lrs' Change the learning rate to specified values at specified iterations. Example: cfg.SOLVER.MAX_ITER: 90 cfg.SOLVER.STEPS: [0, 60, 80] cfg.SOLVER.BASE_LR: 0.02 cfg.SOLVER.LRS: [1, 0.1, 0.01] for cur_iter in [0, 59] use 0.02 in [60, 79] ...
def lr_func_steps_with_relative_lrs(cur_iter): """ For cfg.SOLVER.LR_POLICY = 'steps_with_relative_lrs' Change the learning rate to specified values at specified iterations. Example: cfg.SOLVER.MAX_ITER: 90 cfg.SOLVER.STEPS: [0, 60, 80] cfg.SOLVER.BASE_LR: 0.02 cfg.SOLVER.LRS...
For cfg.SOLVER.LR_POLICY = 'steps_with_decay' Change the learning rate specified iterations based on the formula lr = base_lr * gamma ** lr_step_count. Example: cfg.SOLVER.MAX_ITER: 90 cfg.SOLVER.STEPS: [0, 60, 80] cfg.SOLVER.BASE_LR: 0.02 cfg.SOLVER.GAMMA: 0.1 for cur_iter in [0, 59] use 0.02 = 0.02 *...
def lr_func_steps_with_decay(cur_iter): """ For cfg.SOLVER.LR_POLICY = 'steps_with_decay' Change the learning rate specified iterations based on the formula lr = base_lr * gamma ** lr_step_count. Example: cfg.SOLVER.MAX_ITER: 90 cfg.SOLVER.STEPS: [0, 60, 80] cfg.SOLVER.BASE_LR...
For cfg.SOLVER.LR_POLICY = 'step'
def lr_func_step(cur_iter): """ For cfg.SOLVER.LR_POLICY = 'step' """ return ( cfg.SOLVER.BASE_LR * cfg.SOLVER.GAMMA ** (cur_iter // cfg.SOLVER.STEP_SIZE))
Given an iteration, find which learning rate step we're at.
def get_step_index(cur_iter): """Given an iteration, find which learning rate step we're at.""" assert cfg.SOLVER.STEPS[0] == 0, 'The first step should always start at 0.' steps = cfg.SOLVER.STEPS + [cfg.SOLVER.MAX_ITER] for ind, step in enumerate(steps): # NoQA if cur_iter < step: ...
Compute the number of corret hits
def compute_topk_correct_hits(top_k, preds, labels): '''Compute the number of corret hits''' batch_size = preds.shape[0] top_k_preds = np.zeros((batch_size, top_k), dtype=np.float32) for i in range(batch_size): top_k_preds[i, :] = np.argsort(-preds[i, :])[:top_k] correctness = np.zeros(bat...
Summed values of a blob on each gpu
def sum_multi_gpu_blob(blob_name): """Summed values of a blob on each gpu""" value = 0 num_gpus = cfg.NUM_GPUS root_gpu_id = cfg.ROOT_GPU_ID for idx in range(root_gpu_id, root_gpu_id + num_gpus): value += workspace.FetchBlob('gpu_{}/{}'.format(idx, blob_name)) return value
Summed values of batch size on each gpu
def get_batch_size_from_workspace(): """Summed values of batch size on each gpu""" value = 0 num_gpus = cfg.NUM_GPUS root_gpu_id = cfg.ROOT_GPU_ID for idx in range(root_gpu_id, root_gpu_id + num_gpus): value += workspace.FetchBlob('gpu_{}/{}'.format(idx, 'pred')).shape[0] return value
To save test-time memory, we perform multi-clip test in multiple "sections": e.g., 10-clip test can be done in 2 sections of 5-clip test
def test_net_one_section(): """ To save test-time memory, we perform multi-clip test in multiple "sections": e.g., 10-clip test can be done in 2 sections of 5-clip test """ timer = Timer() results = [] seen_inds = defaultdict(int) logger.warning('Testing started...') # for monitoring c...
a simpler wrapper that creates the elements for train/test models
def create_wrapper(is_train): """ a simpler wrapper that creates the elements for train/test models """ if is_train: suffix = '_train' split = cfg.TRAIN.DATA_TYPE use_mem_cache = cfg.TRAIN.MEM_CACHE else: # is test suffix = '_test'.format(cfg.MODEL.MODEL_NAME) ...
Bernstein polynomial.
def bernstein(n, k): """Bernstein polynomial.""" coeff = binom(n, k) def _bpoly(x): return coeff * x**k * (1 - x) ** (n - k) return _bpoly
Build Bézier curve from points.
def bezier(points, at): """Build Bézier curve from points.""" warnings.warn( message="Deprecated. CatmulClark builds nicer splines.", category=FutureWarning, stacklevel=1, ) at = np.asarray(at) at_flat = at.ravel() n = len(points) curve = np.zeros((at_flat.shape[0], ...
Parses a line of a requirements.txt file.
def _strip_comments_from_line(s: str) -> str: """Parses a line of a requirements.txt file.""" requirement, *_ = s.split('#') return requirement.strip()
Returns a list of dependencies for setup() from requirements.txt.
def _parse_requirements(requirements_txt_path: str) -> list[str]: """Returns a list of dependencies for setup() from requirements.txt.""" # Currently a requirements.txt is being used to specify dependencies. In order # to avoid specifying it in two places, we're going to use that file as the # source of truth....
Dummy evaluator used as an example.
def evaluate_trial(trial: vz.Trial) -> vz.Measurement: """Dummy evaluator used as an example.""" learning_rate = trial.parameters.get_value('learning_rate') num_layers = trial.parameters.get_value('num_layers') m = vz.Measurement() m.metrics = {'accuracy': learning_rate * num_layers} # dummy accuracy if FL...
Default optimizer and random restarts that work okay for most cases.
def default_optimizer(maxiter: int = 50) -> Optimizer: """Default optimizer and random restarts that work okay for most cases.""" # NOTE: Production algorithms are recommended to stay away from using this. return JaxoptScipyLbfgsB(LbfgsBOptions(maxiter=maxiter, best_n=None))
Converts a dict of (..., D_i) arrays to a (..., \sum_i D_i) array.
def dict_to_array(array_dict: Mapping[Any, np.ndarray]) -> np.ndarray: r"""Converts a dict of (..., D_i) arrays to a (..., \sum_i D_i) array.""" return np.concatenate(list(array_dict.values()), axis=-1)
Create a default getter for the given parameter config.
def _create_default_getter( pconfig: pyvizier.ParameterConfig, ) -> Callable[[pyvizier.TrialSuggestion], Any]: """Create a default getter for the given parameter config.""" def getter(trial, pconfig=pconfig): if pconfig.name not in trial.parameters: return None pvalue = trial.parameters[pconfig....
Compute the Kumaraswamy CDF. Arguments: x: values in [0,1]. shape: (num_samples, num_features) a: positive value. b: positive value. Returns: The CDF(x). shape: (num_samples, num_cdfs).
def kumaraswamy_cdf(x: np.ndarray, a: float, b: float) -> np.ndarray: """Compute the Kumaraswamy CDF. Arguments: x: values in [0,1]. shape: (num_samples, num_features) a: positive value. b: positive value. Returns: The CDF(x). shape: (num_samples, num_cdfs). """ return 1 - (1 - x**a) ** b
Compute the inverse of the Kumaraswamy CDF. Arguments: f: values in [0,1]. shape: (num_samples, num_cdfs) a: positive value. b: positive value. Returns: The Inv_CDF(x). shape: (num_samples, num_features).
def kumaraswamy_inv_cdf(f: np.ndarray, a: float, b: float) -> np.ndarray: """Compute the inverse of the Kumaraswamy CDF. Arguments: f: values in [0,1]. shape: (num_samples, num_cdfs) a: positive value. b: positive value. Returns: The Inv_CDF(x). shape: (num_samples, num_features). """ return...
Returns the padded shape according to `padding_types`.
def _padded_dimensions( dims: Sequence[int], padding_types: Sequence[PaddingType] ) -> tuple[int, ...]: """Returns the padded shape according to `padding_types`.""" new_dims = [] for dim, padding_type in zip(dims, padding_types): if padding_type == PaddingType.NONE: new_dims.append(dim) elif ...
Assertion function for comparing two (nested) dictionaries.
def assert_arraytree_allclose( d1: Mapping[str, Any], d2: Mapping[str, Any], **kwargs ) -> None: """Assertion function for comparing two (nested) dictionaries.""" np.testing.assert_equal(d1.keys(), d2.keys()) for k, v in d1.items(): if isinstance(v, dict): assert_arraytree_allclose(v, d2[k], **kwa...
Search space with float parameter types.
def flat_continuous_space_with_scaling() -> vz.SearchSpace: """Search space with float parameter types.""" space = vz.SearchSpace() root = space.root root.add_float_param('lineardouble', -1., 2.) root.add_float_param('logdouble', 1e-4, 1e2, scale_type=vz.ScaleType.LOG) return space
Trials of search space with float parameter types.
def flat_continuous_space_with_scaling_trials( count: int = 1, ) -> list[vz.TrialSuggestion]: """Trials of search space with float parameter types.""" trials = [] for _ in range(count): trials.append( vz.Trial({ 'lineardouble': np.random.uniform(low=-1.0, high=2.0), 'logdou...
Search space with all parameter types.
def flat_space_with_all_types() -> vz.SearchSpace: """Search space with all parameter types.""" space = vz.SearchSpace() root = space.root root.add_float_param('lineardouble', -1., 2.) root.add_float_param('logdouble', 1e-4, 1e2, scale_type=vz.ScaleType.LOG) root.add_int_param('integer', -2, 2) root.add_...
Conditional space for a simple AutoML task.
def conditional_automl_space() -> vz.SearchSpace: """Conditional space for a simple AutoML task.""" space = vz.SearchSpace() root = space.select_root() root.add_categorical_param( 'model_type', ['linear', 'dnn'], default_value='dnn' ) dnn = root.select('model_type', ['dnn']) dnn.add_float_param( ...
Creates a shape validator for attrs. For example, _shape_equals(lambda s : [3, None]) validates that the shape has length 2 and its first element is 3. Code Example: @attrs.define class TestAttr: x = attrs.field(validator=attrs_utils.shape_equals(lambda v: (3, v.d))) d = attrs.field() _TestAttr(np.zeros([3, 2]),...
def shape_equals(instance_to_shape: Callable[[Any], Collection[Optional[int]]]): """Creates a shape validator for attrs. For example, _shape_equals(lambda s : [3, None]) validates that the shape has length 2 and its first element is 3. Code Example: @attrs.define class TestAttr: x = attrs.field(valida...
Example: json.loads(..., object_hook=numpy_hook).
def numpy_hook(obj: Any) -> Any: """Example: json.loads(..., object_hook=numpy_hook).""" if 'dtype' not in obj: return obj if 'shape' not in obj: return obj return np.array(obj['value'], dtype=obj['dtype']).reshape(obj['shape'])
Context manager for turning on the profiler.
def collect_events() -> Generator[List[ProfileEvent], None, None]: """Context manager for turning on the profiler.""" try: if _GLOBAL_SOTRAGE.active: raise RuntimeError( 'There can be only one `collect_events()` context manager active at' ' the same time.' ) _GLOBAL_SOTRAGE.a...
Context manager for measuring the timing. Example: ``` with timeit('scope_name') as duration: ... duration() # returns the duration. ``` Also see: record_runtime, which is the decorator equivalent of this. Args: name: also_log: If True, also create a log. Yields: A callable with zero input arguments. Retur...
def timeit( name: str, also_log: bool = False ) -> Generator[Callable[[], datetime.timedelta], None, None]: """Context manager for measuring the timing. Example: ``` with timeit('scope_name') as duration: ... duration() # returns the duration. ``` Also see: record_runtime, which is the decorato...
Decorates the function to record the runtime. Also see: timeit(), which is the context manager equivalent of this. Args: func: Function being decorated. name_prefix: A prefix to add to the function name. name: The name to record. Defaults to func.__qualname__. also_log: Whether to also logging.info the runtim...
def record_runtime( func: Optional[Callable[..., Any]] = None, *, name_prefix: str = '', name: str = '', also_log: bool = False, block_until_ready: bool = False, ) -> Any: """Decorates the function to record the runtime. Also see: timeit(), which is the context manager equivalent of this. ...
Decorates the function to record the runtime of functions. Args: func: Function being decorated. name: The name to record. Defaults to func.__qualname__. also_log: Whether to also logging.info the runtime duration. Returns: Decorated function, or decorator.
def record_tracing( func: Optional[Callable[..., Any]] = None, *, name: str = '', also_log: bool = True, ) -> Any: """Decorates the function to record the runtime of functions. Args: func: Function being decorated. name: The name to record. Defaults to func.__qualname__. also_log: Wheth...