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 test_event_hooks_with_redirect(): """ A redirect request should trigger additional 'request' and 'response' event hooks. """ events = [] def on_request(request): events.append({"event": "request", "headers": dict(request.headers)}) def on_response(response): events.append(...
A redirect request should trigger additional 'request' and 'response' event hooks.
test_event_hooks_with_redirect
python
encode/httpx
tests/client/test_event_hooks.py
https://github.com/encode/httpx/blob/master/tests/client/test_event_hooks.py
BSD-3-Clause
def test_remove_default_header(): """ Remove a default header from the Client. """ url = "http://example.org/echo_headers" client = httpx.Client(transport=httpx.MockTransport(echo_headers)) del client.headers["User-Agent"] response = client.get(url) assert response.status_code == 200 ...
Remove a default header from the Client.
test_remove_default_header
python
encode/httpx
tests/client/test_headers.py
https://github.com/encode/httpx/blob/master/tests/client/test_headers.py
BSD-3-Clause
def test_host_with_auth_and_port_in_url(): """ The Host header should only include the hostname, or hostname:port (for non-default ports only). Any userinfo or default port should not be present. """ url = "http://username:password@example.org:80/echo_headers" client = httpx.Client(transpor...
The Host header should only include the hostname, or hostname:port (for non-default ports only). Any userinfo or default port should not be present.
test_host_with_auth_and_port_in_url
python
encode/httpx
tests/client/test_headers.py
https://github.com/encode/httpx/blob/master/tests/client/test_headers.py
BSD-3-Clause
def test_host_with_non_default_port_in_url(): """ If the URL includes a non-default port, then it should be included in the Host header. """ url = "http://username:password@example.org:123/echo_headers" client = httpx.Client(transport=httpx.MockTransport(echo_headers)) response = client.get...
If the URL includes a non-default port, then it should be included in the Host header.
test_host_with_non_default_port_in_url
python
encode/httpx
tests/client/test_headers.py
https://github.com/encode/httpx/blob/master/tests/client/test_headers.py
BSD-3-Clause
def url_to_origin(url: str) -> httpcore.URL: """ Given a URL string, return the origin in the raw tuple format that `httpcore` uses for it's representation. """ u = httpx.URL(url) return httpcore.URL(scheme=u.raw_scheme, host=u.raw_host, port=u.port, target="/")
Given a URL string, return the origin in the raw tuple format that `httpcore` uses for it's representation.
url_to_origin
python
encode/httpx
tests/client/test_proxies.py
https://github.com/encode/httpx/blob/master/tests/client/test_proxies.py
BSD-3-Clause
def test_head_redirect(): """ Contrary to Requests, redirects remain enabled by default for HEAD requests. """ client = httpx.Client(transport=httpx.MockTransport(redirects)) response = client.head("https://example.org/redirect_302", follow_redirects=True) assert response.status_code == httpx.co...
Contrary to Requests, redirects remain enabled by default for HEAD requests.
test_head_redirect
python
encode/httpx
tests/client/test_redirects.py
https://github.com/encode/httpx/blob/master/tests/client/test_redirects.py
BSD-3-Clause
def test_body_redirect(): """ A 308 redirect should preserve the request body. """ client = httpx.Client(transport=httpx.MockTransport(redirects)) url = "https://example.org/redirect_body" content = b"Example request body" response = client.post(url, content=content, follow_redirects=True) ...
A 308 redirect should preserve the request body.
test_body_redirect
python
encode/httpx
tests/client/test_redirects.py
https://github.com/encode/httpx/blob/master/tests/client/test_redirects.py
BSD-3-Clause
def test_no_body_redirect(): """ A 303 redirect should remove the request body. """ client = httpx.Client(transport=httpx.MockTransport(redirects)) url = "https://example.org/redirect_no_body" content = b"Example request body" response = client.post(url, content=content, follow_redirects=Tru...
A 303 redirect should remove the request body.
test_no_body_redirect
python
encode/httpx
tests/client/test_redirects.py
https://github.com/encode/httpx/blob/master/tests/client/test_redirects.py
BSD-3-Clause
def test_headers_dict_repr(): """ Headers should display with a dict repr by default. """ headers = httpx.Headers({"custom": "example"}) assert repr(headers) == "Headers({'custom': 'example'})"
Headers should display with a dict repr by default.
test_headers_dict_repr
python
encode/httpx
tests/models/test_headers.py
https://github.com/encode/httpx/blob/master/tests/models/test_headers.py
BSD-3-Clause
def test_headers_list_repr(): """ Headers should display with a list repr if they include multiple identical keys. """ headers = httpx.Headers([("custom", "example 1"), ("custom", "example 2")]) assert ( repr(headers) == "Headers([('custom', 'example 1'), ('custom', 'example 2')])" )
Headers should display with a list repr if they include multiple identical keys.
test_headers_list_repr
python
encode/httpx
tests/models/test_headers.py
https://github.com/encode/httpx/blob/master/tests/models/test_headers.py
BSD-3-Clause
def test_headers_decode_ascii(): """ Headers should decode as ascii by default. """ raw_headers = [(b"Custom", b"Example")] headers = httpx.Headers(raw_headers) assert dict(headers) == {"custom": "Example"} assert headers.encoding == "ascii"
Headers should decode as ascii by default.
test_headers_decode_ascii
python
encode/httpx
tests/models/test_headers.py
https://github.com/encode/httpx/blob/master/tests/models/test_headers.py
BSD-3-Clause
def test_multiple_headers(): """ `Headers.get_list` should support both split_commas=False and split_commas=True. """ h = httpx.Headers([("set-cookie", "a, b"), ("set-cookie", "c")]) assert h.get_list("Set-Cookie") == ["a, b", "c"] h = httpx.Headers([("vary", "a, b"), ("vary", "c")]) assert...
`Headers.get_list` should support both split_commas=False and split_commas=True.
test_multiple_headers
python
encode/httpx
tests/models/test_headers.py
https://github.com/encode/httpx/blob/master/tests/models/test_headers.py
BSD-3-Clause
def test_sensitive_headers(header): """ Some headers should be obfuscated because they contain sensitive data. """ value = "s3kr3t" h = httpx.Headers({header: value}) assert repr(h) == "Headers({'%s': '[secure]'})" % header
Some headers should be obfuscated because they contain sensitive data.
test_sensitive_headers
python
encode/httpx
tests/models/test_headers.py
https://github.com/encode/httpx/blob/master/tests/models/test_headers.py
BSD-3-Clause
def test_ignore_transfer_encoding_header_if_content_length_exists(): """ `Transfer-Encoding` should be ignored if `Content-Length` has been set explicitly. See https://github.com/encode/httpx/issues/1168 """ def streaming_body(data: bytes) -> typing.Iterator[bytes]: yield data # pragma: no...
`Transfer-Encoding` should be ignored if `Content-Length` has been set explicitly. See https://github.com/encode/httpx/issues/1168
test_ignore_transfer_encoding_header_if_content_length_exists
python
encode/httpx
tests/models/test_requests.py
https://github.com/encode/httpx/blob/master/tests/models/test_requests.py
BSD-3-Clause
def test_response_no_charset_with_ascii_content(): """ A response with ascii encoded content should decode correctly, even with no charset specified. """ content = b"Hello, world!" headers = {"Content-Type": "text/plain"} response = httpx.Response( 200, content=content, ...
A response with ascii encoded content should decode correctly, even with no charset specified.
test_response_no_charset_with_ascii_content
python
encode/httpx
tests/models/test_responses.py
https://github.com/encode/httpx/blob/master/tests/models/test_responses.py
BSD-3-Clause
def test_response_non_text_encoding(): """ Default to attempting utf-8 encoding for non-text content-type headers. """ headers = {"Content-Type": "image/png"} response = httpx.Response( 200, content=b"xyz", headers=headers, ) assert response.text == "xyz" assert r...
Default to attempting utf-8 encoding for non-text content-type headers.
test_response_non_text_encoding
python
encode/httpx
tests/models/test_responses.py
https://github.com/encode/httpx/blob/master/tests/models/test_responses.py
BSD-3-Clause
def test_url_with_empty_query(): """ URLs with and without a trailing `?` but an empty query component should preserve the information on the raw path. """ url = httpx.URL("https://www.example.com/path") assert url.path == "/path" assert url.query == b"" assert url.raw_path == b"/path" ...
URLs with and without a trailing `?` but an empty query component should preserve the information on the raw path.
test_url_with_empty_query
python
encode/httpx
tests/models/test_url.py
https://github.com/encode/httpx/blob/master/tests/models/test_url.py
BSD-3-Clause
def test_url_ipv4_like_host(): """rare host names used to quality as IPv4""" url = httpx.URL("https://023b76x43144/") assert url.host == "023b76x43144"
rare host names used to quality as IPv4
test_url_ipv4_like_host
python
encode/httpx
tests/models/test_url.py
https://github.com/encode/httpx/blob/master/tests/models/test_url.py
BSD-3-Clause
def test_url_eq_str(): """ Ensure that `httpx.URL` supports the equality operator. """ url = httpx.URL("https://example.org:123/path/to/somewhere?abc=123#anchor") assert url == "https://example.org:123/path/to/somewhere?abc=123#anchor" assert str(url) == url
Ensure that `httpx.URL` supports the equality operator.
test_url_eq_str
python
encode/httpx
tests/models/test_url.py
https://github.com/encode/httpx/blob/master/tests/models/test_url.py
BSD-3-Clause
def test_url_set(): """ Ensure that `httpx.URL` instances can be used in sets. """ urls = ( httpx.URL("http://example.org:123/path/to/somewhere"), httpx.URL("http://example.org:123/path/to/somewhere/else"), ) url_set = set(urls) assert all(url in urls for url in url_set)
Ensure that `httpx.URL` instances can be used in sets.
test_url_set
python
encode/httpx
tests/models/test_url.py
https://github.com/encode/httpx/blob/master/tests/models/test_url.py
BSD-3-Clause
def test_url_invalid_type(): """ Ensure that invalid types on `httpx.URL()` raise a `TypeError`. """ class ExternalURLClass: # representing external URL class pass with pytest.raises(TypeError): httpx.URL(ExternalURLClass()) # type: ignore
Ensure that invalid types on `httpx.URL()` raise a `TypeError`.
test_url_invalid_type
python
encode/httpx
tests/models/test_url.py
https://github.com/encode/httpx/blob/master/tests/models/test_url.py
BSD-3-Clause
def test_url_join_rfc3986(): """ URL joining tests, as-per reference examples in RFC 3986. https://tools.ietf.org/html/rfc3986#section-5.4 """ url = httpx.URL("http://example.com/b/c/d;p?q") assert url.join("g") == "http://example.com/b/c/g" assert url.join("./g") == "http://example.com/b...
URL joining tests, as-per reference examples in RFC 3986. https://tools.ietf.org/html/rfc3986#section-5.4
test_url_join_rfc3986
python
encode/httpx
tests/models/test_url.py
https://github.com/encode/httpx/blob/master/tests/models/test_url.py
BSD-3-Clause
def test_resolution_error_1833(): """ See https://github.com/encode/httpx/issues/1833 """ url = httpx.URL("https://example.com/?[]") assert url.join("/") == "https://example.com/"
See https://github.com/encode/httpx/issues/1833
test_resolution_error_1833
python
encode/httpx
tests/models/test_url.py
https://github.com/encode/httpx/blob/master/tests/models/test_url.py
BSD-3-Clause
def test_url_copywith_security(): """ Prevent unexpected changes on URL after calling copy_with (CVE-2021-41945) """ with pytest.raises(httpx.InvalidURL): httpx.URL("https://u:p@[invalid!]//evilHost/path?t=w#tw") url = httpx.URL("https://example.com/path?t=w#tw") bad = "https://xxxx:xxx...
Prevent unexpected changes on URL after calling copy_with (CVE-2021-41945)
test_url_copywith_security
python
encode/httpx
tests/models/test_url.py
https://github.com/encode/httpx/blob/master/tests/models/test_url.py
BSD-3-Clause
def test_url_set_param_manipulation(): """ Some basic URL query parameter manipulation. """ url = httpx.URL("https://example.org:123/?a=123") assert url.copy_set_param("a", "456") == "https://example.org:123/?a=456"
Some basic URL query parameter manipulation.
test_url_set_param_manipulation
python
encode/httpx
tests/models/test_url.py
https://github.com/encode/httpx/blob/master/tests/models/test_url.py
BSD-3-Clause
def package_files(prefix: str, directory: str, extension: str): """Get all the files to package.""" # from https://stackoverflow.com/a/36693250 paths = [] for (path, _, filenames) in os.walk(os.path.join(prefix, directory)): for filename in filenames: if filename.endswith(extension):...
Get all the files to package.
package_files
python
mosaicml/composer
setup.py
https://github.com/mosaicml/composer/blob/master/setup.py
Apache-2.0
def _parse_args() -> Namespace: """Parse command-line arguments. Returns: Namespace: Command-line arguments. """ args = ArgumentParser(description='Process a Docker matrix YAML file.') args.add_argument('yaml_file', type=FileType('r'), help='The YAML file to be processed.') args.add_arg...
Parse command-line arguments. Returns: Namespace: Command-line arguments.
_parse_args
python
mosaicml/composer
.github/bin/gen_docker_matrix.py
https://github.com/mosaicml/composer/blob/master/.github/bin/gen_docker_matrix.py
Apache-2.0
def main(args: Namespace): """Reads in the Docker build matrix and generates a GHA job matrix.""" image_configs = yaml.safe_load(args.yaml_file) for image_config in image_configs: # Convert tags list to a CSV string image_config['TAGS'] = ','.join(image_config['TAGS']) # Generate ...
Reads in the Docker build matrix and generates a GHA job matrix.
main
python
mosaicml/composer
.github/bin/gen_docker_matrix.py
https://github.com/mosaicml/composer/blob/master/.github/bin/gen_docker_matrix.py
Apache-2.0
def register( self, *modules: type[torch.nn.Module], ) -> Callable[[AlibiReplacementFunction], AlibiReplacementFunction]: """This decorator registers mappings from torch module types to their ALiBi surgery functions. To accommodate the specifics of composer's module surgery, our ALi...
This decorator registers mappings from torch module types to their ALiBi surgery functions. To accommodate the specifics of composer's module surgery, our ALiBi implementation uses a registry to create a ``Mapping[torch.nn.Module, AlibiReplacementFunction]``, where `AlibiReplacementFunction` is...
register
python
mosaicml/composer
composer/algorithms/alibi/attention_surgery_functions/utils.py
https://github.com/mosaicml/composer/blob/master/composer/algorithms/alibi/attention_surgery_functions/utils.py
Apache-2.0
def zero_and_freeze_expand_position_embeddings( module: torch.nn.Module, max_sequence_length: int, position_embedding_attribute: str, ) -> None: """Replaces weights with zero tensor and prevents them from being learned further. This is intended to be used specifically for "removing" positional embe...
Replaces weights with zero tensor and prevents them from being learned further. This is intended to be used specifically for "removing" positional embeddings.
zero_and_freeze_expand_position_embeddings
python
mosaicml/composer
composer/algorithms/alibi/attention_surgery_functions/utils.py
https://github.com/mosaicml/composer/blob/master/composer/algorithms/alibi/attention_surgery_functions/utils.py
Apache-2.0
def register_alibi(module: torch.nn.Module, n_heads: int, max_token_length: int, causal: bool) -> torch.nn.Module: """Adds ALiBi's linear attention biases as a buffer to the module.""" if causal: # e.g., for GPT # Modified from https://github.com/ofirpress/attention_with_linear_biases/blob/5b327adc6d13...
Adds ALiBi's linear attention biases as a buffer to the module.
register_alibi
python
mosaicml/composer
composer/algorithms/alibi/attention_surgery_functions/utils.py
https://github.com/mosaicml/composer/blob/master/composer/algorithms/alibi/attention_surgery_functions/utils.py
Apache-2.0
def bert_embedding_converter(module: torch.nn.Module, module_index: int, max_sequence_length: int) -> torch.nn.Module: """Removes positional embeddings and expands `position_ids` buffer to support `max_sequence_length` tokens. """ assert isinstance(module, (BertEmbeddings, RobertaEmbeddings)) del module...
Removes positional embeddings and expands `position_ids` buffer to support `max_sequence_length` tokens.
bert_embedding_converter
python
mosaicml/composer
composer/algorithms/alibi/attention_surgery_functions/_bert.py
https://github.com/mosaicml/composer/blob/master/composer/algorithms/alibi/attention_surgery_functions/_bert.py
Apache-2.0
def bert_attention_converter(module: torch.nn.Module, module_index: int, max_sequence_length: int) -> torch.nn.Module: """Adds ALiBi to Bert-style SelfAttention.""" assert isinstance(module, (BertSelfAttention, RobertaSelfAttention)) del module_index # unused module = register_alibi( module=mod...
Adds ALiBi to Bert-style SelfAttention.
bert_attention_converter
python
mosaicml/composer
composer/algorithms/alibi/attention_surgery_functions/_bert.py
https://github.com/mosaicml/composer/blob/master/composer/algorithms/alibi/attention_surgery_functions/_bert.py
Apache-2.0
def forward( self, hidden_states: torch.Tensor, attention_mask: Optional[torch.FloatTensor] = None, head_mask: Optional[torch.FloatTensor] = None, encoder_hidden_states: Optional[torch.FloatTensor] = None, encoder_attention_mask: Optional[torch.FloatTensor] = None, past_key_value: Optional[t...
Replication of identically-named attention function function ("forward") in Composer/HuggingFace BERT model's BERTSelfAttention (:func:`transformers.models.bert.modeling_bert.BERTSelfAttention.forward`), but this function implements ALiBi and will be used to replace the default attention function.
forward
python
mosaicml/composer
composer/algorithms/alibi/attention_surgery_functions/_bert.py
https://github.com/mosaicml/composer/blob/master/composer/algorithms/alibi/attention_surgery_functions/_bert.py
Apache-2.0
def gpt2_attention_converter(module: torch.nn.Module, module_index: int, max_sequence_length: int) -> torch.nn.Module: """Adds ALiBi to GPT2Attention and replaces the attention mask to support `max_sequence_length` tokens.""" assert isinstance(module, GPT2Attention) del module_index # unused module = ...
Adds ALiBi to GPT2Attention and replaces the attention mask to support `max_sequence_length` tokens.
gpt2_attention_converter
python
mosaicml/composer
composer/algorithms/alibi/attention_surgery_functions/_gpt2.py
https://github.com/mosaicml/composer/blob/master/composer/algorithms/alibi/attention_surgery_functions/_gpt2.py
Apache-2.0
def _attn(self, query, key, value, attention_mask=None, head_mask=None) -> tuple[torch.Tensor, torch.Tensor]: """Replication of identically-named attention function function ("_attn") in Composer/HuggingFace GPT2 model's GPT2Attention (:func:`transformers.models.gpt2.modeling_gpt2.GPT2Attention._attn`; `GitHub ...
Replication of identically-named attention function function ("_attn") in Composer/HuggingFace GPT2 model's GPT2Attention (:func:`transformers.models.gpt2.modeling_gpt2.GPT2Attention._attn`; `GitHub link <https://\ github.com/huggingface/transformers/blob/2e11a043374a6229ec129a4765ee4ba7517832b9/src/transformer...
_attn
python
mosaicml/composer
composer/algorithms/alibi/attention_surgery_functions/_gpt2.py
https://github.com/mosaicml/composer/blob/master/composer/algorithms/alibi/attention_surgery_functions/_gpt2.py
Apache-2.0
def enlarge_mask(module: torch.nn.Module, max_sequence_length: int) -> torch.nn.Module: """Increases the size of the attention mask in Composer/HuggingFace GPT2 model's GPT2Attention (:func:`transformers.models.gpt2.modeling_gpt2.GPT2Attention._attn`; `GitHub link <https://\\ github.com/huggingface/transfor...
Increases the size of the attention mask in Composer/HuggingFace GPT2 model's GPT2Attention (:func:`transformers.models.gpt2.modeling_gpt2.GPT2Attention._attn`; `GitHub link <https://\ github.com/huggingface/transformers/blob/2e11a043374a6229ec129a4765ee4ba7517832b9/src/transformers/\ models/gpt2/modeling_g...
enlarge_mask
python
mosaicml/composer
composer/algorithms/alibi/attention_surgery_functions/_gpt2.py
https://github.com/mosaicml/composer/blob/master/composer/algorithms/alibi/attention_surgery_functions/_gpt2.py
Apache-2.0
def augmix_image( img: ImgT, severity: int = 3, depth: int = -1, width: int = 3, alpha: float = 1.0, augmentation_set: list = augmentation_sets['all'], ) -> ImgT: r"""Applies the AugMix (`Hendrycks et al, 2020 <http://arxiv.org/abs/1912.02781>`_) data augmentation. This function works o...
Applies the AugMix (`Hendrycks et al, 2020 <http://arxiv.org/abs/1912.02781>`_) data augmentation. This function works on a single image or batch of images. See :class:`.AugMix` and the :doc:`Method Card </method_cards/augmix>` for details. This function only acts on a single image (or batch) per call and ...
augmix_image
python
mosaicml/composer
composer/algorithms/augmix/augmix.py
https://github.com/mosaicml/composer/blob/master/composer/algorithms/augmix/augmix.py
Apache-2.0
def _log_results(self, event: Event, state: State, logger: Logger) -> None: """Logs the result of BlurPool application, including the number of layers that have been replaced.""" assert state.model is not None num_blurpool_layers = module_surgery.count_module_instances(state.model, BlurMaxPool2...
Logs the result of BlurPool application, including the number of layers that have been replaced.
_log_results
python
mosaicml/composer
composer/algorithms/blurpool/blurpool.py
https://github.com/mosaicml/composer/blob/master/composer/algorithms/blurpool/blurpool.py
Apache-2.0
def blur_2d( input: torch.Tensor, channels: int = -1, stride: _size_2_t = 1, filter: Optional[torch.Tensor] = None, ) -> torch.Tensor: """Applies a spatial low-pass filter. Args: input (torch.Tensor): A 4d tensor of shape NCHW channels (int, optional): The number of channels in ...
Applies a spatial low-pass filter. Args: input (torch.Tensor): A 4d tensor of shape NCHW channels (int, optional): The number of channels in the input tensor. If non-positive, then dynamic control flow is used to determine the number of channels. If positive, then static con...
blur_2d
python
mosaicml/composer
composer/algorithms/blurpool/blurpool_layers.py
https://github.com/mosaicml/composer/blob/master/composer/algorithms/blurpool/blurpool_layers.py
Apache-2.0
def blurmax_pool2d( input: torch.Tensor, kernel_size: Optional[_size_2_t] = None, stride: _size_2_t = 2, padding: _size_2_t = 0, dilation: _size_2_t = 1, ceil_mode: bool = False, filter: Optional[torch.Tensor] = None, ) -> torch.Tensor: """Max-pooling with anti-aliasing. This is a n...
Max-pooling with anti-aliasing. This is a nearly drop-in replacement for PyTorch's :func:`torch.nn.functional.max_pool2d`. The only API difference is that the parameter ``return_indices`` is not available, because it is ill-defined when using anti-aliasing. See the associated `paper <http://proceeding...
blurmax_pool2d
python
mosaicml/composer
composer/algorithms/blurpool/blurpool_layers.py
https://github.com/mosaicml/composer/blob/master/composer/algorithms/blurpool/blurpool_layers.py
Apache-2.0
def colout_batch( sample: Union[ImgT, tuple[ImgT, ImgT]], p_row: float = 0.15, p_col: float = 0.15, resize_target: Union[bool, str] = 'auto', ) -> Union[torch.Tensor, ImgT, tuple[Tensor, Tensor], tuple[ImgT, ImgT]]: """Applies ColOut augmentation to a batch of images and (optionally) targets, dr...
Applies ColOut augmentation to a batch of images and (optionally) targets, dropping the same random rows and columns from all images and targets in a batch. See the :doc:`Method Card </method_cards/colout>` for more details. Example: .. testcode:: from composer.algorithms.colout impo...
colout_batch
python
mosaicml/composer
composer/algorithms/colout/colout.py
https://github.com/mosaicml/composer/blob/master/composer/algorithms/colout/colout.py
Apache-2.0
def __call__( self, sample: Union[ImgT, tuple[ImgT, ImgT]], ) -> Union[torch.Tensor, ImgT, tuple[Tensor, Tensor], tuple[ImgT, ImgT]]: """Drops random rows and columns from up to two images. Args: sample (torch.Tensor | PIL.Image | tuple[torch.Tensor, torch.Tensor] | tupl...
Drops random rows and columns from up to two images. Args: sample (torch.Tensor | PIL.Image | tuple[torch.Tensor, torch.Tensor] | tuple[PIL.Image, PIL.Image]): A single image or a 2-tuple of images as either :class:`torch.Tensor` or :class:`PIL.Image`. Returns: ...
__call__
python
mosaicml/composer
composer/algorithms/colout/colout.py
https://github.com/mosaicml/composer/blob/master/composer/algorithms/colout/colout.py
Apache-2.0
def _apply_sample(self, state: State) -> None: """Add the ColOut dataset transform to the dataloader.""" assert isinstance(state.dataloader, torch.utils.data.DataLoader), 'dataloader type checked on match()' dataset = state.dataloader.dataset transform = ColOutTransform(p_row=self.p_row...
Add the ColOut dataset transform to the dataloader.
_apply_sample
python
mosaicml/composer
composer/algorithms/colout/colout.py
https://github.com/mosaicml/composer/blob/master/composer/algorithms/colout/colout.py
Apache-2.0
def _apply_batch(self, state: State) -> None: """Transform a batch of images using the ColOut augmentation.""" inputs, target = state.batch_get_item(key=self.input_key), state.batch_get_item(key=self.target_key) assert isinstance(inputs, Tensor) and isinstance(target, Tensor), \ 'Inp...
Transform a batch of images using the ColOut augmentation.
_apply_batch
python
mosaicml/composer
composer/algorithms/colout/colout.py
https://github.com/mosaicml/composer/blob/master/composer/algorithms/colout/colout.py
Apache-2.0
def _should_resize_target(sample: Union[ImgT, tuple[ImgT, ImgT]], resize_target: Union[bool, str]) -> bool: """Helper function to determine if both objects in the tuple should be resized. Decision is based on ``resize_target`` and if both objects in the tuple have the same spatial size. """ sample = e...
Helper function to determine if both objects in the tuple should be resized. Decision is based on ``resize_target`` and if both objects in the tuple have the same spatial size.
_should_resize_target
python
mosaicml/composer
composer/algorithms/colout/colout.py
https://github.com/mosaicml/composer/blob/master/composer/algorithms/colout/colout.py
Apache-2.0
def cutmix_batch( input: Tensor, target: Tensor, length: Optional[float] = None, alpha: float = 1., bbox: Optional[tuple] = None, indices: Optional[torch.Tensor] = None, uniform_sampling: bool = False, ) -> tuple[torch.Tensor, torch.Tensor, float, tuple]: """Create new samples using comb...
Create new samples using combinations of pairs of samples. This is done by masking a region of each image in ``input`` and filling the masked region with the corresponding content from a random different image in``input``. The position of the masked region is determined by drawing a center point u...
cutmix_batch
python
mosaicml/composer
composer/algorithms/cutmix/cutmix.py
https://github.com/mosaicml/composer/blob/master/composer/algorithms/cutmix/cutmix.py
Apache-2.0
def _gen_cutmix_coef(alpha: float) -> float: """Generates lambda from ``Beta(alpha, alpha)``. Args: alpha (float): Parameter for the ``Beta(alpha, alpha)`` distribution. Returns: cutmix_lambda: Lambda parameter for performing CutMix. """ # First check if alpha is positive. asse...
Generates lambda from ``Beta(alpha, alpha)``. Args: alpha (float): Parameter for the ``Beta(alpha, alpha)`` distribution. Returns: cutmix_lambda: Lambda parameter for performing CutMix.
_gen_cutmix_coef
python
mosaicml/composer
composer/algorithms/cutmix/cutmix.py
https://github.com/mosaicml/composer/blob/master/composer/algorithms/cutmix/cutmix.py
Apache-2.0
def _rand_bbox( W: int, H: int, cutmix_lambda: float, cx: Optional[int] = None, cy: Optional[int] = None, uniform_sampling: bool = False, ) -> tuple[int, int, int, int]: """Randomly samples a bounding box with area determined by ``cutmix_lambda``. Adapted from original implementation ht...
Randomly samples a bounding box with area determined by ``cutmix_lambda``. Adapted from original implementation https://github.com/clovaai/CutMix-PyTorch Args: W (int): Width of the image H (int): Height of the image cutmix_lambda (float): Lambda param from cutmix, used to set the area...
_rand_bbox
python
mosaicml/composer
composer/algorithms/cutmix/cutmix.py
https://github.com/mosaicml/composer/blob/master/composer/algorithms/cutmix/cutmix.py
Apache-2.0
def _adjust_lambda(x: Tensor, bbox: tuple) -> float: """Rescale the cutmix lambda according to the size of the clipped bounding box. Args: x (torch.Tensor): input tensor of shape ``(B, d1, d2, ..., dn)``, B is batch size, d1-dn are feature dimensions. bbox (tuple): (x1, y1, x2, y2) ...
Rescale the cutmix lambda according to the size of the clipped bounding box. Args: x (torch.Tensor): input tensor of shape ``(B, d1, d2, ..., dn)``, B is batch size, d1-dn are feature dimensions. bbox (tuple): (x1, y1, x2, y2) coordinates of the boundind box, obeying x2 > x1, y2 > y1. ...
_adjust_lambda
python
mosaicml/composer
composer/algorithms/cutmix/cutmix.py
https://github.com/mosaicml/composer/blob/master/composer/algorithms/cutmix/cutmix.py
Apache-2.0
def cutout_batch(input: ImgT, num_holes: int = 1, length: float = 0.5, uniform_sampling: bool = False) -> ImgT: """See :class:`.CutOut`. Args: input (PIL.Image.Image | torch.Tensor): Image or batch of images. If a :class:`torch.Tensor`, must be a single image of shape ``(C, H, W)`` ...
See :class:`.CutOut`. Args: input (PIL.Image.Image | torch.Tensor): Image or batch of images. If a :class:`torch.Tensor`, must be a single image of shape ``(C, H, W)`` or a batch of images of shape ``(N, C, H, W)``. num_holes: Integer number of holes to cut out. Default: ``1...
cutout_batch
python
mosaicml/composer
composer/algorithms/cutout/cutout.py
https://github.com/mosaicml/composer/blob/master/composer/algorithms/cutout/cutout.py
Apache-2.0
def compute_ema( model: torch.nn.Module, ema_model: Union[torch.nn.Module, EMAParameters], smoothing: float = 0.99, ) -> None: r"""Updates the weights of ``ema_model`` to be closer to the weights of ``model`` according to an exponential weighted average. Weights are updated according to .. math...
Updates the weights of ``ema_model`` to be closer to the weights of ``model`` according to an exponential weighted average. Weights are updated according to .. math:: W_{ema_model}^{(t+1)} = smoothing\times W_{ema_model}^{(t)}+(1-smoothing)\times W_{model}^{(t)} The update to ``ema_model`` happens...
compute_ema
python
mosaicml/composer
composer/algorithms/ema/ema.py
https://github.com/mosaicml/composer/blob/master/composer/algorithms/ema/ema.py
Apache-2.0
def get_model_context_manager(model: torch.nn.Module): """Summons full params for FSDP, which is required to update sharded params.""" fsdp_enabled = misc.is_model_fsdp(model) model_context_manager = contextlib.nullcontext() if fsdp_enabled: model_context_manager = model.module.summon_full_param...
Summons full params for FSDP, which is required to update sharded params.
get_model_context_manager
python
mosaicml/composer
composer/algorithms/ema/ema.py
https://github.com/mosaicml/composer/blob/master/composer/algorithms/ema/ema.py
Apache-2.0
def ensure_compatible_state_dict(self, state: dict[str, Any]): """Ensure state dicts created prior to Composer 0.13.0 are compatible with later versions.""" # Version 0.13.0 and later state dicts will not include training_model. if 'training_model' not in state: return state ...
Ensure state dicts created prior to Composer 0.13.0 are compatible with later versions.
ensure_compatible_state_dict
python
mosaicml/composer
composer/algorithms/ema/ema.py
https://github.com/mosaicml/composer/blob/master/composer/algorithms/ema/ema.py
Apache-2.0
def get_ema_model(self, model: torch.nn.Module) -> torch.nn.Module: """Replaces the parameters of the supplied model with the ema parameters if they are not already active. Args: model (torch.nn.Module): The model to replace the parameters of. Returns: torch.nn.Module: ...
Replaces the parameters of the supplied model with the ema parameters if they are not already active. Args: model (torch.nn.Module): The model to replace the parameters of. Returns: torch.nn.Module: The model with the ema parameters.
get_ema_model
python
mosaicml/composer
composer/algorithms/ema/ema.py
https://github.com/mosaicml/composer/blob/master/composer/algorithms/ema/ema.py
Apache-2.0
def get_training_model(self, model: torch.nn.Module) -> torch.nn.Module: """Replaces the parameters of the supplied model with the training parameters if they are not already active. Args: model (torch.nn.Module): The model to replace the parameters of. Returns: torch.n...
Replaces the parameters of the supplied model with the training parameters if they are not already active. Args: model (torch.nn.Module): The model to replace the parameters of. Returns: torch.nn.Module: The model with the training parameters.
get_training_model
python
mosaicml/composer
composer/algorithms/ema/ema.py
https://github.com/mosaicml/composer/blob/master/composer/algorithms/ema/ema.py
Apache-2.0
def swap_params(self, model: torch.nn.Module): """Swaps the parameters and buffers of a model with the ema parameters.""" model_context_manager = get_model_context_manager(model) with torch.no_grad(): ema_params = self.named_parameters_dict ema_buffers = self.named_buffe...
Swaps the parameters and buffers of a model with the ema parameters.
swap_params
python
mosaicml/composer
composer/algorithms/ema/ema.py
https://github.com/mosaicml/composer/blob/master/composer/algorithms/ema/ema.py
Apache-2.0
def transfer_ema_params(self, model: torch.nn.Module): """Transfers the parameters and buffers from the ema model to the supplied model.""" model_context_manager = get_model_context_manager(model) with model_context_manager: with torch.no_grad(): for name, param in m...
Transfers the parameters and buffers from the ema model to the supplied model.
transfer_ema_params
python
mosaicml/composer
composer/algorithms/ema/ema.py
https://github.com/mosaicml/composer/blob/master/composer/algorithms/ema/ema.py
Apache-2.0
def move_params_to_device(self, destination_model: torch.nn.Module): """Moves the ema parameters and buffers to the device of a destination model.""" model_context_manager = get_model_context_manager(destination_model) with model_context_manager: for name, param in destination_model...
Moves the ema parameters and buffers to the device of a destination model.
move_params_to_device
python
mosaicml/composer
composer/algorithms/ema/ema.py
https://github.com/mosaicml/composer/blob/master/composer/algorithms/ema/ema.py
Apache-2.0
def _factorize_conv2d_modules( model: torch.nn.Module, min_channels: int = 512, latent_channels: Union[int, float] = 0.25, optimizers: Optional[Union[Optimizer, Sequence[Optimizer]]] = None, ): """Replaces :class:`torch.nn.Conv2d` modules in ``model`` with :class:`.FactorizedConv2d` modules. ...
Replaces :class:`torch.nn.Conv2d` modules in ``model`` with :class:`.FactorizedConv2d` modules. See :class:`.Factorize` for details.
_factorize_conv2d_modules
python
mosaicml/composer
composer/algorithms/factorize/factorize.py
https://github.com/mosaicml/composer/blob/master/composer/algorithms/factorize/factorize.py
Apache-2.0
def _factorize_linear_modules( model: torch.nn.Module, min_features: int = 512, latent_features: Union[int, float] = 0.25, optimizers: Optional[Union[Optimizer, Sequence[Optimizer]]] = None, ): """Replaces :class:`torch.nn.Linear` modules in ``model`` with :class:`.FactorizedLinear` modules. ...
Replaces :class:`torch.nn.Linear` modules in ``model`` with :class:`.FactorizedLinear` modules. See :class:`.Factorize` for details.
_factorize_linear_modules
python
mosaicml/composer
composer/algorithms/factorize/factorize.py
https://github.com/mosaicml/composer/blob/master/composer/algorithms/factorize/factorize.py
Apache-2.0
def factorize_matrix( X: torch.Tensor, Y: torch.Tensor, Wa: torch.Tensor, Wb: Optional[torch.Tensor] = None, bias: Optional[torch.Tensor] = None, rank: Union[int, float] = .25, n_iters: int = 3, ) -> LowRankSolution: """Approximates a matrix by factorizing it into a product of two smalle...
Approximates a matrix by factorizing it into a product of two smaller matrices. Given a matrix ``W`` of shape ``[D, M]``, a bias vector of length ``M``, and a target rank ``rank < D``, returns a solution ``(Wa, Wb, new_bias)`` of tensors of shapes ``[N, rank]``, ``[rank, D]``, and ``M``, respectively. ...
factorize_matrix
python
mosaicml/composer
composer/algorithms/factorize/factorize_core.py
https://github.com/mosaicml/composer/blob/master/composer/algorithms/factorize/factorize_core.py
Apache-2.0
def factorize_conv2d( X: torch.Tensor, Wa: torch.Tensor, Wb: Optional[torch.Tensor] = None, rank: Union[int, float] = .25, biasA: Optional[torch.Tensor] = None, biasB: Optional[torch.Tensor] = None, n_iters=3, **conv2d_kwargs, ) -> LowRankSolution: """Approximates a :math:`K \\times ...
Approximates a :math:`K \times K` convolution by factorizing it into a :math:`K \times K` convolution with fewer channels followed by a :math:`1 \times 1` convolution. Given a convolutional weight tensor ``W`` for a 2d convolution of shape ``[out_channels, in_channels, k_h, k_w]`` and a vector ``bias`...
factorize_conv2d
python
mosaicml/composer
composer/algorithms/factorize/factorize_core.py
https://github.com/mosaicml/composer/blob/master/composer/algorithms/factorize/factorize_core.py
Apache-2.0
def factorizing_could_speedup(module: torch.nn.Module, latent_size: Union[int, float]): """Whether factorizing a module a given amount could possibly yield a benefit. This computation is based on the number of multiply-add operations involved in the module's current forward pass versus the number that woul...
Whether factorizing a module a given amount could possibly yield a benefit. This computation is based on the number of multiply-add operations involved in the module's current forward pass versus the number that would be involved if it were factorized into two modules using the specified latent size. The ...
factorizing_could_speedup
python
mosaicml/composer
composer/algorithms/factorize/factorize_modules.py
https://github.com/mosaicml/composer/blob/master/composer/algorithms/factorize/factorize_modules.py
Apache-2.0
def set_rank(self, input: torch.Tensor, rank: int) -> None: """Makes the module factorize using a ``rank``-dimensional latent representation. ``rank`` can be large enough that the factorization increases the number of multiply-add operations, but not larger than the current latent rank....
Makes the module factorize using a ``rank``-dimensional latent representation. ``rank`` can be large enough that the factorization increases the number of multiply-add operations, but not larger than the current latent rank. Args: input (torch.Tensor): Tensor that can be pa...
set_rank
python
mosaicml/composer
composer/algorithms/factorize/factorize_modules.py
https://github.com/mosaicml/composer/blob/master/composer/algorithms/factorize/factorize_modules.py
Apache-2.0
def should_factorize(self, proposed_rank: Union[int, float]) -> bool: """Whether factorizing with a given rank would reduce the number of multiply-add operations.""" proposed_rank = self._clean_latent_size(proposed_rank) return proposed_rank <= self._max_rank_with_speedup()
Whether factorizing with a given rank would reduce the number of multiply-add operations.
should_factorize
python
mosaicml/composer
composer/algorithms/factorize/factorize_modules.py
https://github.com/mosaicml/composer/blob/master/composer/algorithms/factorize/factorize_modules.py
Apache-2.0
def from_BertOutput( layer: torch.nn.Module, module_index: int, act_fn: Callable[[torch.Tensor], torch.Tensor], gated_layer_bias: bool = False, non_gated_layer_bias: bool = False, ) -> BERTGatedFFOutput: """Defines a replacement policy from a :class:`transformers.models.bert.modeling_bert.BertOu...
Defines a replacement policy from a :class:`transformers.models.bert.modeling_bert.BertOutput` to a :class:`composer.algorithms.gated_linear_units.gated_linear_unit_layers.BERTGatedFFOutput`
from_BertOutput
python
mosaicml/composer
composer/algorithms/gated_linear_units/gated_linear_units.py
https://github.com/mosaicml/composer/blob/master/composer/algorithms/gated_linear_units/gated_linear_units.py
Apache-2.0
def forward(self, hidden_states: torch.Tensor, residual_connection: torch.Tensor): """ Args: hidden_states (torch.Tensor): The hidden states from the attention matrix. residual_connection (torch.Tensor): The residual connection to add before the LayerNorm operator. """ ...
Args: hidden_states (torch.Tensor): The hidden states from the attention matrix. residual_connection (torch.Tensor): The residual connection to add before the LayerNorm operator.
forward
python
mosaicml/composer
composer/algorithms/gated_linear_units/gated_linear_unit_layers.py
https://github.com/mosaicml/composer/blob/master/composer/algorithms/gated_linear_units/gated_linear_unit_layers.py
Apache-2.0
def _log_results(self, event: Event, state: State, logger: Optional[Logger] = None) -> None: """Logs the result of GhostBatchNorm applications, including the number of modules that have been replaced.""" assert state.model is not None num_new_modules = module_surgery.count_module_instances(stat...
Logs the result of GhostBatchNorm applications, including the number of modules that have been replaced.
_log_results
python
mosaicml/composer
composer/algorithms/ghost_batchnorm/ghost_batchnorm.py
https://github.com/mosaicml/composer/blob/master/composer/algorithms/ghost_batchnorm/ghost_batchnorm.py
Apache-2.0
def apply_gradient_clipping( model: Union[ComposerModel, torch.nn.Module], clipping_type: str, clipping_threshold: float, fsdp_enabled: bool, ): """Clips all gradients in model based on specified clipping_type. Args: model (ComposerModel or torch.nn.Module): The model that we want to ap...
Clips all gradients in model based on specified clipping_type. Args: model (ComposerModel or torch.nn.Module): The model that we want to apply gradient clipping. clipping_type ('adaptive', 'norm', 'value'): String denoting which type of gradient clipping to do. The options are: 'norm', ...
apply_gradient_clipping
python
mosaicml/composer
composer/algorithms/gradient_clipping/gradient_clipping.py
https://github.com/mosaicml/composer/blob/master/composer/algorithms/gradient_clipping/gradient_clipping.py
Apache-2.0
def _apply_agc( parameters: Union[torch.Tensor, Iterable[torch.Tensor]], clipping_threshold: float, ) -> None: """Clips all gradients in model based on ratio of gradient norms to parameter norms. Args: parameters (torch.Tensor or Iterable[torch.Tensor]): The parameters to of the mode...
Clips all gradients in model based on ratio of gradient norms to parameter norms. Args: parameters (torch.Tensor or Iterable[torch.Tensor]): The parameters to of the model for whose gradients we will clip clipping_threshold (float, optional): The largest acceptable ratio between grad ...
_apply_agc
python
mosaicml/composer
composer/algorithms/gradient_clipping/gradient_clipping.py
https://github.com/mosaicml/composer/blob/master/composer/algorithms/gradient_clipping/gradient_clipping.py
Apache-2.0
def _get_clipped_gradient_coeff(weights: torch.Tensor, grad: torch.Tensor, clipping_threshold: float = 0.01): """Clips all gradients in model based on ratio of gradient norms to parameter norms. Gradients whose norms exceed .. math:: weight_norm * clipping_threshold are scaled down by .. math:: ...
Clips all gradients in model based on ratio of gradient norms to parameter norms. Gradients whose norms exceed .. math:: weight_norm * clipping_threshold are scaled down by .. math:: (weight_norm / grad_norm) * clipping_threshold. Args: weights (torch.Tensor): Tensor of weights (paramet...
_get_clipped_gradient_coeff
python
mosaicml/composer
composer/algorithms/gradient_clipping/gradient_clipping.py
https://github.com/mosaicml/composer/blob/master/composer/algorithms/gradient_clipping/gradient_clipping.py
Apache-2.0
def _unitwise_norm(tensor: torch.Tensor): """Implements unitwise norm as described in Brock et al, 2021. For 0D scalars of shape [], we trivially normalize with dim=0 which essentially returns the absolute value of the scalar. For 1D *.bias weights of shape [out_features], we normalize across entire vector...
Implements unitwise norm as described in Brock et al, 2021. For 0D scalars of shape [], we trivially normalize with dim=0 which essentially returns the absolute value of the scalar. For 1D *.bias weights of shape [out_features], we normalize across entire vector -> dim=0. For 2D torch.nn.Linear weights of ...
_unitwise_norm
python
mosaicml/composer
composer/algorithms/gradient_clipping/gradient_clipping.py
https://github.com/mosaicml/composer/blob/master/composer/algorithms/gradient_clipping/gradient_clipping.py
Apache-2.0
def from_Dropout( iters_per_epoch: int, epoch: int, p: float, sigma: int, tau: int, layer: torch.nn.Module, module_index: int, ): """Defines a replacement policy from a `torch.nn.Dropout` to a 'GyroDropout`""" return GyroDropoutLayer(iters_per_epoch, epoch, p, sigma, tau)
Defines a replacement policy from a `torch.nn.Dropout` to a 'GyroDropout`
from_Dropout
python
mosaicml/composer
composer/algorithms/gyro_dropout/gyro_dropout.py
https://github.com/mosaicml/composer/blob/master/composer/algorithms/gyro_dropout/gyro_dropout.py
Apache-2.0
def apply_gyro_dropout( model: torch.nn.Module, iters_per_epoch: int, max_epoch: int, p: float, sigma: int, tau: int, ) -> None: """Replaces all instances of `torch.nn.Dropout` with a `GyroDropout`. By masking Dropout layer, this usually improves accuracy. """ # prepare the rep...
Replaces all instances of `torch.nn.Dropout` with a `GyroDropout`. By masking Dropout layer, this usually improves accuracy.
apply_gyro_dropout
python
mosaicml/composer
composer/algorithms/gyro_dropout/gyro_dropout.py
https://github.com/mosaicml/composer/blob/master/composer/algorithms/gyro_dropout/gyro_dropout.py
Apache-2.0
def smooth_labels(logits: torch.Tensor, target: torch.Tensor, smoothing: float = 0.1): """Shrink targets towards a uniform distribution as in `Szegedy et al <https://arxiv.org/abs/1512.00567>`_. The smoothed labels are computed as ``(1 - smoothing) * targets + smoothing * unif`` where ``unif`` is a vector ...
Shrink targets towards a uniform distribution as in `Szegedy et al <https://arxiv.org/abs/1512.00567>`_. The smoothed labels are computed as ``(1 - smoothing) * targets + smoothing * unif`` where ``unif`` is a vector with elements all equal to ``1 / num_classes``. Args: logits (torch.Tensor): pred...
smooth_labels
python
mosaicml/composer
composer/algorithms/label_smoothing/label_smoothing.py
https://github.com/mosaicml/composer/blob/master/composer/algorithms/label_smoothing/label_smoothing.py
Apache-2.0
def freeze_layers( model: torch.nn.Module, optimizers: Union[Optimizer, Sequence[Optimizer]], current_duration: float, freeze_start: float = 0.5, freeze_level: float = 1.0, ) -> tuple[int, float]: """Progressively freeze the layers of the network in-place during training, starting with the e...
Progressively freeze the layers of the network in-place during training, starting with the earlier layers. Example: .. testcode:: from composer.algorithms.layer_freezing import freeze_layers freeze_depth, feeze_level = freeze_layers( ...
freeze_layers
python
mosaicml/composer
composer/algorithms/layer_freezing/layer_freezing.py
https://github.com/mosaicml/composer/blob/master/composer/algorithms/layer_freezing/layer_freezing.py
Apache-2.0
def _freeze_schedule(current_duration: float, freeze_start: float, freeze_level: float) -> float: """Implements a linear schedule for freezing. The schedule is linear and begins with no freezing and linearly increases the fraction of layers frozen, reaching the fraction specified by ``freeze_level`` at the...
Implements a linear schedule for freezing. The schedule is linear and begins with no freezing and linearly increases the fraction of layers frozen, reaching the fraction specified by ``freeze_level`` at the end of training. The start of freezing is given as a fraction of the total training duration and is ...
_freeze_schedule
python
mosaicml/composer
composer/algorithms/layer_freezing/layer_freezing.py
https://github.com/mosaicml/composer/blob/master/composer/algorithms/layer_freezing/layer_freezing.py
Apache-2.0
def _get_layers(module: torch.nn.Module, flat_children: list[torch.nn.Module]): """Helper function to get all submodules. Does a depth first search to flatten out modules which contain parameters. Args: module (torch.nn.Module): Current module to search. flat_children (list[torch.nn.Mo...
Helper function to get all submodules. Does a depth first search to flatten out modules which contain parameters. Args: module (torch.nn.Module): Current module to search. flat_children (list[torch.nn.Module]): list containing modules.
_get_layers
python
mosaicml/composer
composer/algorithms/layer_freezing/layer_freezing.py
https://github.com/mosaicml/composer/blob/master/composer/algorithms/layer_freezing/layer_freezing.py
Apache-2.0
def _remove_param_from_optimizers(p: torch.nn.Parameter, optimizers: Union[Optimizer, Sequence[Optimizer]]): """Helper function to freeze the training of a parameter. To freeze a parameter, it must be removed from the optimizer, otherwise momentum and weight decay may still be applied. Args: p...
Helper function to freeze the training of a parameter. To freeze a parameter, it must be removed from the optimizer, otherwise momentum and weight decay may still be applied. Args: p (torch.nn.Parameter): The parameter being frozen. optimizers (torch.optim.Optimizer | Sequence[torch.optim....
_remove_param_from_optimizers
python
mosaicml/composer
composer/algorithms/layer_freezing/layer_freezing.py
https://github.com/mosaicml/composer/blob/master/composer/algorithms/layer_freezing/layer_freezing.py
Apache-2.0
def _to_LPGroupNorm(layer: torch.nn.Module, module_index: int) -> LPGroupNorm: """Defines a replacement policy from a `torch.nn.GroupNorm` to a `LPGroupNorm`""" if not isinstance(layer, torch.nn.GroupNorm): raise TypeError(f'Expected torch.nn.GroupNorm, got {type(layer)}') lp_groupnorm = LPGroupNorm...
Defines a replacement policy from a `torch.nn.GroupNorm` to a `LPGroupNorm`
_to_LPGroupNorm
python
mosaicml/composer
composer/algorithms/low_precision_groupnorm/low_precision_groupnorm.py
https://github.com/mosaicml/composer/blob/master/composer/algorithms/low_precision_groupnorm/low_precision_groupnorm.py
Apache-2.0
def _to_LPLayerNorm(layer: torch.nn.Module, module_index: int) -> LPLayerNorm: """Defines a replacement policy from a `torch.nn.LayerNorm` to a `LPLayerNorm`""" if not isinstance(layer, torch.nn.LayerNorm): raise TypeError(f'Expected torch.nn.LayerNorm, got {type(layer)}') lp_layernorm = LPLayerNorm...
Defines a replacement policy from a `torch.nn.LayerNorm` to a `LPLayerNorm`
_to_LPLayerNorm
python
mosaicml/composer
composer/algorithms/low_precision_layernorm/low_precision_layernorm.py
https://github.com/mosaicml/composer/blob/master/composer/algorithms/low_precision_layernorm/low_precision_layernorm.py
Apache-2.0
def mixup_batch( input: torch.Tensor, target: torch.Tensor, mixing: Optional[float] = None, alpha: float = 0.2, indices: Optional[torch.Tensor] = None, ) -> tuple[torch.Tensor, torch.Tensor, float]: """Create new samples using convex combinations of pairs of samples. This is done by taking ...
Create new samples using convex combinations of pairs of samples. This is done by taking a convex combination of ``input`` with a randomly permuted copy of ``input``. The permutation takes place along the sample axis (``dim=0``). The relative weight of the original ``input`` versus the permuted copy i...
mixup_batch
python
mosaicml/composer
composer/algorithms/mixup/mixup.py
https://github.com/mosaicml/composer/blob/master/composer/algorithms/mixup/mixup.py
Apache-2.0
def resize_batch( input: torch.Tensor, target: torch.Tensor, scale_factor: float, mode: str = 'resize', resize_targets: bool = False, ) -> tuple[torch.Tensor, torch.Tensor]: """Resize inputs and optionally outputs by cropping or interpolating. Args: input (torch.Tensor): input tenso...
Resize inputs and optionally outputs by cropping or interpolating. Args: input (torch.Tensor): input tensor of shape ``(N, C, H, W)``. Resizing will be done along dimensions H and W using the constant factor ``scale_factor``. target (torch.Tensor): output tensor of shape ``(...
resize_batch
python
mosaicml/composer
composer/algorithms/progressive_resizing/progressive_resizing.py
https://github.com/mosaicml/composer/blob/master/composer/algorithms/progressive_resizing/progressive_resizing.py
Apache-2.0
def _make_crop(tensor: torch.Tensor, scale_factor: float) -> T_ResizeTransform: """Makes a random crop transform for an input image.""" Hc = int(scale_factor * tensor.shape[2]) Wc = int(scale_factor * tensor.shape[3]) top = torch.randint(tensor.shape[2] - Hc, size=(1,)) left = torch.randint(tensor.s...
Makes a random crop transform for an input image.
_make_crop
python
mosaicml/composer
composer/algorithms/progressive_resizing/progressive_resizing.py
https://github.com/mosaicml/composer/blob/master/composer/algorithms/progressive_resizing/progressive_resizing.py
Apache-2.0
def _make_crop_pair( X: torch.Tensor, y: torch.Tensor, scale_factor: float, ) -> tuple[T_ResizeTransform, T_ResizeTransform]: """Makes a pair of random crops for an input image ``X`` and target tensor ``y``. The same region is selected from both. """ # New height and width for X HcX = i...
Makes a pair of random crops for an input image ``X`` and target tensor ``y``. The same region is selected from both.
_make_crop_pair
python
mosaicml/composer
composer/algorithms/progressive_resizing/progressive_resizing.py
https://github.com/mosaicml/composer/blob/master/composer/algorithms/progressive_resizing/progressive_resizing.py
Apache-2.0
def randaugment_image( img: ImgT, severity: int = 9, depth: int = 2, augmentation_set: list = augmentation_sets['all'], ) -> ImgT: """Randomly applies a sequence of image data augmentations to an image or batch of images. This technique is adapted from `Cubuk et al, 2019 <https://arxiv.org/abs...
Randomly applies a sequence of image data augmentations to an image or batch of images. This technique is adapted from `Cubuk et al, 2019 <https://arxiv.org/abs/1909.13719>`_). See :class:`.RandAugment` or the :doc:`Method Card </method_cards/randaugment>` for details. This function only acts on a single...
randaugment_image
python
mosaicml/composer
composer/algorithms/randaugment/randaugment.py
https://github.com/mosaicml/composer/blob/master/composer/algorithms/randaugment/randaugment.py
Apache-2.0
def should_selective_backprop( current_duration: float, batch_idx: int, start: float = 0.5, end: float = 0.9, interrupt: int = 2, ) -> bool: """Decides if selective backprop should be run based on time in training. Returns true if the ``current_duration`` is between ``start`` and ``end`...
Decides if selective backprop should be run based on time in training. Returns true if the ``current_duration`` is between ``start`` and ``end``. It is recommended that SB be applied during the later stages of a training run, once the model has already "learned" easy examples. To preserve convergence,...
should_selective_backprop
python
mosaicml/composer
composer/algorithms/selective_backprop/selective_backprop.py
https://github.com/mosaicml/composer/blob/master/composer/algorithms/selective_backprop/selective_backprop.py
Apache-2.0
def select_using_loss( input: torch.Tensor, target: torch.Tensor, model: Callable[[Union[torch.Tensor, Sequence[torch.Tensor]]], torch.Tensor], loss_fun: Callable, keep: float = 0.5, scale_factor: float = 1, ) -> tuple[torch.Tensor, torch.Tensor]: """Prunes minibatches as a subroutine of :cl...
Prunes minibatches as a subroutine of :class:`.SelectiveBackprop`. Computes the loss function on the provided training examples and runs minibatches according to the difficulty. The fraction of the minibatch that is kept for gradient computation is specified by the argument ``0 <= keep <= 1``. To speed up ...
select_using_loss
python
mosaicml/composer
composer/algorithms/selective_backprop/selective_backprop.py
https://github.com/mosaicml/composer/blob/master/composer/algorithms/selective_backprop/selective_backprop.py
Apache-2.0
def set_batch_sequence_length( batch: dict[str, torch.Tensor], curr_seq_len: int, truncate: bool = True, preserve_end_of_sequence: bool = False, ) -> Batch: """Set the sequence length of a batch. Changes the sequence length of all tensors in the provided dictionary to ``curr_seq_len`` by ei...
Set the sequence length of a batch. Changes the sequence length of all tensors in the provided dictionary to ``curr_seq_len`` by either truncating the tensors (``truncate=True``) or reshaping the tensors to create new examples from the extra tokens (``truncate=False``). .. note:: The sche...
set_batch_sequence_length
python
mosaicml/composer
composer/algorithms/seq_length_warmup/seq_length_warmup.py
https://github.com/mosaicml/composer/blob/master/composer/algorithms/seq_length_warmup/seq_length_warmup.py
Apache-2.0
def _activate_model(self, state: State, logger: Logger) -> None: """Does a forward and a backward pass on a dummy input. The purpose of activating the model is to prevent OOMs. This happens two ways. First, this prevents GPU memory from being reallocated when the sequence length increa...
Does a forward and a backward pass on a dummy input. The purpose of activating the model is to prevent OOMs. This happens two ways. First, this prevents GPU memory from being reallocated when the sequence length increases. Second, it detects if the batch*max_sequence_length size will ...
_activate_model
python
mosaicml/composer
composer/algorithms/seq_length_warmup/seq_length_warmup.py
https://github.com/mosaicml/composer/blob/master/composer/algorithms/seq_length_warmup/seq_length_warmup.py
Apache-2.0
def apply_stochastic_depth( model: torch.nn.Module, target_layer_name: str, stochastic_method: str = 'block', drop_rate: float = 0.2, drop_distribution: str = 'linear', ) -> None: """Applies Stochastic Depth (`Huang et al, 2016 <https://arxiv.org/abs/1603.09382>`_) to the specified model. T...
Applies Stochastic Depth (`Huang et al, 2016 <https://arxiv.org/abs/1603.09382>`_) to the specified model. The algorithm replaces the specified target layer with a stochastic version of the layer. The stochastic layer will randomly drop either samples or the layer itself depending on the stochastic method ...
apply_stochastic_depth
python
mosaicml/composer
composer/algorithms/stochastic_depth/stochastic_depth.py
https://github.com/mosaicml/composer/blob/master/composer/algorithms/stochastic_depth/stochastic_depth.py
Apache-2.0
def _validate_stochastic_hparams( target_layer_name: str, stochastic_method: str, drop_rate: float, drop_distribution: str, drop_warmup: str = '0dur', ): """Helper function to validate the Stochastic Depth hyperparameter values. """ if stochastic_method and (stochastic_method not in _VA...
Helper function to validate the Stochastic Depth hyperparameter values.
_validate_stochastic_hparams
python
mosaicml/composer
composer/algorithms/stochastic_depth/stochastic_depth.py
https://github.com/mosaicml/composer/blob/master/composer/algorithms/stochastic_depth/stochastic_depth.py
Apache-2.0
def _update_drop_rate( module: torch.nn.Module, target_block: type[torch.nn.Module], drop_rate: float, drop_distribution: str, module_count: int, module_id: int = 0, ): """Recursively updates a module's drop_rate attributes with a new value. """ for child in module.children(): ...
Recursively updates a module's drop_rate attributes with a new value.
_update_drop_rate
python
mosaicml/composer
composer/algorithms/stochastic_depth/stochastic_depth.py
https://github.com/mosaicml/composer/blob/master/composer/algorithms/stochastic_depth/stochastic_depth.py
Apache-2.0
def block_stochastic_forward(self, x): """ResNet Bottleneck forward function where the layers are randomly skipped with probability ``drop_rate`` during training. """ identity = x sample = (not self.training) or bool(torch.bernoulli(1 - self.drop_rate)) if sample: out = self.conv1...
ResNet Bottleneck forward function where the layers are randomly skipped with probability ``drop_rate`` during training.
block_stochastic_forward
python
mosaicml/composer
composer/algorithms/stochastic_depth/stochastic_layers.py
https://github.com/mosaicml/composer/blob/master/composer/algorithms/stochastic_depth/stochastic_layers.py
Apache-2.0
def _sample_drop(x: torch.Tensor, sample_drop_rate: float, is_training: bool): """Randomly drops samples from the input batch according to the `sample_drop_rate`. This is implemented by setting the samples to be dropped to zeros. """ keep_probability = (1 - sample_drop_rate) if not is_training: ...
Randomly drops samples from the input batch according to the `sample_drop_rate`. This is implemented by setting the samples to be dropped to zeros.
_sample_drop
python
mosaicml/composer
composer/algorithms/stochastic_depth/stochastic_layers.py
https://github.com/mosaicml/composer/blob/master/composer/algorithms/stochastic_depth/stochastic_layers.py
Apache-2.0
def sample_stochastic_forward(self, x): """ResNet Bottleneck forward function where samples are randomly dropped with probability ``drop_rate`` during training. """ identity = x out = self.conv1(x) out = self.bn1(out) out = self.relu(out) out = self.conv2(out) out = self.bn2(o...
ResNet Bottleneck forward function where samples are randomly dropped with probability ``drop_rate`` during training.
sample_stochastic_forward
python
mosaicml/composer
composer/algorithms/stochastic_depth/stochastic_layers.py
https://github.com/mosaicml/composer/blob/master/composer/algorithms/stochastic_depth/stochastic_layers.py
Apache-2.0
def make_resnet_bottleneck_stochastic( module: Bottleneck, module_index: int, module_count: int, drop_rate: float, drop_distribution: str, stochastic_method: str, ): """Model surgery policy that dictates how to convert a ResNet Bottleneck layer into a stochastic version. """ if drop...
Model surgery policy that dictates how to convert a ResNet Bottleneck layer into a stochastic version.
make_resnet_bottleneck_stochastic
python
mosaicml/composer
composer/algorithms/stochastic_depth/stochastic_layers.py
https://github.com/mosaicml/composer/blob/master/composer/algorithms/stochastic_depth/stochastic_layers.py
Apache-2.0
def _get_time(self, state: State): """helper function to retrieve either the epoch or the duration depending on the units""" unit = self.swa_start.unit if unit == TimeUnit.EPOCH: return state.timestamp.epoch elif unit == TimeUnit.DURATION: time_elapsed = state.ge...
helper function to retrieve either the epoch or the duration depending on the units
_get_time
python
mosaicml/composer
composer/algorithms/swa/swa.py
https://github.com/mosaicml/composer/blob/master/composer/algorithms/swa/swa.py
Apache-2.0
def _get_last_lr(self, schedulers: list[LRScheduler]): """ retrieves the last lr from current schedulers. """ if len(schedulers) == 0: return 1.0 if len(schedulers) != 1: raise RuntimeError(f'SWA supports only one scheduler, got {len(schedulers)}') scheduler = sch...
retrieves the last lr from current schedulers.
_get_last_lr
python
mosaicml/composer
composer/algorithms/swa/swa.py
https://github.com/mosaicml/composer/blob/master/composer/algorithms/swa/swa.py
Apache-2.0