language
stringclasses
1 value
repo
stringclasses
346 values
path
stringlengths
6
201
class_span
dict
source
stringlengths
21
2.38M
target
stringlengths
1
96
python
pytorch__pytorch
test/quantization/fx/test_numeric_suite_fx.py
{ "start": 84002, "end": 109615 }
class ____(FXNumericSuiteQuantizationTestCase): """ Tests the "n shadows" workflow. """ def _test_impl(self, m, example_input, qconfig_mappings): backend_config = get_native_backend_config() # test that input is valid _ = m(*example_input) msp = prepare_n_shadows_model( m, example_input, qconfig_mappings, backend_config) # print('msp', msp) for _ in range(2): msp(*example_input) msq = convert_n_shadows_model(msp) loggers_set_enabled(msq, True) msq(*example_input) results = extract_results_n_shadows_model(msq) print_comparisons_n_shadows_model(results) return msq @withQNNPACKBackend def test_linear_mod(self): class M(nn.Module): def __init__(self) -> None: super().__init__() self.fc1 = nn.Linear(2, 2) def forward(self, x): x = self.fc1(x) return x m = M().eval() example_input = (torch.randn(2, 2),) qconfig_mappings = \ QConfigMultiMapping().set_global([torch.ao.quantization.default_qconfig]) self._test_impl(m, example_input, qconfig_mappings) @withQNNPACKBackend def test_linear_relu_mod(self): class M(nn.Module): def __init__(self) -> None: super().__init__() self.fc1 = nn.Linear(2, 2) self.fc2 = nn.Linear(2, 2) self.relu = nn.ReLU() def forward(self, x): x = self.fc1(x) x = self.fc2(x) x = self.relu(x) return x m = M().eval() example_input = (torch.randn(2, 2),) qconfig_mappings = ( QConfigMultiMapping().set_global([ torch.ao.quantization.default_qconfig, torch.ao.quantization.default_dynamic_qconfig ]) ) self._test_impl(m, example_input, qconfig_mappings) @withQNNPACKBackend def test_conv_bn_relu_mod(self): class M(nn.Module): def __init__(self) -> None: super().__init__() self.conv = nn.Conv2d(1, 1, 1) self.bn = nn.BatchNorm2d(1) self.relu = nn.ReLU() def forward(self, x): x = self.conv(x) x = self.bn(x) x = self.relu(x) return x m = M().eval() example_input = (torch.randn(32, 1, 16, 16),) qconfig_mappings = QConfigMultiMapping() \ .set_global([ torch.ao.quantization.default_qconfig, torch.ao.quantization.default_per_channel_qconfig ]) self._test_impl(m, example_input, qconfig_mappings) @withQNNPACKBackend def test_functions(self): class M(nn.Module): def __init__(self) -> None: super().__init__() self.w1 = nn.Parameter(torch.randn(2, 2)) self.b1 = nn.Parameter(torch.zeros(2)) torch.nn.init.kaiming_uniform_(self.w1, a=math.sqrt(5)) def forward(self, x): x = F.sigmoid(x) x = F.linear(x, self.w1, self.b1) x = F.linear(x, self.w1[:], self.b1) x = F.relu(x) x = x + x x = torch.cat([x]) x = torch.cat((x,)) x = torch.cat(tensors=[x]) # TODO(future PR): enable layernorm # blocked on FX graph mode quant not inserting observer for # second arg, if the second arg is a module input # x = F.layer_norm(x, x.shape) # x = F.layer_norm(x, x.shape[1:]) # x = x.reshape(1, -1) * 2 # x = F.layer_norm(x.reshape(1, -1), x.shape[1:]) x = torch.matmul(x, x.reshape(2, 2)) x = torch.matmul(x.reshape(2, 2), x.reshape(2, 2)) # TODO(future PR): enable below after FX graph mode quantization handles # it, currently this is not supported # x = F.linear(input=x, weight=self.w1, bias=self.b1) return x m = M().eval() example_input = (torch.randn(2, 2),) qconfig_mappings = QConfigMultiMapping() \ .set_global([torch.ao.quantization.default_qconfig]) self._test_impl(m, example_input, qconfig_mappings) @withQNNPACKBackend def test_partial_qconfig_mapping(self): class M(nn.Module): def __init__(self) -> None: super().__init__() self.fc = nn.Linear(2, 2) self.w1 = nn.Parameter(torch.randn(2, 2)) self.b1 = nn.Parameter(torch.randn(2)) torch.nn.init.kaiming_uniform_(self.w1, a=math.sqrt(5)) def forward(self, x): x = self.fc(x) x = F.linear(x, self.w1, self.b1) x = F.relu(x) x = x + x return x m = M().eval() example_input = (torch.randn(2, 2),) qconfig = torch.ao.quantization.default_qconfig qconfig_mappings = QConfigMultiMapping() \ .set_object_type(F.linear, [qconfig]) \ .set_object_type(F.relu, [qconfig]) self._test_impl(m, example_input, qconfig_mappings) @withQNNPACKBackend def test_logger_enabled_and_save_activations_flags(self): m = nn.Sequential(nn.Linear(1, 1)).eval() example_input = (torch.randn(1, 1),) qconfig_mappings = QConfigMultiMapping() \ .set_global([torch.ao.quantization.default_qconfig]) backend_config = get_native_backend_config() msp = prepare_n_shadows_model( m, example_input, qconfig_mappings, backend_config) for _ in range(2): msp(*example_input) def _check_logger_count(model, exp_count_stats, exp_count_comparisons): for mod in model.modules(): if isinstance(mod, OutputLogger): self.assertTrue( len(mod.stats) == exp_count_stats, f'stats: expected {len(mod.stats)} to equal {exp_count_stats}') if isinstance(mod, OutputComparisonLogger): self.assertTrue( len(mod.comparisons) == exp_count_comparisons, f'comparisons: expected {len(mod.comparisons)} to equal {exp_count_comparisons}') # check behavior with save_activations enabled msq = convert_n_shadows_model(copy.deepcopy(msp)) loggers_set_enabled(msq, True) loggers_set_save_activations(msq, True) # after prepare calibration but before convert calibration, loggers # should not have anything saved _check_logger_count(msq, 0, 0) msq(*example_input) # loggers should save each item after calibration _check_logger_count(msq, 1, 1) # check behavior with save_activations disabled msq = convert_n_shadows_model(copy.deepcopy(msp)) loggers_set_enabled(msq, True) loggers_set_save_activations(msq, False) # after prepare calibration but before convert calibration, loggers # should not have anything saved _check_logger_count(msq, 0, 0) msq(*example_input) # stats should be empty, but comparisons should be there _check_logger_count(msq, 0, 1) @skipIfTorchDynamo("too slow") @skip_if_no_torchvision @withQNNPACKBackend def test_mobilenet_v2(self): import torchvision m = torchvision.models.quantization.mobilenet_v2( pretrained=False, quantize=False).eval() example_input = (torch.randn(1, 3, 224, 224),) qconfig_mappings = QConfigMultiMapping() \ .set_global([torch.ao.quantization.default_qconfig, torch.ao.quantization.default_dynamic_qconfig]) self._test_impl(m, example_input, qconfig_mappings) @withQNNPACKBackend def test_qconfig_multi_mapping_deduplication(self): # check that insertion deduplicates qconfigs qconfig_multi_mapping = QConfigMultiMapping().set_global( [torch.ao.quantization.default_qconfig, torch.ao.quantization.default_qconfig] ) self.assertEqual(len(qconfig_multi_mapping.qconfig_mappings_list), 1) @withQNNPACKBackend def test_qconfig_multi_mapping_insert_padding(self): # test that inserting a higher priority qconfig style with fewer elements than a lower priority qconfig will # result in adding None to the extra QConfigMappings at that same style+key qconfig_multi_mapping = ( QConfigMultiMapping() .set_global( [ torch.ao.quantization.default_qconfig, torch.ao.quantization.default_dynamic_qconfig, ] ) .set_object_type(torch.nn.Linear, [torch.ao.quantization.default_qconfig]) .set_module_name_regex("fc", [torch.ao.quantization.default_qconfig]) .set_module_name("fc2", [torch.ao.quantization.default_qconfig]) .set_module_name_object_type_order( "", nn.Linear, 0, [torch.ao.quantization.default_qconfig] ) ) self.assertEqual( qconfig_multi_mapping.qconfig_mappings_list[1].object_type_qconfigs[ torch.nn.Linear ], None, ) self.assertEqual( qconfig_multi_mapping.qconfig_mappings_list[1].module_name_regex_qconfigs[ "fc" ], None, ) self.assertEqual( qconfig_multi_mapping.qconfig_mappings_list[1].module_name_qconfigs["fc2"], None, ) self.assertEqual( qconfig_multi_mapping.qconfig_mappings_list[ 1 ].module_name_object_type_order_qconfigs[("", nn.Linear, 0)], None, ) @withQNNPACKBackend def test_qconfig_multi_mapping_retroactive_padding(self): # test that inserting a lower priority qconfig style with more elements thhan lower priority qconfig styles # will result in the new QConfigMapping having None at all previously existing styles+keys qconfig_multi_mapping = ( QConfigMultiMapping() .set_object_type(torch.nn.Linear, [torch.ao.quantization.default_qconfig]) .set_module_name_regex("fc", [torch.ao.quantization.default_qconfig]) .set_module_name("fc2", [torch.ao.quantization.default_qconfig]) .set_module_name_object_type_order( "", nn.Linear, 0, [torch.ao.quantization.default_qconfig] ) .set_global( [ torch.ao.quantization.default_qconfig, torch.ao.quantization.default_dynamic_qconfig, ] ) ) self.assertEqual( qconfig_multi_mapping.qconfig_mappings_list[1].object_type_qconfigs[ torch.nn.Linear ], None, ) self.assertEqual( qconfig_multi_mapping.qconfig_mappings_list[1].module_name_regex_qconfigs[ "fc" ], None, ) self.assertEqual( qconfig_multi_mapping.qconfig_mappings_list[1].module_name_qconfigs["fc2"], None, ) self.assertEqual( qconfig_multi_mapping.qconfig_mappings_list[ 1 ].module_name_object_type_order_qconfigs[("", nn.Linear, 0)], None, ) @withQNNPACKBackend def test_qconfig_multi_mapping_end_to_end(self): # test that the prepare/convert_n_shadows_model works as expected # with qconfig_multi_mapping and avoids unwanted matches m = TwoLayerLinearModel().eval() example_input = m.get_example_inputs() qconfig_multi_mapping = ( QConfigMultiMapping() .set_global( [ torch.ao.quantization.default_qconfig, torch.ao.quantization.default_dynamic_qconfig, ] ) .set_module_name("fc2", [None, torch.ao.quantization.default_qconfig]) ) self.assertEqual( qconfig_multi_mapping.qconfig_mappings_list[1].module_name_qconfigs["fc2"], None, ) msq = self._test_impl(m, example_input, qconfig_multi_mapping) self.checkQuantizedLinear(msq.shadow_wrapper_0_1.mod_0) self.checkDynamicQuantizedLinear(msq.shadow_wrapper_0_2.mod_0, torch.qint8) self.checkQuantizedLinear(msq.shadow_wrapper_1_1.mod_0) self.assertRaisesRegex(AttributeError, ".*", lambda: msq.shadow_wrapper_1_2) @withQNNPACKBackend def test_qconfig_multi_mapping_from_list(self): # test QConfigMultiMapping.from_list_qconfig_mapping works as expected m = TwoLayerLinearModel().eval() example_input = m.get_example_inputs() qconfig_mappings_list = [ QConfigMapping().set_global(torch.ao.quantization.default_qconfig), QConfigMapping() .set_global(torch.ao.quantization.default_dynamic_qconfig) .set_module_name("fc2", torch.ao.quantization.default_qconfig), ] qconfig_multi_mapping = QConfigMultiMapping().from_list_qconfig_mapping( qconfig_mappings_list ) self.assertEqual( qconfig_multi_mapping.qconfig_mappings_list[1].module_name_qconfigs["fc2"], None, ) msq = self._test_impl(m, example_input, qconfig_multi_mapping) self.checkQuantizedLinear(msq.shadow_wrapper_0_1.mod_0) self.checkDynamicQuantizedLinear(msq.shadow_wrapper_0_2.mod_0, torch.qint8) self.checkQuantizedLinear(msq.shadow_wrapper_1_1.mod_0) self.assertRaisesRegex(AttributeError, ".*", lambda: msq.shadow_wrapper_1_2) @withQNNPACKBackend def test_qconfig_multi_mapping_ordering(self): # test that the module ordering ignores None m = TwoLayerLinearModel().eval() example_input = m.get_example_inputs() qconfig_multi_mapping = ( QConfigMultiMapping() .set_global( [ torch.ao.quantization.default_qconfig, torch.ao.quantization.default_dynamic_qconfig, ] ) .set_module_name( "fc2", [ None, torch.ao.quantization.default_dynamic_qconfig, torch.ao.quantization.default_qat_qconfig_v2, ], ) ) self.assertEqual(len(qconfig_multi_mapping.qconfig_mappings_list), 2) msq = self._test_impl(m, example_input, qconfig_multi_mapping) self.checkQuantizedLinear(msq.shadow_wrapper_0_1.mod_0) self.checkDynamicQuantizedLinear(msq.shadow_wrapper_0_2.mod_0, torch.qint8) self.checkDynamicQuantizedLinear(msq.shadow_wrapper_1_1.mod_0, torch.qint8) self.checkQuantizedLinear(msq.shadow_wrapper_1_2.mod_0) @withQNNPACKBackend def test_qconfig_multi_mapping_repr(self): qconfig_multi_mapping = ( QConfigMultiMapping() .set_global( [ torch.ao.quantization.default_qconfig, torch.ao.quantization.default_dynamic_qconfig, ] ) .set_module_name( "fc2", [ None, torch.ao.quantization.default_dynamic_qconfig, torch.ao.quantization.default_qat_qconfig_v2, ], ) ) self.assertTrue(isinstance(qconfig_multi_mapping.__repr__(), str)) @withQNNPACKBackend def test_custom_functions_and_tracer(self): class M(nn.Module): def __init__(self) -> None: super().__init__() self.fc1 = nn.Linear(2, 2) self.fc2 = nn.Linear(2, 2) def forward(self, x): x = self.fc1(x) x = self.fc2(x) return x m = M().eval() example_inputs = (torch.randn(2, 2),) qconfig_mappings = QConfigMultiMapping().set_global( [torch.ao.quantization.default_qat_qconfig] ) custom_tracer = torch.ao.quantization.quantize_fx.QuantizationTracer( ["fc2"], [] ) custom_prepare_fn = torch.ao.quantization.quantize_fx.prepare_qat_fx def custom_convert_fn(module, to_print): print(to_print) mod = torch.ao.quantization.quantize_fx.convert_fx(module) return mod backend_config = get_native_backend_config() # test that input is valid _ = m(*example_inputs) kwargs = {"to_print": "working"} msp = prepare_n_shadows_model( m, example_inputs, qconfig_mappings, backend_config, custom_prepare_fn=custom_prepare_fn, custom_prepare_kwargs=None, custom_tracer=custom_tracer, ) for _ in range(2): msp(*example_inputs) msq = convert_n_shadows_model( msp, custom_convert_fn=custom_convert_fn, custom_convert_kwargs=kwargs ) print(msq) loggers_set_enabled(msq, True) msq(*example_inputs) results = extract_results_n_shadows_model(msq) print_comparisons_n_shadows_model(results) def _test_extract_weights_impl(self, m, example_input, qconfig_mapping): backend_config = get_native_backend_config() results = _n_shadows_compare_weights( m, example_input, qconfig_mapping, backend_config) print_comparisons_n_shadows_model(results) @withQNNPACKBackend def test_extract_weights_linear(self): class M(nn.Module): def __init__(self) -> None: super().__init__() self.w1 = nn.Parameter(torch.randn(2, 2)) self.b1 = nn.Parameter(torch.randn(2)) torch.nn.init.kaiming_uniform_(self.w1, a=math.sqrt(5)) self.w2 = nn.Parameter(torch.randn(2, 2)) self.b2 = nn.Parameter(torch.randn(2)) torch.nn.init.kaiming_uniform_(self.w2, a=math.sqrt(5)) self.w3 = nn.Parameter(torch.randn(2, 2)) self.b3 = nn.Parameter(torch.randn(2)) torch.nn.init.kaiming_uniform_(self.w3, a=math.sqrt(5)) self.w4 = nn.Parameter(torch.randn(2, 2)) self.b4 = nn.Parameter(torch.randn(2)) torch.nn.init.kaiming_uniform_(self.w4, a=math.sqrt(5)) def forward(self, x): x = F.linear(x, self.w1, self.b1) x = F.linear(x, self.w2, self.b2) x = F.relu(x) x = F.linear(x, self.w3, self.b3) x = F.linear(x, self.w4, self.b4) return x per_tensor_qconfig = torch.ao.quantization.default_qconfig m = M().eval() example_input = (torch.randn(2, 2),) qconfig_mapping = get_default_qconfig_mapping() # test unquantized qconfig_mapping.set_module_name_object_type_order( '', F.linear, 2, None) # test per-tensor qconfig_mapping.set_module_name_object_type_order( '', F.linear, 3, per_tensor_qconfig) self._test_extract_weights_impl(m, example_input, qconfig_mapping) def _test_add_loggers_impl(self, m, example_input, qconfig_mapping): backend_config = get_native_backend_config() m_copy = copy.deepcopy(m) # test that input is valid _ = m(*example_input) msp = _prepare_n_shadows_add_loggers_model( m, example_input, qconfig_mapping, backend_config) # print('msp', msp) msp(*example_input) msq = convert_n_shadows_model(msp) # print('msq', msq) loggers_set_enabled(msq, True) output_fp32 = msq(*example_input) results = extract_results_n_shadows_model(msq) # print(results) # print_comparisons_n_shadows_model(results) # get the last quantized output from results inner_results = results['model']['node_output'] last_subgraph = list(inner_results.keys())[-1] output_shadow = inner_results[last_subgraph][0]['values'][-1] # verify that both fp32 and quantized output matches reference output_fp32_ref = m_copy(*example_input) mp_ref = prepare_fx(m_copy, qconfig_mapping, example_input) for _ in range(2): mp_ref(*example_input) mq_ref = convert_fx(mp_ref) output_shadow_ref = mq_ref(*example_input) self.assertTrue( torch.allclose(output_fp32, output_fp32_ref), f"fp32 comparison: {output_fp32} not close to {output_fp32_ref}") # print('shadow', output_shadow.shape, output_shadow) # print('shadow_ref', output_shadow_ref.shape, output_shadow_ref) self.assertTrue( torch.allclose(output_shadow, output_shadow_ref), f"shadow comparison: {output_shadow} not close to {output_shadow_ref}") return msq @withQNNPACKBackend def test_add_loggers_linear_mod_quant_quant(self): m = nn.Sequential(nn.Linear(2, 2), nn.Linear(2, 2)) example_input = (torch.randn(2, 2),) qconfig_mapping = get_default_qconfig_mapping() self._test_add_loggers_impl(m, example_input, qconfig_mapping) @withQNNPACKBackend def test_add_loggers_linear_mod_fp32_quant(self): m = nn.Sequential(nn.Linear(2, 2), nn.Linear(2, 2)) example_input = (torch.randn(2, 2),) qconfig_mapping = get_default_qconfig_mapping() qconfig_mapping.set_module_name('0', None) self._test_add_loggers_impl(m, example_input, qconfig_mapping) @withQNNPACKBackend def test_add_loggers_linear_mod_quant_fp32(self): m = nn.Sequential(nn.Linear(2, 2), nn.Linear(2, 2)) example_input = (torch.randn(2, 2),) qconfig_mapping = get_default_qconfig_mapping() qconfig_mapping.set_module_name('1', None) self._test_add_loggers_impl(m, example_input, qconfig_mapping) @withQNNPACKBackend def test_add_loggers_linear_mod_fp32_fp32(self): m = nn.Sequential(nn.Linear(2, 2), nn.Linear(2, 2)) example_input = (torch.randn(2, 2),) qconfig_mapping = get_default_qconfig_mapping() qconfig_mapping.set_module_name('0', None) qconfig_mapping.set_module_name('1', None) self._test_add_loggers_impl(m, example_input, qconfig_mapping) @withQNNPACKBackend def test_add_loggers_conv_bn_relu_fusion_quant(self): m = nn.Sequential(nn.Conv2d(1, 1, 1), nn.BatchNorm2d(1), nn.ReLU()) m.eval() example_input = (torch.randn(16, 1, 4, 4),) qconfig_mapping = get_default_qconfig_mapping() self._test_add_loggers_impl(m, example_input, qconfig_mapping) @withQNNPACKBackend def test_add_loggers_conv_bn_relu_fusion_fp32(self): m = nn.Sequential(nn.Conv2d(1, 1, 1), nn.BatchNorm2d(1), nn.ReLU()) m.eval() example_input = (torch.randn(16, 1, 4, 4),) qconfig_mapping = get_default_qconfig_mapping() qconfig_mapping.set_module_name('0', None) qconfig_mapping.set_module_name('1', None) qconfig_mapping.set_module_name('2', None) self._test_add_loggers_impl(m, example_input, qconfig_mapping) @withQNNPACKBackend def test_add_loggers_functions(self): class M(nn.Module): def __init__(self) -> None: super().__init__() self.w1 = nn.Parameter(torch.randn(2, 2)) self.b1 = nn.Parameter(torch.randn(2)) torch.nn.init.kaiming_uniform_(self.w1, a=math.sqrt(5)) def forward(self, x): x = F.linear(x, self.w1, self.b1) x = F.relu(x) x = x + x x = x + 1 # TODO(future PR): support first arg being a scalar # x = 1 + x x = torch.cat([x, x]) x = torch.cat([x, x]) x = torch.cat(tensors=[x, x]) # function not matchable by quantization x = torch.nn.functional.rrelu(x) x = F.linear(x, self.w1, self.b1) return x m = M().eval() example_input = (torch.randn(16, 2),) for qconfig_mapping in ( get_default_qconfig_mapping(), QConfigMapping(), ): self._test_add_loggers_impl(m, example_input, qconfig_mapping) @skipIfTorchDynamo("too slow") @skip_if_no_torchvision @withQNNPACKBackend def test_add_loggers_mobilenet_v2(self): import torchvision m = torchvision.models.quantization.mobilenet_v2( pretrained=False, quantize=False).eval() example_input = (torch.randn(8, 3, 224, 224),) qconfig_mapping = get_default_qconfig_mapping() self._test_add_loggers_impl(m, example_input, qconfig_mapping)
TestFXNumericSuiteNShadows
python
django__django
tests/migrations/test_migrations/0002_second.py
{ "start": 43, "end": 663 }
class ____(migrations.Migration): dependencies = [ ("migrations", "0001_initial"), ] operations = [ migrations.DeleteModel("Tribble"), migrations.RemoveField("Author", "silly_field"), migrations.AddField("Author", "rating", models.IntegerField(default=0)), migrations.CreateModel( "Book", [ ("id", models.AutoField(primary_key=True)), ( "author", models.ForeignKey("migrations.Author", models.SET_NULL, null=True), ), ], ), ]
Migration
python
tensorflow__tensorflow
tensorflow/python/distribute/distribute_lib.py
{ "start": 32506, "end": 35084 }
class ____(object): """A class wrapping information needed by an input function. This is a context class that is passed to the user's input function and contains information about the compute replicas and input pipelines. The number of compute replicas (in sync training) helps compute the local batch size from the desired global batch size for each replica. The input pipeline information can be used to return a different subset of the input in each replica (for e.g. shard the input pipeline, use a different input source etc). """ __slots__ = [ "_num_input_pipelines", "_input_pipeline_id", "_num_replicas_in_sync" ] def __init__(self, num_input_pipelines=1, input_pipeline_id=0, num_replicas_in_sync=1): """Initializes an InputContext object. Args: num_input_pipelines: the number of input pipelines in a cluster. input_pipeline_id: the current input pipeline id, should be an int in [0,`num_input_pipelines`). num_replicas_in_sync: the number of replicas that are in sync. """ self._num_input_pipelines = num_input_pipelines self._input_pipeline_id = input_pipeline_id self._num_replicas_in_sync = num_replicas_in_sync @property def num_replicas_in_sync(self): """Returns the number of compute replicas in sync.""" return self._num_replicas_in_sync @property def input_pipeline_id(self): """Returns the input pipeline ID.""" return self._input_pipeline_id @property def num_input_pipelines(self): """Returns the number of input pipelines.""" return self._num_input_pipelines def get_per_replica_batch_size(self, global_batch_size): """Returns the per-replica batch size. Args: global_batch_size: the global batch size which should be divisible by `num_replicas_in_sync`. Returns: the per-replica batch size. Raises: ValueError: if `global_batch_size` not divisible by `num_replicas_in_sync`. """ if global_batch_size % self._num_replicas_in_sync != 0: raise ValueError("The `global_batch_size` %r is not divisible by " "`num_replicas_in_sync` %r " % (global_batch_size, self._num_replicas_in_sync)) return global_batch_size // self._num_replicas_in_sync def __str__(self): return "tf.distribute.InputContext(input pipeline id {}, total: {})".format( self.input_pipeline_id, self.num_input_pipelines) @tf_export("distribute.experimental.ValueContext", v1=[])
InputContext
python
openai__openai-python
src/openai/resources/files.py
{ "start": 27879, "end": 28759 }
class ____: def __init__(self, files: AsyncFiles) -> None: self._files = files self.create = _legacy_response.async_to_raw_response_wrapper( files.create, ) self.retrieve = _legacy_response.async_to_raw_response_wrapper( files.retrieve, ) self.list = _legacy_response.async_to_raw_response_wrapper( files.list, ) self.delete = _legacy_response.async_to_raw_response_wrapper( files.delete, ) self.content = _legacy_response.async_to_raw_response_wrapper( files.content, ) self.retrieve_content = ( # pyright: ignore[reportDeprecated] _legacy_response.async_to_raw_response_wrapper( files.retrieve_content, # pyright: ignore[reportDeprecated], ) )
AsyncFilesWithRawResponse
python
spack__spack
var/spack/test_repos/spack_repo/builder_test/packages/builder_and_mixins/package.py
{ "start": 601, "end": 814 }
class ____(metaclass=spack.phase_callbacks.PhaseCallbacksMeta): @run_before("install") def before_install(self): pass @run_after("install") def after_install(self): pass
BuilderMixin
python
bokeh__bokeh
src/bokeh/util/compiler.py
{ "start": 5815, "end": 18931 }
class ____: ''' Represent a custom (user-defined) Bokeh model. ''' def __init__(self, cls: type[HasProps]) -> None: self.cls = cls @property def name(self) -> str: return self.cls.__name__ @property def full_name(self) -> str: name = self.cls.__module__ + "." + self.name return name.replace("__main__.", "") @property def file(self) -> str | None: module = sys.modules[self.cls.__module__] if hasattr(module, "__file__") and (file := module.__file__) is not None: return abspath(file) else: return None @property def path(self) -> str: path = getattr(self.cls, "__base_path__", None) if path is not None: return path elif self.file is not None: return dirname(self.file) else: return os.getcwd() @property def implementation(self) -> Implementation: impl = getattr(self.cls, "__implementation__") if isinstance(impl, str): if "\n" not in impl and impl.endswith(exts): impl = FromFile(impl if isabs(impl) else join(self.path, impl)) else: impl = TypeScript(impl) if isinstance(impl, Inline) and impl.file is None: file = f"{self.file + ':' if self.file else ''}{self.name}.ts" impl = impl.__class__(impl.code, file) return impl @property def dependencies(self) -> dict[str, str]: return getattr(self.cls, "__dependencies__", {}) @property def module(self) -> str: return f"custom/{snakify(self.full_name)}" def get_cache_hook() -> Callable[[CustomModel, Implementation], AttrDict | None]: '''Returns the current cache hook used to look up the compiled code given the CustomModel and Implementation''' return _CACHING_IMPLEMENTATION def set_cache_hook(hook: Callable[[CustomModel, Implementation], AttrDict | None]) -> None: '''Sets a compiled model cache hook used to look up the compiled code given the CustomModel and Implementation''' global _CACHING_IMPLEMENTATION _CACHING_IMPLEMENTATION = hook def calc_cache_key(custom_models: dict[str, CustomModel]) -> str: ''' Generate a key to cache a custom extension implementation with. There is no metadata other than the Model classes, so this is the only base to generate a cache key. We build the model keys from the list of ``model.full_name``. This is not ideal but possibly a better solution can be found found later. ''' model_names = {model.full_name for model in custom_models.values()} encoded_names = ",".join(sorted(model_names)).encode('utf-8') return hashlib.sha256(encoded_names).hexdigest() _bundle_cache: dict[str, str] = {} def bundle_models(models: Sequence[type[HasProps]] | None) -> str | None: """Create a bundle of selected `models`. """ custom_models = _get_custom_models(models) if custom_models is None: return None key = calc_cache_key(custom_models) bundle = _bundle_cache.get(key, None) if bundle is None: try: _bundle_cache[key] = bundle = _bundle_models(custom_models) except CompilationError as error: print("Compilation failed:", file=sys.stderr) print(str(error), file=sys.stderr) sys.exit(1) return bundle def bundle_all_models() -> str | None: """Create a bundle of all models. """ return bundle_models(None) #----------------------------------------------------------------------------- # Dev API #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Private API #----------------------------------------------------------------------------- _plugin_umd = \ """\ (function(root, factory) { factory(root["Bokeh"]); })(this, function(Bokeh) { let define; return %(content)s; }); """ # XXX: this is (almost) the same as bokehjs/src/js/plugin-prelude.js _plugin_prelude = \ """\ (function outer(modules, entry) { if (Bokeh != null) { return Bokeh.register_plugin(modules, entry); } else { throw new Error("Cannot find Bokeh. You have to load it prior to loading plugins."); } }) """ _plugin_template = \ """\ %(prelude)s\ ({ "custom/main": function(require, module, exports) { const models = { %(exports)s }; require("base").register_models(models); module.exports = models; }, %(modules)s }, "custom/main"); """ _style_template = \ """\ (function() { const head = document.getElementsByTagName('head')[0]; const style = document.createElement('style'); style.type = 'text/css'; const css = %(css)s; if (style.styleSheet) { style.styleSheet.cssText = css; } else { style.appendChild(document.createTextNode(css)); } head.appendChild(style); }()); """ _export_template = \ """"%(name)s": require("%(module)s").%(name)s""" _module_template = \ """"%(module)s": function(require, module, exports) {\n%(source)s\n}""" def _detect_nodejs() -> Path: nodejs_path = settings.nodejs_path() nodejs_paths = [nodejs_path] if nodejs_path is not None else ["nodejs", "node"] for nodejs_path in nodejs_paths: try: proc = Popen([nodejs_path, "--version"], stdout=PIPE, stderr=PIPE) (stdout, _) = proc.communicate() except OSError: continue if proc.returncode != 0: continue match = re.match(r"^v(\d+)\.(\d+)\.(\d+).*$", stdout.decode("utf-8")) if match is not None: version = tuple(int(v) for v in match.groups()) if version >= nodejs_min_version: return Path(nodejs_path) # if we've reached here, no valid version was found version_repr = ".".join(str(x) for x in nodejs_min_version) raise RuntimeError(f'node.js v{version_repr} or higher is needed to allow compilation of custom models ' + '("conda install nodejs" or follow https://nodejs.org/en/download/)') _nodejs: Path | None = None _npmjs: Path | None = None def _nodejs_path() -> Path: global _nodejs if _nodejs is None: _nodejs = _detect_nodejs() return _nodejs def _npmjs_path() -> Path: global _npmjs if _npmjs is None: executable = "npm.cmd" if sys.platform == "win32" else "npm" _npmjs = _nodejs_path().parent / executable return _npmjs def _crlf_cr_2_lf(s: str) -> str: return re.sub(r"\\r\\n|\\r|\\n", r"\\n", s) def _run(app: Path, argv: list[str], input: dict[str, Any] | None = None) -> str: proc = Popen([app, *argv], stdout=PIPE, stderr=PIPE, stdin=PIPE) (stdout, errout) = proc.communicate(input=None if input is None else json.dumps(input).encode()) if proc.returncode != 0: raise RuntimeError(errout.decode('utf-8')) else: return _crlf_cr_2_lf(stdout.decode('utf-8')) def _run_nodejs(argv: list[str], input: dict[str, Any] | None = None) -> str: return _run(_nodejs_path(), argv, input) def _run_npmjs(argv: list[str], input: dict[str, Any] | None = None) -> str: return _run(_npmjs_path(), argv, input) def _version(run_app: Callable[[list[str], dict[str, Any] | None], str]) -> str | None: try: version = run_app(["--version"], None) # explicit None to make mypy happy except RuntimeError: return None else: return version.strip() def _model_cache_no_op(model: CustomModel, implementation: Implementation) -> AttrDict | None: """Return cached compiled implementation""" return None _CACHING_IMPLEMENTATION = _model_cache_no_op def _get_custom_models(models: Sequence[type[HasProps]] | None) -> dict[str, CustomModel] | None: """Returns CustomModels for models with a custom `__implementation__`""" custom_models: dict[str, CustomModel] = dict() for cls in models or HasProps.model_class_reverse_map.values(): impl = getattr(cls, "__implementation__", None) if impl is not None: model = CustomModel(cls) custom_models[model.full_name] = model return custom_models if custom_models else None def _compile_models(custom_models: dict[str, CustomModel]) -> dict[str, AttrDict]: """Returns the compiled implementation of supplied `models`. """ ordered_models = sorted(custom_models.values(), key=lambda model: model.full_name) custom_impls = {} dependencies: list[tuple[str, str]] = [] for model in ordered_models: dependencies.extend(list(model.dependencies.items())) if dependencies: dependencies = sorted(dependencies, key=lambda name_version: name_version[0]) _run_npmjs(["install", "--no-progress"] + [ name + "@" + version for (name, version) in dependencies ]) for model in ordered_models: impl = model.implementation compiled = _CACHING_IMPLEMENTATION(model, impl) if compiled is None: compiled = nodejs_compile(impl.code, lang=impl.lang, file=impl.file) if "error" in compiled: raise CompilationError(compiled.error) custom_impls[model.full_name] = compiled return custom_impls def _bundle_models(custom_models: dict[str, CustomModel]) -> str: """ Create a JavaScript bundle with selected `models`. """ exports = [] modules = [] lib_dir = Path(bokehjs_dir) / "js" / "lib" known_modules: set[str] = set() for path in lib_dir.rglob("*.d.ts"): s = str(path.relative_to(lib_dir)) s = s.removesuffix(".d.ts") s = s.replace(os.path.sep, "/") known_modules.add(s) custom_impls = _compile_models(custom_models) extra_modules = {} def resolve_modules(to_resolve: set[str], root: str) -> dict[str, str]: resolved = {} for module in to_resolve: if module.startswith(("./", "../")): def mkpath(module: str, ext: str = "") -> str: return abspath(join(root, *module.split("/")) + ext) if module.endswith(exts): path = mkpath(module) if not exists(path): raise RuntimeError(f"no such module: {module}") else: for ext in exts: path = mkpath(module, ext) if exists(path): break else: raise RuntimeError(f"no such module: {module}") impl = FromFile(path) compiled = nodejs_compile(impl.code, lang=impl.lang, file=impl.file) if impl.lang == "less": code = _style_template % dict(css=json.dumps(compiled.code)) deps = [] else: code = compiled.code deps = compiled.deps sig = hashlib.sha256(code.encode('utf-8')).hexdigest() resolved[module] = sig deps_map = resolve_deps(deps, dirname(path)) if sig not in extra_modules: extra_modules[sig] = True modules.append((sig, code, deps_map)) else: index = module + ("" if module.endswith("/") else "/") + "index" if index not in known_modules: raise RuntimeError(f"no such module: {module}") return resolved def resolve_deps(deps : list[str], root: str) -> dict[str, str]: custom_modules = {model.module for model in custom_models.values()} missing = set(deps) - known_modules - custom_modules return resolve_modules(missing, root) for model in custom_models.values(): compiled = custom_impls[model.full_name] deps_map = resolve_deps(compiled.deps, model.path) exports.append((model.name, model.module)) modules.append((model.module, compiled.code, deps_map)) # sort everything by module name exports = sorted(exports, key=lambda spec: spec[1]) modules = sorted(modules, key=lambda spec: spec[0]) bare_modules = [] for i, (module, code, deps) in enumerate(modules): for name, ref in deps.items(): code = code.replace(f"""require("{name}")""", f"""require("{ref}")""") code = code.replace(f"""require('{name}')""", f"""require('{ref}')""") bare_modules.append((module, code)) sep = ",\n" rendered_exports = sep.join(_export_template % dict(name=name, module=module) for (name, module) in exports) rendered_modules = sep.join(_module_template % dict(module=module, source=code) for (module, code) in bare_modules) content = _plugin_template % dict(prelude=_plugin_prelude, exports=rendered_exports, modules=rendered_modules) return _plugin_umd % dict(content=content) #----------------------------------------------------------------------------- # Code #-----------------------------------------------------------------------------
CustomModel
python
pytoolz__toolz
toolz/tests/test_dicttoolz.py
{ "start": 439, "end": 6046 }
class ____: """Test typical usage: dict inputs, no factory keyword. Class attributes: D: callable that inputs a dict and creates or returns a MutableMapping kw: kwargs dict to specify "factory" keyword (if applicable) """ D = dict kw = {} def test_merge(self): D, kw = self.D, self.kw assert merge(D({1: 1, 2: 2}), D({3: 4}), **kw) == D({1: 1, 2: 2, 3: 4}) def test_merge_iterable_arg(self): D, kw = self.D, self.kw assert merge([D({1: 1, 2: 2}), D({3: 4})], **kw) == D({1: 1, 2: 2, 3: 4}) def test_merge_with(self): D, kw = self.D, self.kw dicts = D({1: 1, 2: 2}), D({1: 10, 2: 20}) assert merge_with(sum, *dicts, **kw) == D({1: 11, 2: 22}) assert merge_with(tuple, *dicts, **kw) == D({1: (1, 10), 2: (2, 20)}) dicts = D({1: 1, 2: 2, 3: 3}), D({1: 10, 2: 20}) assert merge_with(sum, *dicts, **kw) == D({1: 11, 2: 22, 3: 3}) assert merge_with(tuple, *dicts, **kw) == D({1: (1, 10), 2: (2, 20), 3: (3,)}) assert not merge_with(sum) def test_merge_with_iterable_arg(self): D, kw = self.D, self.kw dicts = D({1: 1, 2: 2}), D({1: 10, 2: 20}) assert merge_with(sum, *dicts, **kw) == D({1: 11, 2: 22}) assert merge_with(sum, dicts, **kw) == D({1: 11, 2: 22}) assert merge_with(sum, iter(dicts), **kw) == D({1: 11, 2: 22}) def test_valmap(self): D, kw = self.D, self.kw assert valmap(inc, D({1: 1, 2: 2}), **kw) == D({1: 2, 2: 3}) def test_keymap(self): D, kw = self.D, self.kw assert keymap(inc, D({1: 1, 2: 2}), **kw) == D({2: 1, 3: 2}) def test_itemmap(self): D, kw = self.D, self.kw assert itemmap(reversed, D({1: 2, 2: 4}), **kw) == D({2: 1, 4: 2}) def test_valfilter(self): D, kw = self.D, self.kw assert valfilter(iseven, D({1: 2, 2: 3}), **kw) == D({1: 2}) def test_keyfilter(self): D, kw = self.D, self.kw assert keyfilter(iseven, D({1: 2, 2: 3}), **kw) == D({2: 3}) def test_itemfilter(self): D, kw = self.D, self.kw assert itemfilter(lambda item: iseven(item[0]), D({1: 2, 2: 3}), **kw) == D({2: 3}) assert itemfilter(lambda item: iseven(item[1]), D({1: 2, 2: 3}), **kw) == D({1: 2}) def test_assoc(self): D, kw = self.D, self.kw assert assoc(D({}), "a", 1, **kw) == D({"a": 1}) assert assoc(D({"a": 1}), "a", 3, **kw) == D({"a": 3}) assert assoc(D({"a": 1}), "b", 3, **kw) == D({"a": 1, "b": 3}) # Verify immutability: d = D({'x': 1}) oldd = d assoc(d, 'x', 2, **kw) assert d is oldd def test_dissoc(self): D, kw = self.D, self.kw assert dissoc(D({"a": 1}), "a", **kw) == D({}) assert dissoc(D({"a": 1, "b": 2}), "a", **kw) == D({"b": 2}) assert dissoc(D({"a": 1, "b": 2}), "b", **kw) == D({"a": 1}) assert dissoc(D({"a": 1, "b": 2}), "a", "b", **kw) == D({}) assert dissoc(D({"a": 1}), "a", **kw) == dissoc(dissoc(D({"a": 1}), "a", **kw), "a", **kw) # Verify immutability: d = D({'x': 1}) oldd = d d2 = dissoc(d, 'x', **kw) assert d is oldd assert d2 is not oldd def test_assoc_in(self): D, kw = self.D, self.kw assert assoc_in(D({"a": 1}), ["a"], 2, **kw) == D({"a": 2}) assert (assoc_in(D({"a": D({"b": 1})}), ["a", "b"], 2, **kw) == D({"a": D({"b": 2})})) assert assoc_in(D({}), ["a", "b"], 1, **kw) == D({"a": D({"b": 1})}) # Verify immutability: d = D({'x': 1}) oldd = d d2 = assoc_in(d, ['x'], 2, **kw) assert d is oldd assert d2 is not oldd def test_update_in(self): D, kw = self.D, self.kw assert update_in(D({"a": 0}), ["a"], inc, **kw) == D({"a": 1}) assert update_in(D({"a": 0, "b": 1}), ["b"], str, **kw) == D({"a": 0, "b": "1"}) assert (update_in(D({"t": 1, "v": D({"a": 0})}), ["v", "a"], inc, **kw) == D({"t": 1, "v": D({"a": 1})})) # Handle one missing key. assert update_in(D({}), ["z"], str, None, **kw) == D({"z": "None"}) assert update_in(D({}), ["z"], inc, 0, **kw) == D({"z": 1}) assert update_in(D({}), ["z"], lambda x: x+"ar", default="b", **kw) == D({"z": "bar"}) # Same semantics as Clojure for multiple missing keys, ie. recursively # create nested empty dictionaries to the depth specified by the # keys with the innermost value set to f(default). assert update_in(D({}), [0, 1], inc, default=-1, **kw) == D({0: D({1: 0})}) assert update_in(D({}), [0, 1], str, default=100, **kw) == D({0: D({1: "100"})}) assert (update_in(D({"foo": "bar", 1: 50}), ["d", 1, 0], str, 20, **kw) == D({"foo": "bar", 1: 50, "d": D({1: D({0: "20"})})})) # Verify immutability: d = D({'x': 1}) oldd = d update_in(d, ['x'], inc, **kw) assert d is oldd def test_factory(self): D, kw = self.D, self.kw assert merge(defaultdict(int, D({1: 2})), D({2: 3})) == {1: 2, 2: 3} assert (merge(defaultdict(int, D({1: 2})), D({2: 3}), factory=lambda: defaultdict(int)) == defaultdict(int, D({1: 2, 2: 3}))) assert not (merge(defaultdict(int, D({1: 2})), D({2: 3}), factory=lambda: defaultdict(int)) == {1: 2, 2: 3}) assert raises(TypeError, lambda: merge(D({1: 2}), D({2: 3}), factoryy=dict))
TestDict
python
doocs__leetcode
solution/0300-0399/0310.Minimum Height Trees/Solution.py
{ "start": 0, "end": 705 }
class ____: def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]: if n == 1: return [0] g = [[] for _ in range(n)] degree = [0] * n for a, b in edges: g[a].append(b) g[b].append(a) degree[a] += 1 degree[b] += 1 q = deque(i for i in range(n) if degree[i] == 1) ans = [] while q: ans.clear() for _ in range(len(q)): a = q.popleft() ans.append(a) for b in g[a]: degree[b] -= 1 if degree[b] == 1: q.append(b) return ans
Solution
python
falconry__falcon
examples/recipes/pretty_json_main.py
{ "start": 29, "end": 847 }
class ____(falcon.media.BaseHandler): MAX_INDENT_LEVEL = 8 def deserialize(self, stream, content_type, content_length): data = stream.read() return json.loads(data.decode()) def serialize(self, media, content_type): _, params = falcon.parse_header(content_type) indent = params.get('indent') if indent is not None: try: indent = int(indent) # NOTE: Impose a reasonable indentation level limit. if indent < 0 or indent > self.MAX_INDENT_LEVEL: indent = None except ValueError: # TODO: Handle invalid params? indent = None result = json.dumps(media, indent=indent, sort_keys=bool(indent)) return result.encode()
CustomJSONHandler
python
keras-team__keras
keras/src/layers/preprocessing/image_preprocessing/cut_mix.py
{ "start": 273, "end": 7877 }
class ____(BaseImagePreprocessingLayer): """CutMix data augmentation technique. CutMix is a data augmentation method where patches are cut and pasted between two images in the dataset, while the labels are also mixed proportionally to the area of the patches. **Note:** This layer is safe to use inside a `tf.data` or `grain` pipeline (independently of which backend you're using). References: - [CutMix paper]( https://arxiv.org/abs/1905.04899). Args: factor: A single float or a tuple of two floats between 0 and 1. If a tuple of numbers is passed, a `factor` is sampled between the two values. If a single float is passed, a value between 0 and the passed float is sampled. These values define the range from which the mixing weight is sampled. A higher factor increases the variability in patch sizes, leading to more diverse and larger mixed patches. Defaults to 1. seed: Integer. Used to create a random seed. """ _USE_BASE_FACTOR = False _FACTOR_BOUNDS = (0, 1) def __init__(self, factor=1.0, seed=None, data_format=None, **kwargs): super().__init__(data_format=data_format, **kwargs) self._set_factor(factor) self.seed = seed self.generator = SeedGenerator(seed) if self.data_format == "channels_first": self.height_axis = -2 self.width_axis = -1 self.channel_axis = -3 else: self.height_axis = -3 self.width_axis = -2 self.channel_axis = -1 def get_random_transformation(self, data, training=True, seed=None): if not training: return None if isinstance(data, dict): images = data["images"] else: images = data images_shape = self.backend.shape(images) if len(images_shape) == 3: return None batch_size = images_shape[0] image_height = images_shape[self.height_axis] image_width = images_shape[self.width_axis] seed = seed or self._get_seed_generator(self.backend._backend) mix_weight = self._generate_mix_weight(batch_size, seed) ratio = self.backend.numpy.sqrt(1.0 - mix_weight) x0, x1 = self._compute_crop_bounds(batch_size, image_width, ratio, seed) y0, y1 = self._compute_crop_bounds( batch_size, image_height, ratio, seed ) batch_masks, mix_weight = self._generate_batch_mask( images_shape, (x0, x1, y0, y1), ) permutation_order = self.backend.random.shuffle( self.backend.numpy.arange(0, batch_size, dtype="int32"), seed=seed, ) return { "permutation_order": permutation_order, "batch_masks": batch_masks, "mix_weight": mix_weight, } def _generate_batch_mask(self, images_shape, box_corners): def _generate_grid_xy(image_height, image_width): grid_y, grid_x = self.backend.numpy.meshgrid( self.backend.numpy.arange( image_height, dtype=self.compute_dtype ), self.backend.numpy.arange( image_width, dtype=self.compute_dtype ), indexing="ij", ) if self.data_format == "channels_last": grid_y = self.backend.cast( grid_y[None, :, :, None], dtype=self.compute_dtype ) grid_x = self.backend.cast( grid_x[None, :, :, None], dtype=self.compute_dtype ) else: grid_y = self.backend.cast( grid_y[None, None, :, :], dtype=self.compute_dtype ) grid_x = self.backend.cast( grid_x[None, None, :, :], dtype=self.compute_dtype ) return grid_x, grid_y image_height, image_width = ( images_shape[self.height_axis], images_shape[self.width_axis], ) grid_x, grid_y = _generate_grid_xy(image_height, image_width) x0, x1, y0, y1 = box_corners x0 = x0[:, None, None, None] y0 = y0[:, None, None, None] x1 = x1[:, None, None, None] y1 = y1[:, None, None, None] batch_masks = ( (grid_x >= x0) & (grid_x < x1) & (grid_y >= y0) & (grid_y < y1) ) batch_masks = self.backend.numpy.repeat( batch_masks, images_shape[self.channel_axis], axis=self.channel_axis ) mix_weight = 1.0 - (x1 - x0) * (y1 - y0) / (image_width * image_height) return batch_masks, mix_weight def _compute_crop_bounds(self, batch_size, image_length, crop_ratio, seed): crop_length = self.backend.cast( crop_ratio * image_length, dtype=self.compute_dtype ) start_pos = self.backend.random.uniform( shape=[batch_size], minval=0, maxval=1, dtype=self.compute_dtype, seed=seed, ) * (image_length - crop_length) end_pos = start_pos + crop_length return start_pos, end_pos def _generate_mix_weight(self, batch_size, seed): alpha = ( self.backend.random.uniform( shape=(), minval=self.factor[0], maxval=self.factor[1], dtype=self.compute_dtype, seed=seed, ) + 1e-6 ) mix_weight = self.backend.random.beta( (batch_size,), alpha, alpha, seed=seed, dtype=self.compute_dtype ) return mix_weight def transform_images(self, images, transformation=None, training=True): if training and transformation is not None: images = self.backend.cast(images, self.compute_dtype) permutation_order = transformation["permutation_order"] batch_masks = transformation["batch_masks"] images = self.backend.numpy.where( batch_masks, self.backend.numpy.take(images, permutation_order, axis=0), images, ) images = self.backend.cast(images, self.compute_dtype) return images def transform_labels(self, labels, transformation, training=True): if training and transformation is not None: permutation_order = transformation["permutation_order"] mix_weight = transformation["mix_weight"] cutout_labels = self.backend.numpy.take( labels, permutation_order, axis=0 ) mix_weight = self.backend.numpy.reshape(mix_weight, [-1, 1]) labels = mix_weight * labels + (1.0 - mix_weight) * cutout_labels return labels def transform_bounding_boxes( self, bounding_boxes, transformation, training=True, ): raise NotImplementedError() def transform_segmentation_masks( self, segmentation_masks, transformation, training=True ): return self.transform_images( segmentation_masks, transformation, training ) def compute_output_shape(self, input_shape): return input_shape def get_config(self): config = { "factor": self.factor, "seed": self.seed, } base_config = super().get_config() return {**base_config, **config}
CutMix
python
facebook__pyre-check
client/commands/infer.py
{ "start": 6080, "end": 7240 }
class ____(json_mixins.CamlCaseAndExcludeJsonMixin): qualifier: str global_annotations: List[RawGlobalAnnotation] = dataclasses.field( metadata=dataclasses_json.config(field_name="globals"), default_factory=list ) attribute_annotations: List[RawAttributeAnnotation] = dataclasses.field( metadata=dataclasses_json.config(field_name="attributes"), default_factory=list ) define_annotations: List[RawDefineAnnotation] = dataclasses.field( metadata=dataclasses_json.config(field_name="defines"), default_factory=list ) @staticmethod def create_from_json(input: Dict[str, object]) -> "RawInferOutputForPath": # pyre-fixme[7]: Imprecise return type of `loads()` return RawInferOutputForPath.cached_schema().loads(json.dumps(input)) def _sanitize_name(name: str) -> str: """The last part of the access path is the function/attribute name""" return name.split(".")[-1] @functools.lru_cache() def empty_module() -> libcst.Module: return libcst.parse_module("") def code_for_node(node: libcst.CSTNode) -> str: return empty_module().code_for_node(node)
RawInferOutputForPath
python
Pylons__pyramid
tests/test_scripting.py
{ "start": 1459, "end": 6705 }
class ____(unittest.TestCase): def _callFUT(self, request=None, registry=None): from pyramid.scripting import prepare return prepare(request, registry) def _makeRegistry(self, L=None): if L is None: L = [None, DummyFactory] return DummyRegistry(L) def setUp(self): from pyramid.threadlocal import manager self.manager = manager self.default = manager.get() def test_it_no_valid_apps(self): from pyramid.exceptions import ConfigurationError self.assertRaises(ConfigurationError, self._callFUT) def test_it_norequest(self): registry = self._makeRegistry([DummyFactory, None, DummyFactory]) info = self._callFUT(registry=registry) root, closer, request = info['root'], info['closer'], info['request'] pushed = self.manager.get() self.assertEqual(pushed['registry'], registry) self.assertEqual(pushed['request'].registry, registry) self.assertEqual(root.a, (pushed['request'],)) closer() self.assertEqual(self.default, self.manager.get()) self.assertEqual(request.context, root) def test_it_withrequest_hasregistry(self): request = DummyRequest({}) registry = request.registry = self._makeRegistry() info = self._callFUT(request=request) root, closer, request = info['root'], info['closer'], info['request'] pushed = self.manager.get() self.assertEqual(pushed['request'], request) self.assertEqual(pushed['registry'], registry) self.assertEqual(pushed['request'].registry, registry) self.assertEqual(root.a, (request,)) closer() self.assertEqual(self.default, self.manager.get()) self.assertEqual(request.context, root) self.assertEqual(request.registry, registry) def test_it_withrequest_noregistry(self): request = DummyRequest({}) registry = self._makeRegistry() info = self._callFUT(request=request, registry=registry) root, closer, request = info['root'], info['closer'], info['request'] closer() self.assertEqual(request.context, root) # should be set by prepare self.assertEqual(request.registry, registry) def test_it_with_request_and_registry(self): request = DummyRequest({}) registry = request.registry = self._makeRegistry() info = self._callFUT(request=request, registry=registry) root, closer, root = info['root'], info['closer'], info['root'] pushed = self.manager.get() self.assertEqual(pushed['request'], request) self.assertEqual(pushed['registry'], registry) self.assertEqual(pushed['request'].registry, registry) self.assertEqual(root.a, (request,)) closer() self.assertEqual(self.default, self.manager.get()) self.assertEqual(request.context, root) def test_it_with_request_context_already_set(self): request = DummyRequest({}) context = Dummy() request.context = context registry = request.registry = self._makeRegistry() info = self._callFUT(request=request, registry=registry) closer = info['closer'] closer() self.assertEqual(request.context, context) def test_it_with_extensions(self): from pyramid.util import InstancePropertyHelper exts = DummyExtensions() ext_method = lambda r: 'bar' name, fn = InstancePropertyHelper.make_property(ext_method, 'foo') exts.descriptors[name] = fn request = DummyRequest({}) registry = request.registry = self._makeRegistry([exts, DummyFactory]) info = self._callFUT(request=request, registry=registry) self.assertEqual(request.foo, 'bar') closer = info['closer'] closer() def test_it_is_a_context_manager(self): request = DummyRequest({}) registry = request.registry = self._makeRegistry() closer_called = [False] with self._callFUT(request=request) as info: root, request = info['root'], info['request'] pushed = self.manager.get() self.assertEqual(pushed['request'], request) self.assertEqual(pushed['registry'], registry) self.assertEqual(pushed['request'].registry, registry) self.assertEqual(root.a, (request,)) orig_closer = info['closer'] def closer(): orig_closer() closer_called[0] = True info['closer'] = closer self.assertTrue(closer_called[0]) self.assertEqual(self.default, self.manager.get()) self.assertEqual(request.context, root) self.assertEqual(request.registry, registry) def test_closer_invokes_finished_callbacks(self): finish_called = [False] def finished_callback(request): finish_called[0] = True request = DummyRequest({}) request.registry = self._makeRegistry() info = self._callFUT(request=request) request.add_finished_callback(finished_callback) closer = info['closer'] closer() self.assertTrue(finish_called[0])
Test_prepare
python
kamyu104__LeetCode-Solutions
Python/print-zero-even-odd.py
{ "start": 48, "end": 1359 }
class ____(object): def __init__(self, n): self.__n = n self.__curr = 0 self.__cv = threading.Condition() # printNumber(x) outputs "x", where x is an integer. def zero(self, printNumber): """ :type printNumber: method :rtype: void """ for i in xrange(self.__n): with self.__cv: while self.__curr % 2 != 0: self.__cv.wait() self.__curr += 1 printNumber(0) self.__cv.notifyAll() def even(self, printNumber): """ :type printNumber: method :rtype: void """ for i in xrange(2, self.__n+1, 2): with self.__cv: while self.__curr % 4 != 3: self.__cv.wait() self.__curr += 1 printNumber(i) self.__cv.notifyAll() def odd(self, printNumber): """ :type printNumber: method :rtype: void """ for i in xrange(1, self.__n+1, 2): with self.__cv: while self.__curr % 4 != 1: self.__cv.wait() self.__curr += 1 printNumber(i) self.__cv.notifyAll()
ZeroEvenOdd
python
keras-team__keras
keras/src/backend/common/masking_test.py
{ "start": 208, "end": 1311 }
class ____(testing.TestCase): def test_mask_on_eager_tensor(self): x = ops.zeros((2, 3)) self.assertIsNone(get_keras_mask(x)) set_keras_mask(x, None) self.assertIsNone(get_keras_mask(x)) mask = ops.ones((2, 3)) set_keras_mask(x, mask) self.assertIs(get_keras_mask(x), mask) set_keras_mask(x, None) self.assertIsNone(get_keras_mask(x)) set_keras_mask(x, None) self.assertIsNone(get_keras_mask(x)) def test_mask_on_tracer_tensor(self): def fn(x): self.assertIsNone(get_keras_mask(x)) set_keras_mask(x, None) self.assertIsNone(get_keras_mask(x)) mask = ops.ones((2, 3)) set_keras_mask(x, mask) self.assertIs(get_keras_mask(x), mask) set_keras_mask(x, None) self.assertIsNone(get_keras_mask(x)) set_keras_mask(x, None) # key is now deleted, should be a no-op self.assertIsNone(get_keras_mask(x)) backend.compute_output_spec(fn, backend.KerasTensor((2, 3)))
MaskingTest
python
facebook__pyre-check
source/interprocedural_analyses/taint/test/integration/constructors.py
{ "start": 3390, "end": 3805 }
class ____(ConstructorTitoModelQuery): def __init__(self, a, b): super().__init__(a, b) def test_constructor_with_tito_model_query(): _test_sink(DerivedConstructorTitoModelQuery("", "").a) # No issue. _test_sink(DerivedConstructorTitoModelQuery(_test_source(), "").a) # Issue. _test_sink(DerivedConstructorTitoModelQuery("", _test_source()).a) # No issue.
DerivedConstructorTitoModelQuery
python
PrefectHQ__prefect
src/prefect/server/utilities/messaging/__init__.py
{ "start": 3071, "end": 3230 }
class ____(Exception): """ Exception to raise to stop a consumer. """ def __init__(self, ack: bool = False): self.ack = ack
StopConsumer
python
allegroai__clearml
clearml/backend_api/services/v2_20/tasks.py
{ "start": 394025, "end": 395873 }
class ____(Response): """ Response of tasks.stop endpoint. :param updated: Number of tasks updated (0 or 1) :type updated: int :param fields: Updated fields names and values :type fields: dict """ _service = "tasks" _action = "stop" _version = "2.20" _schema = { "definitions": {}, "properties": { "fields": { "additionalProperties": True, "description": "Updated fields names and values", "type": ["object", "null"], }, "updated": { "description": "Number of tasks updated (0 or 1)", "enum": [0, 1], "type": ["integer", "null"], }, }, "type": "object", } def __init__(self, updated: Optional[int] = None, fields: Optional[dict] = None, **kwargs: Any) -> None: super(StopResponse, self).__init__(**kwargs) self.updated = updated self.fields = fields @schema_property("updated") def updated(self) -> Optional[int]: return self._property_updated @updated.setter def updated(self, value: Optional[int]) -> None: if value is None: self._property_updated = None return if isinstance(value, float) and value.is_integer(): value = int(value) self.assert_isinstance(value, "updated", six.integer_types) self._property_updated = value @schema_property("fields") def fields(self) -> Optional[dict]: return self._property_fields @fields.setter def fields(self, value: Optional[dict]) -> None: if value is None: self._property_fields = None return self.assert_isinstance(value, "fields", (dict,)) self._property_fields = value
StopResponse
python
weaviate__weaviate-python-client
weaviate/aliases/executor.py
{ "start": 321, "end": 5498 }
class ____(Generic[ConnectionType]): def __init__(self, connection: Connection): self._connection = connection def list_all( self, *, collection: Optional[str] = None ) -> executor.Result[Dict[str, AliasReturn]]: """Get the alias for a given alias name.""" self._connection._weaviate_version.check_is_at_least_1_32_0("alias") error_msg = "list all aliases" if collection is not None: error_msg += f" for collection {collection}" def resp(res: Response) -> Dict[str, AliasReturn]: response_typed = _decode_json_response_dict(res, "list all aliases") assert response_typed is not None aliases = response_typed.get("aliases") assert aliases is not None, "Expected 'aliases' in response" return { alias["alias"]: AliasReturn(alias=alias["alias"], collection=alias["class"]) for alias in cast(List[_WeaviateAlias], aliases) } return executor.execute( response_callback=resp, method=self._connection.get, path="/aliases", error_msg=error_msg, params={"class": collection} if collection else None, status_codes=_ExpectedStatusCodes( ok_in=[200], error=error_msg, ), ) def get(self, *, alias_name: str) -> executor.Result[Optional[AliasReturn]]: """Get the given alias.""" self._connection._weaviate_version.check_is_at_least_1_32_0("alias") def resp(res: Response) -> Optional[AliasReturn]: if res.status_code == 404: return None response_typed = _decode_json_response_dict(res, "get alias") assert response_typed is not None return AliasReturn(alias=response_typed["alias"], collection=response_typed["class"]) return executor.execute( response_callback=resp, method=self._connection.get, path=f"/aliases/{alias_name}", error_msg=f"Could not get alias {alias_name}", status_codes=_ExpectedStatusCodes( ok_in=[200, 404], error="get alias", ), ) def create(self, *, alias_name: str, target_collection: str) -> executor.Result[None]: """Create an alias for a given collection.""" self._connection._weaviate_version.check_is_at_least_1_32_0("alias") def resp(res: Response) -> None: return None return executor.execute( response_callback=resp, method=self._connection.post, path="/aliases", error_msg=f"Could not create alias {alias_name} for collection {target_collection}", weaviate_object={"class": target_collection, "alias": alias_name}, status_codes=_ExpectedStatusCodes( ok_in=[200], error="create aliases", ), ) def delete(self, *, alias_name: str) -> executor.Result[bool]: """Create an alias.""" self._connection._weaviate_version.check_is_at_least_1_32_0("alias") def resp(res: Response) -> bool: return res.status_code == 204 return executor.execute( response_callback=resp, method=self._connection.delete, path=f"/aliases/{alias_name}", error_msg=f"Could not delete alias {alias_name}", status_codes=_ExpectedStatusCodes( ok_in=[204, 404], error="delete aliases", ), ) def update(self, *, alias_name: str, new_target_collection: str) -> executor.Result[bool]: """Replace an alias.""" self._connection._weaviate_version.check_is_at_least_1_32_0("alias") def resp(res: Response) -> bool: return res.status_code == 200 return executor.execute( response_callback=resp, method=self._connection.put, path=f"/aliases/{alias_name}", weaviate_object={"class": new_target_collection}, error_msg=f"Could not update alias {alias_name} to point to collection {new_target_collection}", status_codes=_ExpectedStatusCodes( ok_in=[200, 404], error="update aliases", ), ) def exists(self, *, alias_name: str) -> executor.Result[bool]: """Use this method to check if an alias exists in the Weaviate instance. Args: name: The name of the alias to check. Returns: `True` if the alias exists, `False` otherwise. """ self._connection._weaviate_version.check_is_at_least_1_32_0("alias") def resp(res: Response) -> bool: return res.status_code == 200 return executor.execute( response_callback=resp, method=self._connection.get, path=f"/aliases/{alias_name}", error_msg="Alias may not exist.", status_codes=_ExpectedStatusCodes(ok_in=[200, 404], error="alias exists"), )
_AliasExecutor
python
sympy__sympy
sympy/polys/fields.py
{ "start": 10866, "end": 22375 }
class ____(DomainElement, DefaultPrinting, CantSympify, Generic[Er]): """Element of multivariate distributed rational function field. """ def __init__(self, field: FracField[Er], numer: PolyElement[Er], denom: PolyElement[Er] | None = None) -> None: if denom is None: denom = field.ring.one elif not denom: raise ZeroDivisionError("zero denominator") self.field = field self.numer = numer self.denom = denom def raw_new(f, numer: PolyElement[Er], denom: PolyElement[Er] | None = None) -> FracElement[Er]: return f.__class__(f.field, numer, denom) def new(f, numer, denom): return f.raw_new(*numer.cancel(denom)) def to_poly(f): if f.denom != 1: raise ValueError("f.denom should be 1") return f.numer def parent(self): return self.field.to_domain() def __getnewargs__(self): return (self.field, self.numer, self.denom) _hash = None def __hash__(self): _hash = self._hash if _hash is None: self._hash = _hash = hash((self.field, self.numer, self.denom)) return _hash def copy(self): return self.raw_new(self.numer.copy(), self.denom.copy()) def set_field(self, new_field: FracField[Es]) -> FracElement[Es]: if self.field == new_field: return self # type: ignore else: new_ring = new_field.ring numer = self.numer.set_ring(new_ring) denom = self.denom.set_ring(new_ring) return new_field.new(numer, denom) def as_expr(self, *symbols) -> Expr: return self.numer.as_expr(*symbols)/self.denom.as_expr(*symbols) def __eq__(f, g): if isinstance(g, FracElement) and f.field == g.field: return f.numer == g.numer and f.denom == g.denom else: return f.numer == g and f.denom == f.field.ring.one def __ne__(f, g): return not f == g def __bool__(f): return bool(f.numer) def sort_key(self): return (self.denom.sort_key(), self.numer.sort_key()) def _cmp(f1, f2, op): if f1.field.is_element(f2): return op(f1.sort_key(), f2.sort_key()) else: return NotImplemented def __lt__(f1, f2): return f1._cmp(f2, lt) def __le__(f1, f2): return f1._cmp(f2, le) def __gt__(f1, f2): return f1._cmp(f2, gt) def __ge__(f1, f2): return f1._cmp(f2, ge) def __pos__(f): """Negate all coefficients in ``f``. """ return f.raw_new(f.numer, f.denom) def __neg__(f): """Negate all coefficients in ``f``. """ return f.raw_new(-f.numer, f.denom) def _extract_ground(self, element): domain = self.field.domain try: element = domain.convert(element) except CoercionFailed: if not domain.is_Field and domain.has_assoc_Field: ground_field = domain.get_field() try: element = ground_field.convert(element) except CoercionFailed: pass else: return -1, ground_field.numer(element), ground_field.denom(element) return 0, None, None else: return 1, element, None def __add__(f, g): """Add rational functions ``f`` and ``g``. """ field = f.field if not g: return f elif not f: return g elif field.is_element(g): if f.denom == g.denom: return f.new(f.numer + g.numer, f.denom) else: return f.new(f.numer*g.denom + f.denom*g.numer, f.denom*g.denom) elif field.ring.is_element(g): return f.new(f.numer + f.denom*g, f.denom) else: if isinstance(g, FracElement): if isinstance(field.domain, FractionField) and field.domain.field == g.field: pass elif isinstance(g.field.domain, FractionField) and g.field.domain.field == field: return g.__radd__(f) else: return NotImplemented elif isinstance(g, PolyElement): if isinstance(field.domain, PolynomialRing) and field.domain.ring == g.ring: pass else: return g.__radd__(f) return f.__radd__(g) def __radd__(f, c): if f.field.ring.is_element(c): return f.new(f.numer + f.denom*c, f.denom) op, g_numer, g_denom = f._extract_ground(c) if op == 1: return f.new(f.numer + f.denom*g_numer, f.denom) elif not op: return NotImplemented else: return f.new(f.numer*g_denom + f.denom*g_numer, f.denom*g_denom) def __sub__(f, g): """Subtract rational functions ``f`` and ``g``. """ field = f.field if not g: return f elif not f: return -g elif field.is_element(g): if f.denom == g.denom: return f.new(f.numer - g.numer, f.denom) else: return f.new(f.numer*g.denom - f.denom*g.numer, f.denom*g.denom) elif field.ring.is_element(g): return f.new(f.numer - f.denom*g, f.denom) else: if isinstance(g, FracElement): if isinstance(field.domain, FractionField) and field.domain.field == g.field: pass elif isinstance(g.field.domain, FractionField) and g.field.domain.field == field: return g.__rsub__(f) else: return NotImplemented elif isinstance(g, PolyElement): if isinstance(field.domain, PolynomialRing) and field.domain.ring == g.ring: pass else: return g.__rsub__(f) op, g_numer, g_denom = f._extract_ground(g) if op == 1: return f.new(f.numer - f.denom*g_numer, f.denom) elif not op: return NotImplemented else: return f.new(f.numer*g_denom - f.denom*g_numer, f.denom*g_denom) def __rsub__(f, c): if f.field.ring.is_element(c): return f.new(-f.numer + f.denom*c, f.denom) op, g_numer, g_denom = f._extract_ground(c) if op == 1: return f.new(-f.numer + f.denom*g_numer, f.denom) elif not op: return NotImplemented else: return f.new(-f.numer*g_denom + f.denom*g_numer, f.denom*g_denom) def __mul__(f, g): """Multiply rational functions ``f`` and ``g``. """ field = f.field if not f or not g: return field.zero elif field.is_element(g): return f.new(f.numer*g.numer, f.denom*g.denom) elif field.ring.is_element(g): return f.new(f.numer*g, f.denom) else: if isinstance(g, FracElement): if isinstance(field.domain, FractionField) and field.domain.field == g.field: pass elif isinstance(g.field.domain, FractionField) and g.field.domain.field == field: return g.__rmul__(f) else: return NotImplemented elif isinstance(g, PolyElement): if isinstance(field.domain, PolynomialRing) and field.domain.ring == g.ring: pass else: return g.__rmul__(f) return f.__rmul__(g) def __rmul__(f, c): if f.field.ring.is_element(c): return f.new(f.numer*c, f.denom) op, g_numer, g_denom = f._extract_ground(c) if op == 1: return f.new(f.numer*g_numer, f.denom) elif not op: return NotImplemented else: return f.new(f.numer*g_numer, f.denom*g_denom) def __truediv__(f, g): """Computes quotient of fractions ``f`` and ``g``. """ field = f.field if not g: raise ZeroDivisionError elif field.is_element(g): return f.new(f.numer*g.denom, f.denom*g.numer) elif field.ring.is_element(g): return f.new(f.numer, f.denom*g) else: if isinstance(g, FracElement): if isinstance(field.domain, FractionField) and field.domain.field == g.field: pass elif isinstance(g.field.domain, FractionField) and g.field.domain.field == field: return g.__rtruediv__(f) else: return NotImplemented elif isinstance(g, PolyElement): if isinstance(field.domain, PolynomialRing) and field.domain.ring == g.ring: pass else: return g.__rtruediv__(f) op, g_numer, g_denom = f._extract_ground(g) if op == 1: return f.new(f.numer, f.denom*g_numer) elif not op: return NotImplemented else: return f.new(f.numer*g_denom, f.denom*g_numer) def __rtruediv__(f, c): if not f: raise ZeroDivisionError elif f.field.ring.is_element(c): return f.new(f.denom*c, f.numer) op, g_numer, g_denom = f._extract_ground(c) if op == 1: return f.new(f.denom*g_numer, f.numer) elif not op: return NotImplemented else: return f.new(f.denom*g_numer, f.numer*g_denom) def __pow__(f, n): """Raise ``f`` to a non-negative power ``n``. """ if n >= 0: return f.raw_new(f.numer**n, f.denom**n) elif not f: raise ZeroDivisionError else: return f.raw_new(f.denom**-n, f.numer**-n) def diff(f, x): """Computes partial derivative in ``x``. Examples ======== >>> from sympy.polys.fields import field >>> from sympy.polys.domains import ZZ >>> _, x, y, z = field("x,y,z", ZZ) >>> ((x**2 + y)/(z + 1)).diff(x) 2*x/(z + 1) """ x = x.to_poly() return f.new(f.numer.diff(x)*f.denom - f.numer*f.denom.diff(x), f.denom**2) def __call__(f, *values): if 0 < len(values) <= f.field.ngens: return f.evaluate(list(zip(f.field.gens, values))) else: raise ValueError("expected at least 1 and at most %s values, got %s" % (f.field.ngens, len(values))) def evaluate(f, x, a=None): if isinstance(x, list) and a is None: x = [ (X.to_poly(), a) for X, a in x ] numer, denom = f.numer.evaluate(x), f.denom.evaluate(x) else: x = x.to_poly() numer, denom = f.numer.evaluate(x, a), f.denom.evaluate(x, a) field = numer.ring.to_field() return field.new(numer, denom) def subs(f, x, a=None): if isinstance(x, list) and a is None: x = [ (X.to_poly(), a) for X, a in x ] numer, denom = f.numer.subs(x), f.denom.subs(x) else: x = x.to_poly() numer, denom = f.numer.subs(x, a), f.denom.subs(x, a) return f.new(numer, denom) def compose(f, x, a=None): raise NotImplementedError
FracElement
python
pytorch__pytorch
torch/testing/_internal/opinfo/core.py
{ "start": 114296, "end": 116811 }
class ____(OpInfo): """Early version of a specialized OpInfo for Shape manipulating operations like tile and roll""" def __init__( self, name, # the string name of the function *, ref, # a reference function dtypes=floating_types(), dtypesIfCUDA=None, dtypesIfROCM=None, dtypesIfXPU=None, sample_inputs_func=None, **kwargs, ): super().__init__( name, dtypes=dtypes, dtypesIfCUDA=dtypesIfCUDA, dtypesIfROCM=dtypesIfROCM, dtypesIfXPU=dtypesIfXPU, sample_inputs_func=sample_inputs_func, **kwargs, ) self.ref = ref def sample_inputs_foreach( self, device, dtype, N, *, noncontiguous=False, same_size=False, low=None, high=None, # zero_size means EVERY input is empty zero_size: bool, requires_grad: bool, # mutually exclusive from same_size and zero_size, which are all or nothing intersperse_empty_tensors: bool = False, ): if zero_size: return [torch.empty(0, dtype=dtype, device=device) for _ in range(N)] if same_size: return [ make_tensor( (N, N), dtype=dtype, device=device, noncontiguous=noncontiguous, low=low, high=high, requires_grad=requires_grad, ) for _ in range(N) ] else: # interweave some empty tensors + have the last 2 tensors be empty (see #100701) return [ torch.empty(0, dtype=dtype, device=device, requires_grad=requires_grad) if (i % 3 == 0 or i >= N - 2) and intersperse_empty_tensors else make_tensor( (N - i, N - i), dtype=dtype, device=device, noncontiguous=noncontiguous, low=low, high=high, requires_grad=requires_grad, ) for i in range(N) ] def get_foreach_method_names(name): # get torch inplace reference function op_name = "_foreach_" + name inplace_op_name = op_name + "_" op = getattr(torch, op_name, None) inplace_op = getattr(torch, inplace_op_name, None) ref = getattr(torch, name, None) ref_inplace = getattr(torch.Tensor, name + "_", None) return op, inplace_op, ref, ref_inplace @dataclass
ShapeFuncInfo
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pyupgrade/UP049_1.py
{ "start": 360, "end": 636 }
class ____[_T, _U: str, _V: (int, float), *_W, **_X]: @staticmethod def transform(t: _T, u: _U, v: _V) -> tuple[*_W] | Callable[_X, _T] | None: return None # this should not be fixed because the new name is a keyword, but we still # offer a diagnostic
Everything
python
Pylons__pyramid
tests/test_exceptions.py
{ "start": 485, "end": 827 }
class ____(unittest.TestCase): def test_response_equivalence(self): from pyramid.exceptions import BadCSRFOrigin from pyramid.httpexceptions import HTTPBadRequest self.assertTrue(isinstance(BadCSRFOrigin(), HTTPBadRequest)) self.assertEqual(BadCSRFOrigin().status, HTTPBadRequest().status)
TestBadCSRFOrigin
python
pytorch__pytorch
test/test_overrides.py
{ "start": 7358, "end": 8061 }
class ____(torch.Tensor): pass @implements_sub(torch.mean) def sub_mean(mat): return 0 @implements_sub(torch.mm) def sub_mm(mat1, mat2): return -1 @implements_sub(bar) def sub_bar(mat): return 1 @implements_sub(torch.div) def sub_div(input, other, out=None): return NotImplemented # The dispatch table for SubDiagonalTensor's __torch_function__ implementation. HANDLED_FUNCTIONS_SUB_DIAGONAL = {} def implements_sub_diagonal(torch_function): "Register a torch function override for SubDiagonalTensor" @functools.wraps(torch_function) def decorator(func): HANDLED_FUNCTIONS_SUB_DIAGONAL[torch_function] = func return func return decorator
SubTensor3
python
plotly__plotly.py
plotly/graph_objs/volume/_lightposition.py
{ "start": 233, "end": 3489 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "volume" _path_str = "volume.lightposition" _valid_props = {"x", "y", "z"} @property def x(self): """ Numeric vector, representing the X coordinate for each vertex. The 'x' property is a number and may be specified as: - An int or float in the interval [-100000, 100000] Returns ------- int|float """ return self["x"] @x.setter def x(self, val): self["x"] = val @property def y(self): """ Numeric vector, representing the Y coordinate for each vertex. The 'y' property is a number and may be specified as: - An int or float in the interval [-100000, 100000] Returns ------- int|float """ return self["y"] @y.setter def y(self, val): self["y"] = val @property def z(self): """ Numeric vector, representing the Z coordinate for each vertex. The 'z' property is a number and may be specified as: - An int or float in the interval [-100000, 100000] Returns ------- int|float """ return self["z"] @z.setter def z(self, val): self["z"] = val @property def _prop_descriptions(self): return """\ x Numeric vector, representing the X coordinate for each vertex. y Numeric vector, representing the Y coordinate for each vertex. z Numeric vector, representing the Z coordinate for each vertex. """ def __init__(self, arg=None, x=None, y=None, z=None, **kwargs): """ Construct a new Lightposition object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.volume.Lightposition` x Numeric vector, representing the X coordinate for each vertex. y Numeric vector, representing the Y coordinate for each vertex. z Numeric vector, representing the Z coordinate for each vertex. Returns ------- Lightposition """ super().__init__("lightposition") if "_parent" in kwargs: self._parent = kwargs["_parent"] return if arg is None: arg = {} elif isinstance(arg, self.__class__): arg = arg.to_plotly_json() elif isinstance(arg, dict): arg = _copy.copy(arg) else: raise ValueError("""\ The first argument to the plotly.graph_objs.volume.Lightposition constructor must be a dict or an instance of :class:`plotly.graph_objs.volume.Lightposition`""") self._skip_invalid = kwargs.pop("skip_invalid", False) self._validate = kwargs.pop("_validate", True) self._set_property("x", arg, x) self._set_property("y", arg, y) self._set_property("z", arg, z) self._process_kwargs(**dict(arg, **kwargs)) self._skip_invalid = False
Lightposition
python
pytorch__pytorch
torch/distributed/fsdp/fully_sharded_data_parallel.py
{ "start": 2999, "end": 101286 }
class ____(nn.Module, _FSDPState): """A wrapper for sharding module parameters across data parallel workers. This is inspired by `Xu et al. <https://arxiv.org/abs/2004.13336>`_ as well as the ZeRO Stage 3 from `DeepSpeed <https://www.deepspeed.ai/>`_. FullyShardedDataParallel is commonly shortened to FSDP. Example:: >>> # xdoctest: +SKIP("undefined variables") >>> import torch >>> from torch.distributed.fsdp import FullyShardedDataParallel as FSDP >>> torch.cuda.set_device(device_id) >>> sharded_module = FSDP(my_module) >>> optim = torch.optim.Adam(sharded_module.parameters(), lr=0.0001) >>> x = sharded_module(x, y=3, z=torch.Tensor([1])) >>> loss = x.sum() >>> loss.backward() >>> optim.step() Using FSDP involves wrapping your module and then initializing your optimizer after. This is required since FSDP changes the parameter variables. When setting up FSDP, you need to consider the destination CUDA device. If the device has an ID (``dev_id``), you have three options: * Place the module on that device * Set the device using ``torch.cuda.set_device(dev_id)`` * Pass ``dev_id`` into the ``device_id`` constructor argument. This ensures that the FSDP instance's compute device is the destination device. For option 1 and 3, the FSDP initialization always occurs on GPU. For option 2, the FSDP initialization happens on module's current device, which may be a CPU. If you're using the ``sync_module_states=True`` flag, you need to ensure that the module is on a GPU or use the ``device_id`` argument to specify a CUDA device that FSDP will move the module to in the FSDP constructor. This is necessary because ``sync_module_states=True`` requires GPU communication. FSDP also takes care of moving input tensors to the forward method to the GPU compute device, so you don't need to manually move them from CPU. For ``use_orig_params=True``, ``ShardingStrategy.SHARD_GRAD_OP`` exposes the unsharded parameters, not the sharded parameters after forward, unlike ``ShardingStrategy.FULL_SHARD``. If you want to inspect the gradients, you can use the ``summon_full_params`` method with ``with_grads=True``. With ``limit_all_gathers=True``, you may see a gap in the FSDP pre-forward where the CPU thread is not issuing any kernels. This is intentional and shows the rate limiter in effect. Synchronizing the CPU thread in that way prevents over-allocating memory for subsequent all-gathers, and it should not actually delay GPU kernel execution. FSDP replaces managed modules' parameters with ``torch.Tensor`` views during forward and backward computation for autograd-related reasons. If your module's forward relies on saved references to the parameters instead of reacquiring the references each iteration, then it will not see FSDP's newly created views, and autograd will not work correctly. Finally, when using ``sharding_strategy=ShardingStrategy.HYBRID_SHARD`` with the sharding process group being intra-node and the replication process group being inter-node, setting ``NCCL_CROSS_NIC=1`` can help improve the all-reduce times over the replication process group for some cluster setups. **Limitations** There are several limitations to be aware of when using FSDP: * FSDP currently does not support gradient accumulation outside ``no_sync()`` when using CPU offloading. This is because FSDP uses the newly-reduced gradient instead of accumulating with any existing gradient, which can lead to incorrect results. * FSDP does not support running the forward pass of a submodule that is contained in an FSDP instance. This is because the submodule's parameters will be sharded, but the submodule itself is not an FSDP instance, so its forward pass will not all-gather the full parameters appropriately. * FSDP does not work with double backwards due to the way it registers backward hooks. * FSDP has some constraints when freezing parameters. For ``use_orig_params=False``, each FSDP instance must manage parameters that are all frozen or all non-frozen. For ``use_orig_params=True``, FSDP supports mixing frozen and non-frozen parameters, but it's recommended to avoid doing so to prevent higher than expected gradient memory usage. * As of PyTorch 1.12, FSDP offers limited support for shared parameters. If enhanced shared parameter support is needed for your use case, please post in `this issue <https://github.com/pytorch/pytorch/issues/77724>`__. * You should avoid modifying the parameters between forward and backward without using the ``summon_full_params`` context, as the modifications may not persist. Args: module (nn.Module): This is the module to be wrapped with FSDP. process_group (Optional[Union[ProcessGroup, Tuple[ProcessGroup, ProcessGroup]]]): This is the process group over which the model is sharded and thus the one used for FSDP's all-gather and reduce-scatter collective communications. If ``None``, then FSDP uses the default process group. For hybrid sharding strategies such as ``ShardingStrategy.HYBRID_SHARD``, users can pass in a tuple of process groups, representing the groups over which to shard and replicate, respectively. If ``None``, then FSDP constructs process groups for the user to shard intra-node and replicate inter-node. (Default: ``None``) sharding_strategy (Optional[ShardingStrategy]): This configures the sharding strategy, which may trade off memory saving and communication overhead. See :class:`ShardingStrategy` for details. (Default: ``FULL_SHARD``) cpu_offload (Optional[CPUOffload]): This configures CPU offloading. If this is set to ``None``, then no CPU offloading happens. See :class:`CPUOffload` for details. (Default: ``None``) auto_wrap_policy (Optional[Union[Callable[[nn.Module, bool, int], bool], ModuleWrapPolicy, CustomPolicy]]): This specifies a policy to apply FSDP to submodules of ``module``, which is needed for communication and computation overlap and thus affects performance. If ``None``, then FSDP only applies to ``module``, and users should manually apply FSDP to parent modules themselves (proceeding bottom-up). For convenience, this accepts ``ModuleWrapPolicy`` directly, which allows users to specify the module classes to wrap (e.g. the transformer block). Otherwise, this should be a callable that takes in three arguments ``module: nn.Module``, ``recurse: bool``, and ``nonwrapped_numel: int`` and should return a ``bool`` specifying whether the passed-in ``module`` should have FSDP applied if ``recurse=False`` or if the traversal should continue into the module's subtree if ``recurse=True``. Users may add additional arguments to the callable. The ``size_based_auto_wrap_policy`` in ``torch.distributed.fsdp.wrap.py`` gives an example callable that applies FSDP to a module if the parameters in its subtree exceed 100M numel. We recommend printing the model after applying FSDP and adjusting as needed. Example:: >>> def custom_auto_wrap_policy( >>> module: nn.Module, >>> recurse: bool, >>> nonwrapped_numel: int, >>> # Additional custom arguments >>> min_num_params: int = int(1e8), >>> ) -> bool: >>> return nonwrapped_numel >= min_num_params >>> # Configure a custom `min_num_params` >>> my_auto_wrap_policy = functools.partial(custom_auto_wrap_policy, min_num_params=int(1e5)) backward_prefetch (Optional[BackwardPrefetch]): This configures explicit backward prefetching of all-gathers. If ``None``, then FSDP does not backward prefetch, and there is no communication and computation overlap in the backward pass. See :class:`BackwardPrefetch` for details. (Default: ``BACKWARD_PRE``) mixed_precision (Optional[MixedPrecision]): This configures native mixed precision for FSDP. If this is set to ``None``, then no mixed precision is used. Otherwise, parameter, buffer, and gradient reduction dtypes can be set. See :class:`MixedPrecision` for details. (Default: ``None``) ignored_modules (Optional[Iterable[torch.nn.Module]]): Modules whose own parameters and child modules' parameters and buffers are ignored by this instance. None of the modules directly in ``ignored_modules`` should be :class:`FullyShardedDataParallel` instances, and any child modules that are already-constructed :class:`FullyShardedDataParallel` instances will not be ignored if they are nested under this instance. This argument may be used to avoid sharding specific parameters at module granularity when using an ``auto_wrap_policy`` or if parameters' sharding is not managed by FSDP. (Default: ``None``) param_init_fn (Optional[Callable[[nn.Module], None]]): A ``Callable[torch.nn.Module] -> None`` that specifies how modules that are currently on the meta device should be initialized onto an actual device. As of v1.12, FSDP detects modules with parameters or buffers on meta device via ``is_meta`` and either applies ``param_init_fn`` if specified or calls ``nn.Module.reset_parameters()`` otherwise. For both cases, the implementation should *only* initialize the parameters/buffers of the module, not those of its submodules. This is to avoid re-initialization. In addition, FSDP also supports deferred initialization via torchdistX's (https://github.com/pytorch/torchdistX) ``deferred_init()`` API, where the deferred modules are initialized by calling ``param_init_fn`` if specified or torchdistX's default ``materialize_module()`` otherwise. If ``param_init_fn`` is specified, then it is applied to all meta-device modules, meaning that it should probably case on the module type. FSDP calls the initialization function before parameter flattening and sharding. Example:: >>> # xdoctest: +SKIP("undefined variables") >>> module = MyModule(device="meta") >>> def my_init_fn(module: nn.Module): >>> # E.g. initialize depending on the module type >>> ... >>> fsdp_model = FSDP(module, param_init_fn=my_init_fn, auto_wrap_policy=size_based_auto_wrap_policy) >>> print(next(fsdp_model.parameters()).device) # current CUDA device >>> # With torchdistX >>> module = deferred_init.deferred_init(MyModule, device="cuda") >>> # Will initialize via deferred_init.materialize_module(). >>> fsdp_model = FSDP(module, auto_wrap_policy=size_based_auto_wrap_policy) device_id (Optional[Union[int, torch.device]]): An ``int`` or ``torch.device`` giving the CUDA device on which FSDP initialization takes place, including the module initialization if needed and the parameter sharding. This should be specified to improve initialization speed if ``module`` is on CPU. If the default CUDA device was set (e.g. via ``torch.cuda.set_device``), then the user may pass ``torch.cuda.current_device`` to this. (Default: ``None``) sync_module_states (bool): If ``True``, then each FSDP module will broadcast module parameters and buffers from rank 0 to ensure that they are replicated across ranks (adding communication overhead to this constructor). This can help load ``state_dict`` checkpoints via ``load_state_dict`` in a memory efficient way. See :class:`FullStateDictConfig` for an example of this. (Default: ``False``) forward_prefetch (bool): If ``True``, then FSDP *explicitly* prefetches the next forward-pass all-gather before the current forward computation. This is only useful for CPU-bound workloads, in which case issuing the next all-gather earlier may improve overlap. This should only be used for static-graph models since the prefetching follows the first iteration's execution order. (Default: ``False``) limit_all_gathers (bool): If ``True``, then FSDP explicitly synchronizes the CPU thread to ensure GPU memory usage from only *two* consecutive FSDP instances (the current instance running computation and the next instance whose all-gather is prefetched). If ``False``, then FSDP allows the CPU thread to issue all-gathers without any extra synchronization. (Default: ``True``) We often refer to this feature as the "rate limiter". This flag should only be set to ``False`` for specific CPU-bound workloads with low memory pressure in which case the CPU thread can aggressively issue all kernels without concern for the GPU memory usage. use_orig_params (bool): Setting this to ``True`` has FSDP use ``module`` 's original parameters. FSDP exposes those original parameters to the user via :meth:`nn.Module.named_parameters` instead of FSDP's internal :class:`FlatParameter` s. This means that the optimizer step runs on the original parameters, enabling per-original-parameter hyperparameters. FSDP preserves the original parameter variables and manipulates their data between unsharded and sharded forms, where they are always views into the underlying unsharded or sharded :class:`FlatParameter`, respectively. With the current algorithm, the sharded form is always 1D, losing the original tensor structure. An original parameter may have all, some, or none of its data present for a given rank. In the none case, its data will be like a size-0 empty tensor. Users should not author programs relying on what data is present for a given original parameter in its sharded form. ``True`` is required to use ``torch.compile()``. Setting this to ``False`` exposes FSDP's internal :class:`FlatParameter` s to the user via :meth:`nn.Module.named_parameters`. (Default: ``False``) ignored_states (Optional[Iterable[torch.nn.Parameter]], Optional[Iterable[torch.nn.Module]]): Ignored parameters or modules that will not be managed by this FSDP instance, meaning that the parameters are not sharded and their gradients are not reduced across ranks. This argument unifies with the existing ``ignored_modules`` argument, and we may deprecate ``ignored_modules`` soon. For backward compatibility, we keep both ``ignored_states`` and `ignored_modules``, but FSDP only allows one of them to be specified as not ``None``. device_mesh (Optional[DeviceMesh]): DeviceMesh can be used as an alternative to process_group. When device_mesh is passed, FSDP will use the underlying process groups for all-gather and reduce-scatter collective communications. Therefore, these two args need to be mutually exclusive. For hybrid sharding strategies such as ``ShardingStrategy.HYBRID_SHARD``, users can pass in a 2D DeviceMesh instead of a tuple of process groups. For 2D FSDP + TP, users are required to pass in device_mesh instead of process_group. For more DeviceMesh info, please visit: https://pytorch.org/tutorials/recipes/distributed_device_mesh.html """ def __init__( self, module: nn.Module, process_group: ProcessGroupType = None, sharding_strategy: Optional[ShardingStrategy] = None, cpu_offload: Optional[CPUOffload] = None, auto_wrap_policy: Optional[ Union[Callable, ModuleWrapPolicy, CustomPolicy] ] = None, backward_prefetch: Optional[BackwardPrefetch] = BackwardPrefetch.BACKWARD_PRE, mixed_precision: Optional[MixedPrecision] = None, ignored_modules: Optional[Iterable[torch.nn.Module]] = None, param_init_fn: Optional[Callable[[nn.Module], None]] = None, device_id: Optional[Union[int, torch.device]] = None, sync_module_states: bool = False, forward_prefetch: bool = False, limit_all_gathers: bool = True, use_orig_params: bool = False, ignored_states: Union[ Optional[Iterable[torch.nn.Parameter]], Optional[Iterable[torch.nn.Module]] ] = None, device_mesh: Optional[DeviceMesh] = None, ): torch._C._log_api_usage_once("torch.distributed.fsdp") super().__init__() if isinstance(module, (nn.ModuleList, nn.ModuleDict)): warnings.warn( "FSDP will not all-gather parameters for containers that do " f"not implement forward: {module}", stacklevel=2, ) _init_ignored_module_states(self, module, ignored_modules, ignored_states) _init_device_handle(self, module, self._ignored_params, device_id) # Add module annotations for Dynamo support (see function for details) _annotate_modules_for_dynamo(module, self._ignored_modules, use_orig_params) # Initializes self.process_group, along with rank and world size. This will # also set another attribute, _inter_node_pg, to control the process group # over which sharding occurs, if sharding_strategy is {HYBRID_SHARD, _HYBRID_SHARD_ZERO2}. # Note that this is done before auto_wrapping, so that child FSDP modules simply pick up # the same process group state as the root FSDP module. self._device_mesh = device_mesh _init_process_group_state( self, process_group, sharding_strategy, auto_wrap_policy, device_mesh, ) if auto_wrap_policy is not None: root_kwargs = { "process_group": process_group, "sharding_strategy": sharding_strategy, "cpu_offload": cpu_offload, "backward_prefetch": backward_prefetch, "mixed_precision": mixed_precision, "param_init_fn": param_init_fn, "device_id": device_id, "sync_module_states": sync_module_states, "forward_prefetch": forward_prefetch, "limit_all_gathers": limit_all_gathers, "use_orig_params": use_orig_params, "ignored_states": self._ignored_params, "device_mesh": device_mesh, } if sharding_strategy in HYBRID_SHARDING_STRATEGIES and device_mesh is None: # Share root process groups with children to maintain # the invariant that all FSDP modules will have the same # process groups. root_kwargs["process_group"] = (self.process_group, self._inter_node_pg) _auto_wrap( module, auto_wrap_policy, self._ignored_modules, self._ignored_params, root_kwargs, FullyShardedDataParallel, ) backward_prefetch_limit = 1 forward_prefetch_limit = 1 _init_core_state( self, sharding_strategy, mixed_precision, cpu_offload, limit_all_gathers, use_orig_params, backward_prefetch_limit, forward_prefetch_limit, ) _init_runtime_state(self) _init_prefetching_state(self, backward_prefetch, forward_prefetch) _init_buffer_state(self, module) # extension needs to be set before `_init_param_handle_from_module()` _init_extension(self, device_mesh) _init_param_handle_from_module( self, module, device_id, param_init_fn, sync_module_states, ) self._fsdp_wrapped_module = module if not use_orig_params: _check_orig_params_flattened(self, self._ignored_params) _register_flat_param(self, self) # `_state_dict_type` controls the `state_dict()` behavior, which is # implemented using post-save and pre-load hooks _init_state_dict_state(self) _register_all_state_dict_hooks(self) self._zero_scalar = None @property def module(self) -> nn.Module: """Return the wrapped module.""" # FSDP's `.module` must refer to the innermost wrapped module when # composing with other module wrappers in order for state dict to work if isinstance(self._fsdp_wrapped_module, ActivationWrapper): return getattr(self._fsdp_wrapped_module, _CHECKPOINT_WRAPPED_MODULE) return self._fsdp_wrapped_module @property def _has_params(self) -> bool: """Returns whether this FSDP instance manages any parameters.""" return hasattr(self, "_handle") and self._handle is not None @property def _flat_param(self) -> Optional[FlatParameter]: return self._handle.flat_param if self._handle else None def __getattr__(self, name: str) -> Any: """Forward missing attributes to the wrapped module.""" try: return super().__getattr__(name) # defer to nn.Module's logic except AttributeError: return getattr(self._fsdp_wrapped_module, name) def __getitem__(self, key: int) -> Any: """Forward indexing calls in case the module is an ``nn.Sequential``.""" if hasattr(self, FSDP_WRAPPED_MODULE): return self._fsdp_wrapped_module.__getitem__(key) # type: ignore[operator] return super().__getitem__(key) def check_is_root(self) -> bool: """Check if this instance is a root FSDP module.""" return _is_fsdp_root(self, self) @staticmethod def fsdp_modules( module: nn.Module, root_only: bool = False, ) -> list["FullyShardedDataParallel"]: """Return all nested FSDP instances. This possibly includes ``module`` itself and only includes FSDP root modules if ``root_only=True``. Args: module (torch.nn.Module): Root module, which may or may not be an ``FSDP`` module. root_only (bool): Whether to return only FSDP root modules. (Default: ``False``) Returns: List[FullyShardedDataParallel]: FSDP modules that are nested in the input ``module``. """ if root_only: return _get_fsdp_root_states(module) return traversal_utils._get_fsdp_states(module) def apply(self, fn: Callable[[nn.Module], None]) -> "FullyShardedDataParallel": r"""Apply ``fn`` recursively to every submodule (as returned by ``.children()``) as well as self. Typical use includes initializing the parameters of a model (see also :ref:`nn-init-doc`). Compared to ``torch.nn.Module.apply``, this version additionally gathers the full parameters before applying ``fn``. It should not be called from within another ``summon_full_params`` context. Args: fn (:class:`Module` -> None): function to be applied to each submodule Returns: Module: self """ uninitialized = self._is_root is None self._assert_state(TrainingState.IDLE) # Use `_unshard_params_for_summon()` with `recurse=False` instead of # `_unshard_fsdp_state_params()` directly to perform lazy # initialization, which is needed to initialize `FlatParameter` # parameter attributes as required by the unshard logic with _unshard_params_for_summon( self, self, writeback=True, rank0_only=False, offload_to_cpu=False, with_grads=False, ): ret = super().apply(fn) # Reset lazy init called in `_unshard_params_for_summon()` since # `apply()` may have been called on FSDP instance that is not truly a # root, in which case it will be incorrectly marked as one. if uninitialized and self._is_root: for module in traversal_utils._get_fsdp_states(self): module._reset_lazy_init() return ret def _mixed_precision_enabled_for_buffers(self) -> bool: """Return whether the user explicitly enabled buffer mixed precision. NOTE: Unlike parameters and gradient reduction, buffer mixed precision is applied at the FSDP instance level, not the ``FlatParameter`` level, which may be different for the composable code path. """ return self.mixed_precision.buffer_dtype is not None def _low_precision_hook_enabled(self) -> bool: """Whether a low precision hook is registered or not.""" return self._comm_hook is not None and self._comm_hook in LOW_PRECISION_HOOKS def _reset_lazy_init(self) -> None: """Reset instance so :func:`_lazy_init` will run on the next forward.""" self._is_root: Optional[bool] = None @staticmethod def set_state_dict_type( module: nn.Module, state_dict_type: StateDictType, state_dict_config: Optional[StateDictConfig] = None, optim_state_dict_config: Optional[OptimStateDictConfig] = None, ) -> StateDictSettings: """Set the ``state_dict_type`` of all the descendant FSDP modules of the target module. Also takes (optional) configuration for the model's and optimizer's state dict. The target module does not have to be a FSDP module. If the target module is a FSDP module, its ``state_dict_type`` will also be changed. .. note:: This API should be called for only the top-level (root) module. .. note:: This API enables users to transparently use the conventional ``state_dict`` API to take model checkpoints in cases where the root FSDP module is wrapped by another ``nn.Module``. For example, the following will ensure ``state_dict`` is called on all non-FSDP instances, while dispatching into `sharded_state_dict` implementation for FSDP: Example:: >>> # xdoctest: +SKIP("undefined variables") >>> model = DDP(FSDP(...)) >>> FSDP.set_state_dict_type( >>> model, >>> StateDictType.SHARDED_STATE_DICT, >>> state_dict_config = ShardedStateDictConfig(offload_to_cpu=True), >>> optim_state_dict_config = OptimStateDictConfig(offload_to_cpu=True), >>> ) >>> param_state_dict = model.state_dict() >>> optim_state_dict = FSDP.optim_state_dict(model, optim) Args: module (torch.nn.Module): Root module. state_dict_type (StateDictType): the desired ``state_dict_type`` to set. state_dict_config (Optional[StateDictConfig]): the configuration for the target ``state_dict_type``. optim_state_dict_config (Optional[OptimStateDictConfig]): the configuration for the optimizer state dict. Returns: A StateDictSettings that include the previous state_dict type and configuration for the module. """ warnings.warn( "FSDP.state_dict_type() and FSDP.set_state_dict_type() are being " "deprecated. Please use APIs, get_state_dict() and set_state_dict(), " "which can support different parallelisms, FSDP1, FSDP2, DDP. " "API doc: https://pytorch.org/docs/stable/distributed.checkpoint.html" "#torch.distributed.checkpoint.state_dict.get_state_dict ." "Tutorial: https://pytorch.org/tutorials/recipes/distributed_checkpoint_recipe.html .", FutureWarning, stacklevel=2, ) _state_dict_type_to_config = { StateDictType.FULL_STATE_DICT: FullStateDictConfig, StateDictType.LOCAL_STATE_DICT: LocalStateDictConfig, StateDictType.SHARDED_STATE_DICT: ShardedStateDictConfig, } _optim_state_dict_type_to_config = { StateDictType.FULL_STATE_DICT: FullOptimStateDictConfig, StateDictType.LOCAL_STATE_DICT: LocalOptimStateDictConfig, StateDictType.SHARDED_STATE_DICT: ShardedOptimStateDictConfig, } # Use the default config if a state_dict config is not set. state_dict_config_type = _state_dict_type_to_config[state_dict_type] optim_state_dict_config_type = _optim_state_dict_type_to_config[state_dict_type] if state_dict_config is None: state_dict_config = state_dict_config_type() if optim_state_dict_config is None: optim_state_dict_config = optim_state_dict_config_type() if state_dict_config_type is not type(state_dict_config): raise RuntimeError( f"Expected state_dict_config of type {state_dict_config_type} " f"but got {type(state_dict_config)}" ) if optim_state_dict_config_type is not type(optim_state_dict_config): raise RuntimeError( f"Expected optim_state_dict_config of type {optim_state_dict_config_type} " f"but got {type(optim_state_dict_config)}" ) # Set the state_dict type and configurations. prev_state_dict_type = None prev_state_dict_config = None prev_optim_state_dict_config = None for submodule in traversal_utils._get_fsdp_states(module): if prev_state_dict_type is None: prev_state_dict_type = submodule._state_dict_type else: if prev_state_dict_type != submodule._state_dict_type: raise AssertionError( "All FSDP modules should have the same state_dict_type." ) if prev_state_dict_config is None: prev_state_dict_config = submodule._state_dict_config else: if not isinstance( submodule._state_dict_config, type(prev_state_dict_config) ): raise AssertionError( "All FSDP modules must have the same type of state_dict_config." ) if prev_optim_state_dict_config is None: prev_optim_state_dict_config = submodule._optim_state_dict_config else: if not isinstance( submodule._optim_state_dict_config, type(prev_optim_state_dict_config), ): raise AssertionError( "All FSDP modules must have the same type of optim_state_dict_config." ) submodule._state_dict_type = state_dict_type submodule._state_dict_config = state_dict_config submodule._optim_state_dict_config = optim_state_dict_config return StateDictSettings( prev_state_dict_type, prev_state_dict_config, prev_optim_state_dict_config ) @staticmethod def get_state_dict_type(module: nn.Module) -> StateDictSettings: """Get the state_dict_type and the corresponding configurations for the FSDP modules rooted at ``module``. The target module does not have to be an FSDP module. Returns: A ``StateDictSettings`` containing the state_dict_type and state_dict / optim_state_dict configs that are currently set. Raises: ``AssertionError`` if the ``StateDictSettings`` for different FSDP submodules differ. """ state_dict_settings: Optional[StateDictSettings] = None for submodule in FullyShardedDataParallel.fsdp_modules(module): if state_dict_settings is None: state_dict_settings = StateDictSettings( state_dict_type=submodule._state_dict_type, state_dict_config=submodule._state_dict_config, optim_state_dict_config=submodule._optim_state_dict_config, ) _set_optim_use_dtensor(submodule, state_dict_settings) else: submodule_settings = StateDictSettings( submodule._state_dict_type, submodule._state_dict_config, submodule._optim_state_dict_config, ) if state_dict_settings != submodule_settings: raise AssertionError( "All FSDP modules must have the same state dict settings." f"Got {submodule_settings} and {state_dict_settings}." ) _set_optim_use_dtensor(submodule, submodule_settings) return state_dict_settings @staticmethod @contextlib.contextmanager def state_dict_type( module: nn.Module, state_dict_type: StateDictType, state_dict_config: Optional[StateDictConfig] = None, optim_state_dict_config: Optional[OptimStateDictConfig] = None, ) -> Generator: """Set the ``state_dict_type`` of all the descendant FSDP modules of the target module. This context manager has the same functions as :meth:`set_state_dict_type`. Read the document of :meth:`set_state_dict_type` for the detail. Example:: >>> # xdoctest: +SKIP("undefined variables") >>> model = DDP(FSDP(...)) >>> with FSDP.state_dict_type( >>> model, >>> StateDictType.SHARDED_STATE_DICT, >>> ): >>> checkpoint = model.state_dict() Args: module (torch.nn.Module): Root module. state_dict_type (StateDictType): the desired ``state_dict_type`` to set. state_dict_config (Optional[StateDictConfig]): the model ``state_dict`` configuration for the target ``state_dict_type``. optim_state_dict_config (Optional[OptimStateDictConfig]): the optimizer ``state_dict`` configuration for the target ``state_dict_type``. """ prev_state_dict_settings = FullyShardedDataParallel.set_state_dict_type( module, state_dict_type, state_dict_config, optim_state_dict_config, ) yield FullyShardedDataParallel.set_state_dict_type( module, prev_state_dict_settings.state_dict_type, prev_state_dict_settings.state_dict_config, prev_state_dict_settings.optim_state_dict_config, ) def forward(self, *args: Any, **kwargs: Any) -> Any: """Run the forward pass for the wrapped module, inserting FSDP-specific pre- and post-forward sharding logic.""" handle = self._handle with torch.autograd.profiler.record_function( "FullyShardedDataParallel.forward" ): args, kwargs = _root_pre_forward(self, self, args, kwargs) unused = None args, kwargs = _pre_forward( self, handle, _pre_forward_unshard, self._fsdp_wrapped_module, args, kwargs, ) if handle: _p_assert( handle.flat_param.device == self.compute_device, "Expected `FlatParameter` to be on the compute device " f"{self.compute_device} but got {handle.flat_param.device}", ) output = self._fsdp_wrapped_module(*args, **kwargs) return _post_forward( self, handle, _post_forward_reshard, self, unused, output ) @staticmethod @contextlib.contextmanager def summon_full_params( module: nn.Module, recurse: bool = True, writeback: bool = True, rank0_only: bool = False, offload_to_cpu: bool = False, with_grads: bool = False, ) -> Generator: r"""Expose full params for FSDP instances with this context manager. Can be useful *after* forward/backward for a model to get the params for additional processing or checking. It can take a non-FSDP module and will summon full params for all contained FSDP modules as well as their children, depending on the ``recurse`` argument. .. note:: This can be used on inner FSDPs. .. note:: This can *not* be used within a forward or backward pass. Nor can forward and backward be started from within this context. .. note:: Parameters will revert to their local shards after the context manager exits, storage behavior is the same as forward. .. note:: The full parameters can be modified, but only the portion corresponding to the local param shard will persist after the context manager exits (unless ``writeback=False``, in which case changes will be discarded). In the case where FSDP does not shard the parameters, currently only when ``world_size == 1``, or ``NO_SHARD`` config, the modification is persisted regardless of ``writeback``. .. note:: This method works on modules which are not FSDP themselves but may contain multiple independent FSDP units. In that case, the given arguments will apply to all contained FSDP units. .. warning:: Note that ``rank0_only=True`` in conjunction with ``writeback=True`` is not currently supported and will raise an error. This is because model parameter shapes would be different across ranks within the context, and writing to them can lead to inconsistency across ranks when the context is exited. .. warning:: Note that ``offload_to_cpu`` and ``rank0_only=False`` will result in full parameters being redundantly copied to CPU memory for GPUs that reside on the same machine, which may incur the risk of CPU OOM. It is recommended to use ``offload_to_cpu`` with ``rank0_only=True``. Args: recurse (bool, Optional): recursively summon all params for nested FSDP instances (default: True). writeback (bool, Optional): if ``False``, modifications to params are discarded after the context manager exits; disabling this can be slightly more efficient (default: True) rank0_only (bool, Optional): if ``True``, full parameters are materialized on only global rank 0. This means that within the context, only rank 0 will have full parameters and the other ranks will have sharded parameters. Note that setting ``rank0_only=True`` with ``writeback=True`` is not supported, as model parameter shapes will be different across ranks within the context, and writing to them can lead to inconsistency across ranks when the context is exited. offload_to_cpu (bool, Optional): If ``True``, full parameters are offloaded to CPU. Note that this offloading currently only occurs if the parameter is sharded (which is only not the case for world_size = 1 or ``NO_SHARD`` config). It is recommended to use ``offload_to_cpu`` with ``rank0_only=True`` to avoid redundant copies of model parameters being offloaded to the same CPU memory. with_grads (bool, Optional): If ``True``, gradients are also unsharded with the parameters. Currently, this is only supported when passing ``use_orig_params=True`` to the FSDP constructor and ``offload_to_cpu=False`` to this method. (Default: ``False``) """ with _unshard_params( module, recurse, writeback, rank0_only, offload_to_cpu, with_grads ): yield @contextlib.contextmanager def _deregister_orig_params_ctx(self): """Deregister the original parameters and expose the :class:`FlatParameter`. If a :class:`FlatParameter` is sharded, then this refreshes the sharded views before exiting. This method should only be called when using the original parameters. """ _p_assert( self._use_orig_params, "`_deregister_orig_params_ctx()` should only be called when " "`_use_orig_params=True`", ) for fsdp_module in traversal_utils._get_fsdp_states(self): _deregister_orig_params(fsdp_module, fsdp_module) try: yield finally: for fsdp_module in traversal_utils._get_fsdp_states(self): _register_orig_params(fsdp_module, fsdp_module) def _apply(self, *args, **kwargs): """Deregister the original parameters and expose the :class:`FlatParameter` s before calling ``_apply()``.""" # When using the original parameters: Since (1) the `FlatParameter`s # own the storage and (2) `_apply()` is the subroutine underlying the # most common storage-changing ops like `to()` and `cuda()`, we # override `_apply()` to have the storage change directly performed on # the `FlatParameter`s instead of applying to the original parameters # and then writing back to the `FlatParameter`s. context = ( self._deregister_orig_params_ctx() if self._use_orig_params else contextlib.nullcontext() ) with context: return super()._apply(*args, **kwargs) def named_buffers( self, *args, **kwargs, ) -> Iterator[tuple[str, torch.Tensor]]: """Return an iterator over module buffers, yielding both the name of the buffer and the buffer itself. Intercepts buffer names and removes all occurrences of the FSDP-specific flattened buffer prefix when inside the :meth:`summon_full_params` context manager. """ should_clean_name = self.training_state == TrainingState.SUMMON_FULL_PARAMS for buffer_name, buffer in super().named_buffers(*args, **kwargs): if should_clean_name: # Remove any instances of the FSDP-specific prefix; there can # be multiple in the case of nested FSDP modules buffer_name = buffer_name.replace(FSDP_PREFIX, "") yield (buffer_name, buffer) def named_parameters( self, *args, **kwargs, ) -> Iterator[tuple[str, torch.nn.Parameter]]: """Return an iterator over module parameters, yielding both the name of the parameter and the parameter itself. Intercepts parameter names and removes all occurrences of the FSDP-specific flattened parameter prefix when inside the :meth:`summon_full_params` context manager. """ should_clean_name = self.training_state == TrainingState.SUMMON_FULL_PARAMS for param_name, param in super().named_parameters(*args, **kwargs): if should_clean_name: # Remove any instances of the FSDP-specific prefix; there can # be multiple in the case of nested FSDP modules param_name = param_name.replace(FSDP_PREFIX, "") yield (param_name, param) def _assert_state(self, state: Union[TrainingState, list[TrainingState]]) -> None: """Assert we are in the given state.""" # Since assert can be turned off and this error checking # is really important, we use explicit error checking # and raise a ValueError if needed. if isinstance(state, TrainingState): state = [state] if self.training_state not in state: msg = ( f"expected to be in states {state} but current state " f"is {self.training_state}" ) # In case we are failing in the context of autograd hook, asserting # may not generate useful msg. So, let's print it to be sure. if self.rank == 0: print(f"Asserting FSDP instance is: {self}") print(f"ERROR: {msg}") traceback.print_stack() raise ValueError(msg) @contextmanager def no_sync(self) -> Generator: """Disable gradient synchronizations across FSDP instances. Within this context, gradients will be accumulated in module variables, which will later be synchronized in the first forward-backward pass after exiting the context. This should only be used on the root FSDP instance and will recursively apply to all children FSDP instances. .. note:: This likely results in higher memory usage because FSDP will accumulate the full model gradients (instead of gradient shards) until the eventual sync. .. note:: When used with CPU offloading, the gradients will not be offloaded to CPU when inside the context manager. Instead, they will only be offloaded right after the eventual sync. """ _lazy_init(self, self) if not self._is_root: raise RuntimeError( "`no_sync()` on inner FSDP instances is not supported. Please call `no_sync()` on root FSDP module." ) self._assert_state(TrainingState.IDLE) old_flags = [] for m in self.modules(): if isinstance(m, FullyShardedDataParallel): old_flags.append((m, m._sync_gradients)) m._sync_gradients = False try: yield finally: for m, old_flag in old_flags: if m._sync_gradients: raise AssertionError( "`_sync_gradients` was incorrectly set to " "`True` while in the `no_sync()` context manager" ) m._sync_gradients = old_flag @torch.no_grad() def clip_grad_norm_( self, max_norm: Union[float, int], norm_type: Union[float, int] = 2.0 ) -> torch.Tensor: """Clip the gradient norm of all parameters. The norm is computed over all parameters' gradients as viewed as a single vector, and the gradients are modified in-place. Args: max_norm (float or int): max norm of the gradients norm_type (float or int): type of the used p-norm. Can be ``'inf'`` for infinity norm. Returns: Total norm of the parameters (viewed as a single vector). If every FSDP instance uses ``NO_SHARD``, meaning that no gradients are sharded across ranks, then you may directly use :func:`torch.nn.utils.clip_grad_norm_`. If at least some FSDP instance uses a sharded strategy (i.e. one other than ``NO_SHARD``), then you should use this method instead of :func:`torch.nn.utils.clip_grad_norm_` since this method handles the fact that gradients are sharded across ranks. The total norm returned will have the "largest" dtype across all parameters/gradients as defined by PyTorch's type promotion semantics. For example, if *all* parameters/gradients use a low precision dtype, then the returned norm's dtype will be that low precision dtype, but if there exists at least one parameter/ gradient using FP32, then the returned norm's dtype will be FP32. .. warning:: This needs to be called on all ranks since it uses collective communications. """ _lazy_init(self, self) if not self._is_root: raise RuntimeError( "`clip_grad_norm_()` should only be called on the root FSDP instance" ) if self._zero_scalar is None: self._zero_scalar = torch.tensor(0.0, device=self.compute_device) self._assert_state(TrainingState.IDLE) # If every FSDP instance uses `NO_SHARD`, then we can directly use # the normal `nn.utils` one targeting local gradients all_no_shard = all( not handle.uses_sharded_strategy for handle in self._all_handles ) if all_no_shard: return torch.nn.utils.clip_grad_norm_( self.parameters(), max_norm, norm_type ) # Otherwise, there exists some FSDP instance using a sharded strategy, # where sharded and non-sharded parameters must be handled separately max_norm = float(max_norm) norm_type = float(norm_type) sharded_params_set = set() nonsharded_params_set = set() # `NO_SHARD` or not FSDP-managed # Make sure to compute the local norm using lists for deterministic # iteration order and hence deterministic total norm computation sharded_params = [] nonsharded_params = [] grads: list[torch.Tensor] = [] for handle in self._all_handles: if handle.uses_sharded_strategy: target_set = sharded_params_set target_list = sharded_params else: target_set = nonsharded_params_set target_list = nonsharded_params if handle._use_orig_params: for param in handle.flat_param._params: if param not in target_set: target_set.add(param) target_list.append(param) if param.grad is not None: grads.append(param.grad) else: if handle.flat_param not in target_set: target_set.add(handle.flat_param) target_list.append(handle.flat_param) if handle.flat_param.grad is not None: grads.append(handle.flat_param.grad) for param in self.parameters(): not_fsdp_managed = ( param not in sharded_params_set and param not in nonsharded_params_set ) if not_fsdp_managed: nonsharded_params_set.add(param) nonsharded_params.append(param) if param.grad is not None: grads.append(param.grad) # Compute local norms (forced to be in FP32) local_sharded_norm = _get_grad_norm( sharded_params, norm_type, self._zero_scalar, self.compute_device ) local_nonsharded_norm = ( _get_grad_norm( nonsharded_params, norm_type, self._zero_scalar, self.compute_device ) if nonsharded_params else None ) # Reconstruct the total gradient norm depending on the norm type if norm_type == math.inf: total_norm = ( torch.maximum(local_sharded_norm, local_nonsharded_norm) if local_nonsharded_norm is not None else local_sharded_norm ) dist.all_reduce( total_norm, op=torch.distributed.ReduceOp.MAX, group=self.process_group ) else: total_norm = local_sharded_norm**norm_type dist.all_reduce(total_norm, group=self.process_group) # All-reducing the local non-sharded norm would count it an extra # world-size-many times if local_nonsharded_norm is not None: total_norm += local_nonsharded_norm**norm_type total_norm = total_norm ** (1.0 / norm_type) if self.cpu_offload.offload_params: total_norm = total_norm.cpu() clip_coef = max_norm / (total_norm + 1e-6) # Multiplying by the clamped coefficient is meaningless when it is # equal to 1, but it avoids the host-device sync that would result from # `if clip_coef < 1` clip_coef_clamped = torch.clamp(clip_coef, max=1.0) for grad in grads: grad.mul_(clip_coef_clamped.to(grad.device, grad.dtype)) # Use the "largest" dtype by type promotion semantics to use the same # dtype as if we did not force local norm computation to be in FP32 if len(grads) == 0: # If this rank has no gradients, then we must default to FP32 # unless we use additional communication, which we prefer to avoid # since `clip_grad_norm_()` is called in the training loop warnings.warn( f"Called FSDP.clip_grad_norm_() on rank {self.rank} with no " "gradients -- returning the total norm in the default dtype " f"{total_norm.dtype}", stacklevel=2, ) # warn since this is generally unexpected return total_norm total_norm_dtype = functools.reduce( torch.promote_types, [grad.dtype for grad in grads], ) return total_norm.to(total_norm_dtype) @staticmethod def _warn_optim_input(optim_input, *, stacklevel: int = 1): if optim_input is not None: warnings.warn( "The `optim_input` argument is deprecated and will be removed after PyTorch 1.13. " "You may remove it from your code without changing its functionality.", FutureWarning, stacklevel=stacklevel + 1, ) @staticmethod def _is_using_optim_input(optim_input, optim) -> bool: if optim_input is None and optim is None: # Use the default behavior of `optim_input`` return True if optim_input is not None: # Use the `optim_input` code path return True # Use the `optim` code path return False @staticmethod def _warn_legacy_optim_state_dict(curr: str, new: str, *, stacklevel: int = 1): warnings.warn( f"``FullyShardedDataParallel.{curr}``is being deprecated and is " f"replaced by ``FullyShardedDataParallel.{new}``. " f"``FullyShardedDataParallel.{curr}`` may be removed after PyTorch 2.2.", FutureWarning, stacklevel=stacklevel + 1, ) @staticmethod def _optim_state_dict_impl( model: torch.nn.Module, optim: torch.optim.Optimizer, optim_state_dict: dict[str, Any], optim_input: Optional[ Union[ list[dict[str, Any]], Iterable[torch.nn.Parameter], ] ] = None, rank0_only: bool = True, full_state_dict: bool = True, group: Optional[dist.ProcessGroup] = None, cpu_offload: bool = True, *, _stacklevel: int = 1, ) -> dict[str, Any]: """Transform the state-dict of an optimizer corresponding to a sharded model. This is the internal API that is used by all the optim_state_dict implementations. Given model, optim, the original optim_state_dict, this API removes the FSDP internal information and internal sharding from the optim_state_dict. """ if full_state_dict: FullyShardedDataParallel._warn_optim_input( optim_input, stacklevel=_stacklevel + 1 ) using_optim_input = FullyShardedDataParallel._is_using_optim_input( optim_input, optim, ) else: using_optim_input = False if optim_input is not None or rank0_only: raise AssertionError( f"Expected optim_input to be None and rank0_only to be False, " f"got optim_input={optim_input}, rank0_only={rank0_only}" ) use_orig_params = FullyShardedDataParallel.fsdp_modules(model)[ 0 ]._use_orig_params if not all( use_orig_params == m._use_orig_params for m in FullyShardedDataParallel.fsdp_modules(model) ): raise AssertionError( "Not all FSDP modules have the same _use_orig_params value" ) return _optim_state_dict( model=model, optim=optim, optim_state_dict=optim_state_dict, optim_input=optim_input, rank0_only=rank0_only, shard_state=not full_state_dict, group=group, using_optim_input=using_optim_input, use_orig_params=use_orig_params, cpu_offload=cpu_offload, ) @staticmethod def _optim_state_dict_to_load_impl( optim_state_dict: dict[str, Any], model: torch.nn.Module, optim_input: Optional[ Union[ list[dict[str, Any]], Iterable[torch.nn.Parameter], ] ] = None, optim: Optional[torch.optim.Optimizer] = None, full_state_dict: bool = True, rank0_only: bool = False, is_named_optimizer: bool = False, group: Optional[dist.ProcessGroup] = None, ) -> dict[str, Any]: """ Convert an optimizer state-dict so that it can be loaded into the optimizer associated with the FSDP model. This is the internal API that is used by all the load optim_state_dict implementations. Given model, optim, and the saved optim_state_dict, this API adds the FSDP internal information and internal sharding to the optim_state_dict. """ if full_state_dict: FullyShardedDataParallel._warn_optim_input(optim_input) using_optim_input = FullyShardedDataParallel._is_using_optim_input( optim_input, optim, ) else: using_optim_input = False if optim_input is not None or rank0_only: raise AssertionError( f"Expected optim_input to be None and rank0_only to be False, " f"got optim_input={optim_input}, rank0_only={rank0_only}" ) use_orig_params = FullyShardedDataParallel.fsdp_modules(model)[ 0 ]._use_orig_params if not all( use_orig_params == m._use_orig_params for m in FullyShardedDataParallel.fsdp_modules(model) ): raise AssertionError( "Not all FSDP modules have the same _use_orig_params value" ) if rank0_only and dist.get_rank(group) > 0: optim_state_dict = {} sharded_osd = _flatten_optim_state_dict( optim_state_dict, model=model, use_orig_params=use_orig_params, optim=(optim if is_named_optimizer else None), rank0_only=rank0_only, group=group, ) return _rekey_sharded_optim_state_dict( sharded_osd, model=model, optim=optim, optim_input=optim_input, using_optim_input=using_optim_input, is_named_optimizer=is_named_optimizer, ) @staticmethod def full_optim_state_dict( model: torch.nn.Module, optim: torch.optim.Optimizer, optim_input: Optional[ Union[ list[dict[str, Any]], Iterable[torch.nn.Parameter], ] ] = None, rank0_only: bool = True, group: Optional[dist.ProcessGroup] = None, ) -> dict[str, Any]: """Return the full optimizer state-dict. Consolidates the full optimizer state on rank 0 and returns it as a :class:`dict` following the convention of :meth:`torch.optim.Optimizer.state_dict`, i.e. with keys ``"state"`` and ``"param_groups"``. The flattened parameters in ``FSDP`` modules contained in ``model`` are mapped back to their unflattened parameters. This needs to be called on all ranks since it uses collective communications. However, if ``rank0_only=True``, then the state dict is only populated on rank 0, and all other ranks return an empty :class:`dict`. Unlike ``torch.optim.Optimizer.state_dict()``, this method uses full parameter names as keys instead of parameter IDs. Like in :meth:`torch.optim.Optimizer.state_dict`, the tensors contained in the optimizer state dict are not cloned, so there may be aliasing surprises. For best practices, consider saving the returned optimizer state dict immediately, e.g. using ``torch.save()``. Args: model (torch.nn.Module): Root module (which may or may not be a :class:`FullyShardedDataParallel` instance) whose parameters were passed into the optimizer ``optim``. optim (torch.optim.Optimizer): Optimizer for ``model`` 's parameters. optim_input (Optional[Union[List[Dict[str, Any]], Iterable[torch.nn.Parameter]]]): Input passed into the optimizer ``optim`` representing either a :class:`list` of parameter groups or an iterable of parameters; if ``None``, then this method assumes the input was ``model.parameters()``. This argument is deprecated, and there is no need to pass it in anymore. (Default: ``None``) rank0_only (bool): If ``True``, saves the populated :class:`dict` only on rank 0; if ``False``, saves it on all ranks. (Default: ``True``) group (dist.ProcessGroup): Model's process group or ``None`` if using the default process group. (Default: ``None``) Returns: Dict[str, Any]: A :class:`dict` containing the optimizer state for ``model`` 's original unflattened parameters and including keys "state" and "param_groups" following the convention of :meth:`torch.optim.Optimizer.state_dict`. If ``rank0_only=True``, then nonzero ranks return an empty :class:`dict`. """ FullyShardedDataParallel._warn_legacy_optim_state_dict( "full_optim_state_dict", "optim_state_dict", stacklevel=2, ) return FullyShardedDataParallel._optim_state_dict_impl( model=model, optim=optim, optim_state_dict=optim.state_dict(), optim_input=optim_input, rank0_only=rank0_only, group=group, full_state_dict=True, _stacklevel=2, ) @staticmethod def sharded_optim_state_dict( model: torch.nn.Module, optim: torch.optim.Optimizer, group: Optional[dist.ProcessGroup] = None, ) -> dict[str, Any]: """Return the optimizer state-dict in its sharded form. The API is similar to :meth:`full_optim_state_dict` but this API chunks all non-zero-dimension states to :class:`ShardedTensor` to save memory. This API should only be used when the model ``state_dict`` is derived with the context manager ``with state_dict_type(SHARDED_STATE_DICT):``. For the detailed usage, refer to :meth:`full_optim_state_dict`. .. warning:: The returned state dict contains ``ShardedTensor`` and cannot be directly used by the regular ``optim.load_state_dict``. """ FullyShardedDataParallel._warn_legacy_optim_state_dict( "sharded_optim_state_dict", "optim_state_dict", stacklevel=2, ) return FullyShardedDataParallel._optim_state_dict_impl( model=model, optim=optim, optim_state_dict=optim.state_dict(), optim_input=None, rank0_only=False, full_state_dict=False, group=group, _stacklevel=2, ) @staticmethod def shard_full_optim_state_dict( full_optim_state_dict: dict[str, Any], model: torch.nn.Module, optim_input: Optional[ Union[ list[dict[str, Any]], Iterable[torch.nn.Parameter], ] ] = None, optim: Optional[torch.optim.Optimizer] = None, ) -> dict[str, Any]: """Shard a full optimizer state-dict. Remaps the state in ``full_optim_state_dict`` to flattened parameters instead of unflattened parameters and restricts to only this rank's part of the optimizer state. The first argument should be the return value of :meth:`full_optim_state_dict`. Example:: >>> # xdoctest: +SKIP("undefined variables") >>> from torch.distributed.fsdp import FullyShardedDataParallel as FSDP >>> model, optim = ... >>> full_osd = FSDP.full_optim_state_dict(model, optim) >>> torch.save(full_osd, PATH) >>> # Define new model with possibly different world size >>> new_model, new_optim = ... >>> full_osd = torch.load(PATH) >>> sharded_osd = FSDP.shard_full_optim_state_dict(full_osd, new_model) >>> new_optim.load_state_dict(sharded_osd) .. note:: Both :meth:`shard_full_optim_state_dict` and :meth:`scatter_full_optim_state_dict` may be used to get the sharded optimizer state dict to load. Assuming that the full optimizer state dict resides in CPU memory, the former requires each rank to have the full dict in CPU memory, where each rank individually shards the dict without any communication, while the latter requires only rank 0 to have the full dict in CPU memory, where rank 0 moves each shard to GPU memory (for NCCL) and communicates it to ranks appropriately. Hence, the former has higher aggregate CPU memory cost, while the latter has higher communication cost. Args: full_optim_state_dict (Dict[str, Any]): Optimizer state dict corresponding to the unflattened parameters and holding the full non-sharded optimizer state. model (torch.nn.Module): Root module (which may or may not be a :class:`FullyShardedDataParallel` instance) whose parameters correspond to the optimizer state in ``full_optim_state_dict``. optim_input (Optional[Union[List[Dict[str, Any]], Iterable[torch.nn.Parameter]]]): Input passed into the optimizer representing either a :class:`list` of parameter groups or an iterable of parameters; if ``None``, then this method assumes the input was ``model.parameters()``. This argument is deprecated, and there is no need to pass it in anymore. (Default: ``None``) optim (Optional[torch.optim.Optimizer]): Optimizer that will load the state dict returned by this method. This is the preferred argument to use over ``optim_input``. (Default: ``None``) Returns: Dict[str, Any]: The full optimizer state dict now remapped to flattened parameters instead of unflattened parameters and restricted to only include this rank's part of the optimizer state. """ FullyShardedDataParallel._warn_legacy_optim_state_dict( "shard_full_optim_state_dict", "optim_state_dict_to_load", stacklevel=2, ) return FullyShardedDataParallel._optim_state_dict_to_load_impl( optim_state_dict=full_optim_state_dict, model=model, optim_input=optim_input, optim=optim, full_state_dict=True, is_named_optimizer=False, ) @staticmethod def flatten_sharded_optim_state_dict( sharded_optim_state_dict: dict[str, Any], model: torch.nn.Module, optim: torch.optim.Optimizer, ) -> dict[str, Any]: """Flatten a sharded optimizer state-dict. The API is similar to :meth:`shard_full_optim_state_dict`. The only difference is that the input ``sharded_optim_state_dict`` should be returned from :meth:`sharded_optim_state_dict`. Therefore, there will be all-gather calls on each rank to gather ``ShardedTensor`` s. Args: sharded_optim_state_dict (Dict[str, Any]): Optimizer state dict corresponding to the unflattened parameters and holding the sharded optimizer state. model (torch.nn.Module): Refer to :meth:`shard_full_optim_state_dict`. optim (torch.optim.Optimizer): Optimizer for ``model`` 's parameters. Returns: Refer to :meth:`shard_full_optim_state_dict`. """ FullyShardedDataParallel._warn_legacy_optim_state_dict( "flatten_sharded_optim_state_dict", "optim_state_dict_to_load", stacklevel=2, ) return FullyShardedDataParallel._optim_state_dict_to_load_impl( optim_state_dict=sharded_optim_state_dict, model=model, optim_input=None, optim=optim, full_state_dict=False, is_named_optimizer=False, ) @staticmethod def scatter_full_optim_state_dict( full_optim_state_dict: Optional[dict[str, Any]], model: torch.nn.Module, optim_input: Optional[ Union[ list[dict[str, Any]], Iterable[torch.nn.Parameter], ] ] = None, optim: Optional[torch.optim.Optimizer] = None, group: Optional[Any] = None, ) -> dict[str, Any]: """Scatter the full optimizer state dict from rank 0 to all other ranks. Returns the sharded optimizer state dict on each rank. The return value is the same as :meth:`shard_full_optim_state_dict`, and on rank 0, the first argument should be the return value of :meth:`full_optim_state_dict`. Example:: >>> # xdoctest: +SKIP("undefined variables") >>> from torch.distributed.fsdp import FullyShardedDataParallel as FSDP >>> model, optim = ... >>> full_osd = FSDP.full_optim_state_dict(model, optim) # only non-empty on rank 0 >>> # Define new model with possibly different world size >>> new_model, new_optim, new_group = ... >>> sharded_osd = FSDP.scatter_full_optim_state_dict(full_osd, new_model, group=new_group) >>> new_optim.load_state_dict(sharded_osd) .. note:: Both :meth:`shard_full_optim_state_dict` and :meth:`scatter_full_optim_state_dict` may be used to get the sharded optimizer state dict to load. Assuming that the full optimizer state dict resides in CPU memory, the former requires each rank to have the full dict in CPU memory, where each rank individually shards the dict without any communication, while the latter requires only rank 0 to have the full dict in CPU memory, where rank 0 moves each shard to GPU memory (for NCCL) and communicates it to ranks appropriately. Hence, the former has higher aggregate CPU memory cost, while the latter has higher communication cost. Args: full_optim_state_dict (Optional[Dict[str, Any]]): Optimizer state dict corresponding to the unflattened parameters and holding the full non-sharded optimizer state if on rank 0; the argument is ignored on nonzero ranks. model (torch.nn.Module): Root module (which may or may not be a :class:`FullyShardedDataParallel` instance) whose parameters correspond to the optimizer state in ``full_optim_state_dict``. optim_input (Optional[Union[List[Dict[str, Any]], Iterable[torch.nn.Parameter]]]): Input passed into the optimizer representing either a :class:`list` of parameter groups or an iterable of parameters; if ``None``, then this method assumes the input was ``model.parameters()``. This argument is deprecated, and there is no need to pass it in anymore. (Default: ``None``) optim (Optional[torch.optim.Optimizer]): Optimizer that will load the state dict returned by this method. This is the preferred argument to use over ``optim_input``. (Default: ``None``) group (dist.ProcessGroup): Model's process group or ``None`` if using the default process group. (Default: ``None``) Returns: Dict[str, Any]: The full optimizer state dict now remapped to flattened parameters instead of unflattened parameters and restricted to only include this rank's part of the optimizer state. """ FullyShardedDataParallel._warn_legacy_optim_state_dict( "scatter_full_optim_state_dict", "optim_state_dict_to_load", stacklevel=2, ) return FullyShardedDataParallel._optim_state_dict_to_load_impl( optim_state_dict=full_optim_state_dict, model=model, optim_input=optim_input, optim=optim, full_state_dict=True, rank0_only=True, is_named_optimizer=False, group=group, ) @staticmethod def rekey_optim_state_dict( optim_state_dict: dict[str, Any], optim_state_key_type: OptimStateKeyType, model: torch.nn.Module, optim_input: Optional[ Union[ list[dict[str, Any]], Iterable[torch.nn.Parameter], ] ] = None, optim: Optional[torch.optim.Optimizer] = None, ) -> dict[str, Any]: """Re-keys the optimizer state dict ``optim_state_dict`` to use the key type ``optim_state_key_type``. This can be used to achieve compatibility between optimizer state dicts from models with FSDP instances and ones without. To re-key an FSDP full optimizer state dict (i.e. from :meth:`full_optim_state_dict`) to use parameter IDs and be loadable to a non-wrapped model:: >>> # xdoctest: +SKIP("undefined variables") >>> wrapped_model, wrapped_optim = ... >>> full_osd = FSDP.full_optim_state_dict(wrapped_model, wrapped_optim) >>> nonwrapped_model, nonwrapped_optim = ... >>> rekeyed_osd = FSDP.rekey_optim_state_dict(full_osd, OptimStateKeyType.PARAM_ID, nonwrapped_model) >>> nonwrapped_optim.load_state_dict(rekeyed_osd) To re-key a normal optimizer state dict from a non-wrapped model to be loadable to a wrapped model:: >>> # xdoctest: +SKIP("undefined variables") >>> nonwrapped_model, nonwrapped_optim = ... >>> osd = nonwrapped_optim.state_dict() >>> rekeyed_osd = FSDP.rekey_optim_state_dict(osd, OptimStateKeyType.PARAM_NAME, nonwrapped_model) >>> wrapped_model, wrapped_optim = ... >>> sharded_osd = FSDP.shard_full_optim_state_dict(rekeyed_osd, wrapped_model) >>> wrapped_optim.load_state_dict(sharded_osd) Returns: Dict[str, Any]: The optimizer state dict re-keyed using the parameter keys specified by ``optim_state_key_type``. """ FullyShardedDataParallel._warn_optim_input(optim_input) using_optim_input = FullyShardedDataParallel._is_using_optim_input( optim_input, optim, ) if optim_state_key_type not in ( OptimStateKeyType.PARAM_NAME, OptimStateKeyType.PARAM_ID, ): raise AssertionError( f"Expected optim_state_key_type to be PARAM_NAME or PARAM_ID, got {optim_state_key_type}" ) osd = optim_state_dict # alias # Validate that the existing parameter keys are uniformly typed uses_param_name_mask = [type(param_key) is str for param_key in osd["state"]] uses_param_id_mask = [type(param_key) is int for param_key in osd["state"]] if (any(uses_param_name_mask) and not all(uses_param_name_mask)) or ( any(uses_param_id_mask) and not all(uses_param_id_mask) ): error_msg = f"Invalid parameter keys: {osd['state'].keys()}" raise ValueError(error_msg) # Return directly if the existing key type matches the target key type if ( optim_state_key_type == OptimStateKeyType.PARAM_NAME and all(uses_param_name_mask) ) or ( optim_state_key_type == OptimStateKeyType.PARAM_ID and all(uses_param_id_mask) ): return osd # Otherwise, actually perform the re-keying new_osd = {} if optim_state_key_type == OptimStateKeyType.PARAM_NAME: # ID -> name param_id_to_param = ( _get_param_id_to_param_from_optim_input(model, optim_input) if using_optim_input else _get_param_key_to_param(optim) ) param_to_param_name = _get_param_to_fqn(model) param_id_to_param_name: list[str] = [ param_to_param_name[param] for param in param_id_to_param.values() ] new_osd["state"] = { param_id_to_param_name[param_id]: param_state for param_id, param_state in osd["state"].items() } new_osd["param_groups"] = copy.deepcopy(osd["param_groups"]) for param_group in new_osd["param_groups"]: param_group["params"] = sorted( [ param_id_to_param_name[param_id] for param_id in param_group["params"] ] ) return new_osd elif optim_state_key_type == OptimStateKeyType.PARAM_ID: # name -> ID param_name_to_param = _get_fqn_to_param(model) param_to_param_id = ( _get_param_to_param_id_from_optim_input(model, optim_input) if using_optim_input else _get_param_to_param_key(optim) ) # Because not all model parameters may be passed as the optimizer # input, we may need to drop some parameters from this mapping param_name_to_param_id = { param_name: param_to_param_id[param] for param_name, param in param_name_to_param.items() if param in param_to_param_id } new_osd["state"] = { param_name_to_param_id[param_name]: param_state for param_name, param_state in osd["state"].items() } new_osd["param_groups"] = copy.deepcopy(osd["param_groups"]) for param_group in new_osd["param_groups"]: param_group["params"] = sorted( [ param_name_to_param_id[param_name] for param_name in param_group["params"] ] ) return new_osd return new_osd # should never reach here @staticmethod def optim_state_dict( model: torch.nn.Module, optim: torch.optim.Optimizer, optim_state_dict: Optional[dict[str, Any]] = None, group: Optional[dist.ProcessGroup] = None, ) -> dict[str, Any]: """ Transform the state-dict of an optimizer corresponding to a sharded model. The given state-dict can be transformed to one of three types: 1) full optimizer state_dict, 2) sharded optimizer state_dict, 3) local optimizer state_dict. For full optimizer state_dict, all states are unflattened and not sharded. Rank0 only and CPU only can be specified via :meth:`state_dict_type` to avoid OOM. For sharded optimizer state_dict, all states are unflattened but sharded. CPU only can be specified via :meth:`state_dict_type` to further save memory. For local state_dict, no transformation will be performed. But a state will be converted from nn.Tensor to ShardedTensor to represent its sharding nature (this is not supported yet). Example:: >>> # xdoctest: +SKIP("undefined variables") >>> from torch.distributed.fsdp import FullyShardedDataParallel as FSDP >>> from torch.distributed.fsdp import StateDictType >>> from torch.distributed.fsdp import FullStateDictConfig >>> from torch.distributed.fsdp import FullOptimStateDictConfig >>> # Save a checkpoint >>> model, optim = ... >>> FSDP.set_state_dict_type( >>> model, >>> StateDictType.FULL_STATE_DICT, >>> FullStateDictConfig(rank0_only=False), >>> FullOptimStateDictConfig(rank0_only=False), >>> ) >>> state_dict = model.state_dict() >>> optim_state_dict = FSDP.optim_state_dict(model, optim) >>> save_a_checkpoint(state_dict, optim_state_dict) >>> # Load a checkpoint >>> model, optim = ... >>> state_dict, optim_state_dict = load_a_checkpoint() >>> FSDP.set_state_dict_type( >>> model, >>> StateDictType.FULL_STATE_DICT, >>> FullStateDictConfig(rank0_only=False), >>> FullOptimStateDictConfig(rank0_only=False), >>> ) >>> model.load_state_dict(state_dict) >>> optim_state_dict = FSDP.optim_state_dict_to_load( >>> model, optim, optim_state_dict >>> ) >>> optim.load_state_dict(optim_state_dict) Args: model (torch.nn.Module): Root module (which may or may not be a :class:`FullyShardedDataParallel` instance) whose parameters were passed into the optimizer ``optim``. optim (torch.optim.Optimizer): Optimizer for ``model`` 's parameters. optim_state_dict (Dict[str, Any]): the target optimizer state_dict to transform. If the value is None, optim.state_dict() will be used. ( Default: ``None``) group (dist.ProcessGroup): Model's process group across which parameters are sharded or ``None`` if using the default process group. ( Default: ``None``) Returns: Dict[str, Any]: A :class:`dict` containing the optimizer state for ``model``. The sharding of the optimizer state is based on ``state_dict_type``. """ state_dict_settings = FullyShardedDataParallel.get_state_dict_type(model) if optim_state_dict is None: optim_state_dict = optim.state_dict() return FullyShardedDataParallel._optim_state_dict_impl( model=model, optim=optim, optim_state_dict=optim_state_dict, optim_input=None, rank0_only=getattr( state_dict_settings.optim_state_dict_config, "rank0_only", False ), full_state_dict=state_dict_settings.state_dict_type == StateDictType.FULL_STATE_DICT, group=group, cpu_offload=getattr( state_dict_settings.optim_state_dict_config, "offload_to_cpu", True ), _stacklevel=2, ) @staticmethod def optim_state_dict_to_load( model: torch.nn.Module, optim: torch.optim.Optimizer, optim_state_dict: dict[str, Any], is_named_optimizer: bool = False, load_directly: bool = False, group: Optional[dist.ProcessGroup] = None, ) -> dict[str, Any]: """ Convert an optimizer state-dict so that it can be loaded into the optimizer associated with the FSDP model. Given a ``optim_state_dict`` that is transformed through :meth:`optim_state_dict`, it gets converted to the flattened optimizer state_dict that can be loaded to ``optim`` which is the optimizer for ``model``. ``model`` must be sharded by FullyShardedDataParallel. >>> # xdoctest: +SKIP("undefined variables") >>> from torch.distributed.fsdp import FullyShardedDataParallel as FSDP >>> from torch.distributed.fsdp import StateDictType >>> from torch.distributed.fsdp import FullStateDictConfig >>> from torch.distributed.fsdp import FullOptimStateDictConfig >>> # Save a checkpoint >>> model, optim = ... >>> FSDP.set_state_dict_type( >>> model, >>> StateDictType.FULL_STATE_DICT, >>> FullStateDictConfig(rank0_only=False), >>> FullOptimStateDictConfig(rank0_only=False), >>> ) >>> state_dict = model.state_dict() >>> original_osd = optim.state_dict() >>> optim_state_dict = FSDP.optim_state_dict( >>> model, >>> optim, >>> optim_state_dict=original_osd >>> ) >>> save_a_checkpoint(state_dict, optim_state_dict) >>> # Load a checkpoint >>> model, optim = ... >>> state_dict, optim_state_dict = load_a_checkpoint() >>> FSDP.set_state_dict_type( >>> model, >>> StateDictType.FULL_STATE_DICT, >>> FullStateDictConfig(rank0_only=False), >>> FullOptimStateDictConfig(rank0_only=False), >>> ) >>> model.load_state_dict(state_dict) >>> optim_state_dict = FSDP.optim_state_dict_to_load( >>> model, optim, optim_state_dict >>> ) >>> optim.load_state_dict(optim_state_dict) Args: model (torch.nn.Module): Root module (which may or may not be a :class:`FullyShardedDataParallel` instance) whose parameters were passed into the optimizer ``optim``. optim (torch.optim.Optimizer): Optimizer for ``model`` 's parameters. optim_state_dict (Dict[str, Any]): The optimizer states to be loaded. is_named_optimizer (bool): Is this optimizer a NamedOptimizer or KeyedOptimizer. Only set to True if ``optim`` is TorchRec's KeyedOptimizer or torch.distributed's NamedOptimizer. load_directly (bool): If this is set to True, this API will also call optim.load_state_dict(result) before returning the result. Otherwise, users are responsible to call ``optim.load_state_dict()`` (Default: ``False``) group (dist.ProcessGroup): Model's process group across which parameters are sharded or ``None`` if using the default process group. ( Default: ``None``) """ state_dict_settings = FullyShardedDataParallel.get_state_dict_type(model) result = FullyShardedDataParallel._optim_state_dict_to_load_impl( optim_state_dict=optim_state_dict, model=model, optim_input=None, optim=optim, full_state_dict=( state_dict_settings.state_dict_type == StateDictType.FULL_STATE_DICT ), rank0_only=getattr( state_dict_settings.optim_state_dict_config, "rank0_only", False ), is_named_optimizer=is_named_optimizer, group=group, ) if load_directly: optim.load_state_dict(result) return result def register_comm_hook(self, state: object, hook: callable): """Register a communication hook. This is an enhancement that provides a flexible hook to users where they can specify how FSDP aggregates gradients across multiple workers. This hook can be used to implement several algorithms like `GossipGrad <https://arxiv.org/abs/1803.05880>`_ and gradient compression which involve different communication strategies for parameter syncs while training with :class:`FullyShardedDataParallel`. .. warning :: FSDP communication hook should be registered before running an initial forward pass and only once. Args: state (object): Passed to the hook to maintain any state information during the training process. Examples include error feedback in gradient compression, peers to communicate with next in `GossipGrad <https://arxiv.org/abs/1803.05880>`_, etc. It is locally stored by each worker and shared by all the gradient tensors on the worker. hook (Callable): Callable, which has one of the following signatures: 1) ``hook: Callable[torch.Tensor] -> None``: This function takes in a Python tensor, which represents the full, flattened, unsharded gradient with respect to all variables corresponding to the model this FSDP unit is wrapping (that are not wrapped by other FSDP sub-units). It then performs all necessary processing and returns ``None``; 2) ``hook: Callable[torch.Tensor, torch.Tensor] -> None``: This function takes in two Python tensors, the first one represents the full, flattened, unsharded gradient with respect to all variables corresponding to the model this FSDP unit is wrapping (that are not wrapped by other FSDP sub-units). The latter represents a pre-sized tensor to store a chunk of a sharded gradient after reduction. In both cases, callable performs all necessary processing and returns ``None``. Callables with signature 1 are expected to handle gradient communication for a `NO_SHARD` case. Callables with signature 2 are expected to handle gradient communication for sharded cases. """ if not self.check_is_root(): raise AssertionError( "register_comm_hook can only be called on a root instance." ) for fsdp_state in traversal_utils._get_fsdp_states(self): if fsdp_state.sharding_strategy in HYBRID_SHARDING_STRATEGIES: raise AssertionError( f"Communication hook is not supported for hybrid strategies: {fsdp_state.sharding_strategy}" ) if fsdp_state._comm_hook is not None: raise AssertionError("A communication hook is already registered") if not callable(hook): raise ValueError( f"The communication hook must be callable but got {hook}" ) fsdp_state._comm_hook = hook fsdp_state._comm_hook_state = state def _unshard(self, async_op: bool = False): class UnshardHandle: def __init__( self, flat_param_handle: Optional[FlatParamHandle], unshard_event: torch.Event, ): self._flat_param_handle = flat_param_handle self._unshard_event = unshard_event def wait(self): if self._flat_param_handle is not None: current_stream = ( self._flat_param_handle._device_handle.current_stream() ) current_stream.wait_event(self._unshard_event) self._flat_param_handle = None if self._handle: with self._use_training_state( TrainingState.FORWARD_BACKWARD, HandleTrainingState.FORWARD ): _unshard( self, self._handle, self._unshard_stream, self._pre_unshard_stream ) self._unshard_event = self._unshard_stream.record_event() self._handle._prefetched = True unshard_handle = UnshardHandle(self._handle, self._unshard_stream) if async_op: return unshard_handle unshard_handle.wait() return None def _wait_unshard_streams_on_current_stream(self): _wait_for_computation_stream( self._device_handle.current_stream(), self._unshard_stream, self._pre_unshard_stream, ) @contextlib.contextmanager def _use_training_state( self, training_state: TrainingState, handle_training_state: HandleTrainingState ): prev_training_state = self.training_state self.training_state = training_state if self._handle: prev_handle_training_state = self._handle._training_state self._handle._training_state = handle_training_state try: yield finally: self.training_state = prev_training_state if self._handle: self._handle._training_state = prev_handle_training_state def _get_grad_norm( params: Iterable[nn.Parameter], norm_type: float, zero: torch.Tensor, device: torch.device, ) -> torch.Tensor: """ Return the gradient norm of parameters ``param`` s, where the gradients are viewed as a single vector. The returned norm is in FP32 even if parameters/gradients are in a low precision. This is because the downstream use of this return value is a reduction across ranks. """ params_with_grad = [param for param in params if param.grad is not None] if len(params_with_grad) == 0: # Reuse a tensor for zero to avoid a GPU sync return zero grads = [param.grad for param in params_with_grad] grad_dtypes = {grad.dtype for grad in grads} if len(grad_dtypes) != 1: raise ValueError( f"Requires uniform dtype across all gradients but got {grad_dtypes}" ) # Compute the gradient norm in FP32, where we treat the gradients as a # single vector grad_norm = torch.linalg.vector_norm( torch.stack( [ torch.linalg.vector_norm(grad.detach(), norm_type, dtype=torch.float32) for grad in grads ], ), norm_type, dtype=torch.float32, ) return grad_norm.to(device=device) def _get_param_to_fqn( model: torch.nn.Module, ) -> dict[torch.nn.Parameter, str]: """ Construct a mapping from parameters to their parameter names. The ``model`` should not contain any :class:`FullyShardedDataParallel` instances, which means that none of the parameters should be ``FlatParameter`` s. As a result, compared to :meth:`_get_param_to_fqns`, the mapped values may be flattened from singleton :class:`list` s to the contained names themselves. Args: model (torch.nn.Module): Root module, which should not contain any :class:`FullyShardedDataParallel` instances. """ param_to_param_names = _get_param_to_fqns(model) for param_names in param_to_param_names.values(): if len(param_names) == 0: raise AssertionError( "`_get_param_to_fqns()` should not construct empty lists" ) if len(param_names) > 1: raise RuntimeError( "Each parameter should only map to one parameter name but got " f"{len(param_names)}: {param_names}" ) param_to_param_name = { param: param_names[0] for param, param_names in param_to_param_names.items() } return param_to_param_name def _get_fqn_to_param( model: torch.nn.Module, ) -> dict[str, torch.nn.Parameter]: """Construct the inverse mapping of :meth:`_get_param_to_fqn`.""" param_to_param_name = _get_param_to_fqn(model) return dict(zip(param_to_param_name.values(), param_to_param_name.keys()))
FullyShardedDataParallel
python
PrefectHQ__prefect
tests/server/orchestration/test_core_policy.py
{ "start": 113770, "end": 115631 }
class ____: @pytest.mark.parametrize( "proposed_state_type", sorted( list(set(ALL_ORCHESTRATION_STATES) - {states.StateType.CANCELLED, None}) ), ) async def test_rejects_cancelling_to_anything_but_cancelled( self, session, initialize_orchestration, proposed_state_type, ): initial_state_type = states.StateType.CANCELLING intended_transition = (initial_state_type, proposed_state_type) ctx = await initialize_orchestration( session, "flow", *intended_transition, ) async with EnforceCancellingToCancelledTransition( ctx, *intended_transition ) as ctx: await ctx.validate_proposed_state() assert ctx.response_status == SetStateStatus.REJECT assert ctx.validated_state_type == states.StateType.CANCELLING @pytest.mark.parametrize( "proposed_state_type", sorted( list(set(ALL_ORCHESTRATION_STATES) - {states.StateType.CANCELLED, None}) ), ) async def test_rejects_cancelled_cancelling_to_anything_but_cancelled( self, session, initialize_orchestration, proposed_state_type, ): initial_state_type = states.StateType.CANCELLING intended_transition = (initial_state_type, proposed_state_type) ctx = await initialize_orchestration( session, "flow", *intended_transition, ) async with EnforceCancellingToCancelledTransition( ctx, *intended_transition ) as ctx: await ctx.validate_proposed_state() assert ctx.response_status == SetStateStatus.REJECT assert ctx.validated_state_type == states.StateType.CANCELLING
TestHandleCancellingStateTransitions
python
run-llama__llama_index
llama-index-integrations/program/llama-index-program-evaporate/llama_index/program/evaporate/base.py
{ "start": 4127, "end": 6210 }
class ____(BaseEvaporateProgram[DataFrameRowsOnly]): """ Evaporate DF program. Given a set of fields, extracts a dataframe from a set of nodes. Each node corresponds to a row in the dataframe - each value in the row corresponds to a field value. """ def fit( self, nodes: List[BaseNode], field: str, field_context: Optional[Any] = None, expected_output: Optional[Any] = None, inplace: bool = True, ) -> str: """Given the input Nodes and fields, synthesize the python code.""" fn = self._extractor.extract_fn_from_nodes(nodes, field) logger.debug(f"Extracted function: {fn}") if inplace: self._field_fns[field] = fn return fn def _inference( self, nodes: List[BaseNode], fn_str: str, field_name: str ) -> List[Any]: """Given the input, call the python code and return the result.""" results = self._extractor.run_fn_on_nodes(nodes, fn_str, field_name) logger.debug(f"Results: {results}") return results @property def output_cls(self) -> Type[DataFrameRowsOnly]: """Output class.""" return DataFrameRowsOnly def __call__(self, *args: Any, **kwds: Any) -> DataFrameRowsOnly: """Call evaporate on inference data.""" # TODO: either specify `nodes` or `texts` in kwds if "nodes" in kwds: nodes = kwds["nodes"] elif "texts" in kwds: nodes = [TextNode(text=t) for t in kwds["texts"]] else: raise ValueError("Must provide either `nodes` or `texts`.") col_dict = {} for field in self._fields: col_dict[field] = self._inference(nodes, self._field_fns[field], field) df = pd.DataFrame(col_dict, columns=self._fields) # convert pd.DataFrame to DataFrameRowsOnly df_row_objs = [] for row_arr in df.values: df_row_objs.append(DataFrameRow(row_values=list(row_arr))) return DataFrameRowsOnly(rows=df_row_objs)
DFEvaporateProgram
python
viewflow__viewflow
viewflow/urls/model.py
{ "start": 3304, "end": 3577 }
class ____(metaclass=ViewsetMeta): list_bulk_actions = DEFAULT def get_list_bulk_actions(self, request, *actions): if self.list_bulk_actions is not DEFAULT: actions = (*self.list_bulk_actions, *actions) return actions
ListBulkActionsMixin
python
google__jax
tests/pallas/tpu_pallas_test.py
{ "start": 109463, "end": 109557 }
class ____(PallasCallTPUBooleanTest): INTERPRET: bool = True
PallasCallTPUBooleanInterpretTest
python
pypa__pip
src/pip/_vendor/pygments/filters/__init__.py
{ "start": 1804, "end": 2862 }
class ____(Filter): """Highlight special code tags in comments and docstrings. Options accepted: `codetags` : list of strings A list of strings that are flagged as code tags. The default is to highlight ``XXX``, ``TODO``, ``FIXME``, ``BUG`` and ``NOTE``. .. versionchanged:: 2.13 Now recognizes ``FIXME`` by default. """ def __init__(self, **options): Filter.__init__(self, **options) tags = get_list_opt(options, 'codetags', ['XXX', 'TODO', 'FIXME', 'BUG', 'NOTE']) self.tag_re = re.compile(r'\b({})\b'.format('|'.join([ re.escape(tag) for tag in tags if tag ]))) def filter(self, lexer, stream): regex = self.tag_re for ttype, value in stream: if ttype in String.Doc or \ ttype in Comment and \ ttype not in Comment.Preproc: yield from _replace_special(ttype, value, regex, Comment.Special) else: yield ttype, value
CodeTagFilter
python
google__pytype
pytype/block_environment.py
{ "start": 247, "end": 1822 }
class ____: """A store of local variables per blockgraph node.""" def __init__(self): self.block_locals: BlockLocals = {} # Blocks whose outgoing edges cannot be traversed. This can happen if, for # example, a block unconditionally raises an exception. self._dead_ends: set[blocks.Block] = set() def mark_dead_end(self, block): self._dead_ends.add(block) def add_block(self, frame, block): """Add a new block and initialize its locals.""" local = {} self.block_locals[block] = local incoming = [ b for b in block.incoming if b in self.block_locals and b != block and b not in self._dead_ends ] n_inc = len(incoming) if n_inc == 0: try: f_locals = frame.f_locals.pyval.items() except AttributeError: f_locals = () frame_locals = {k: [v] for k, v in f_locals} local.update(frame_locals) elif n_inc == 1: (inc,) = incoming local.update(self.block_locals[inc]) else: keys = None for b in incoming: b_keys = set(self.block_locals[b]) if keys is None: keys = b_keys else: keys &= b_keys assert keys is not None for k in keys: var = set() for b in incoming: incoming_locals = self.block_locals[b] var |= set(incoming_locals[k]) local[k] = list(var) def store_local(self, block, name, var): self.block_locals[block][name] = [var] def get_local(self, block, name): return self.block_locals[block].get(name)
Environment
python
google__jax
tests/pallas/mosaic_gpu_test.py
{ "start": 113797, "end": 113915 }
class ____( PallasCallSm90ATest, lowering_semantics=plgpu.LoweringSemantics.Warpgroup ): ...
PallasCallSm90AWGTest
python
tensorflow__tensorflow
tensorflow/python/util/function_parameter_canonicalizer_test.py
{ "start": 884, "end": 3638 }
class ____(test.TestCase): def setUp(self): super(FunctionParameterCanonicalizerTest, self).setUp() self._matmul_func = ( _function_parameter_canonicalizer_binding_for_test .FunctionParameterCanonicalizer([ 'a', 'b', 'transpose_a', 'transpose_b', 'adjoint_a', 'adjoint_b', 'a_is_sparse', 'b_is_sparse', 'name' ], (False, False, False, False, False, False, None))) def testPosOnly(self): self.assertEqual( self._matmul_func.canonicalize(2, 3), [2, 3, False, False, False, False, False, False, None]) def testPosOnly2(self): self.assertEqual( self._matmul_func.canonicalize(2, 3, True, False, True), [2, 3, True, False, True, False, False, False, None]) def testPosAndKwd(self): self.assertEqual( self._matmul_func.canonicalize( 2, 3, transpose_a=True, name='my_matmul'), [2, 3, True, False, False, False, False, False, 'my_matmul']) def testPosAndKwd2(self): self.assertEqual( self._matmul_func.canonicalize(2, b=3), [2, 3, False, False, False, False, False, False, None]) def testMissingPos(self): with self.assertRaisesRegex(TypeError, 'Missing required positional argument'): self._matmul_func.canonicalize(2) def testMissingPos2(self): with self.assertRaisesRegex(TypeError, 'Missing required positional argument'): self._matmul_func.canonicalize( transpose_a=True, transpose_b=True, adjoint_a=True) def testTooManyArgs(self): with self.assertRaisesRegex(TypeError, 'Too many arguments were given.' ' Expected 9 but got 10.'): self._matmul_func.canonicalize(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) def testInvalidKwd(self): with self.assertRaisesRegex(TypeError, 'Got an unexpected keyword argument'): self._matmul_func.canonicalize(2, 3, hohoho=True) def testDuplicatedArg(self): with self.assertRaisesRegex(TypeError, "Got multiple values for argument 'b'"): self._matmul_func.canonicalize(2, 3, False, b=4) def testDuplicatedArg2(self): with self.assertRaisesRegex( TypeError, "Got multiple values for argument 'transpose_a'"): self._matmul_func.canonicalize(2, 3, False, transpose_a=True) def testKwargNotInterned(self): func = ( _function_parameter_canonicalizer_binding_for_test .FunctionParameterCanonicalizer(['long_parameter_name'], ())) kwargs = dict([('_'.join(['long', 'parameter', 'name']), 5)]) func.canonicalize(**kwargs) if __name__ == '__main__': test.main()
FunctionParameterCanonicalizerTest
python
Unity-Technologies__ml-agents
ml-agents-envs/mlagents_envs/exception.py
{ "start": 366, "end": 504 }
class ____(UnityException): """ Raised when communicator has stopped gracefully. """ pass
UnityCommunicatorStoppedException
python
django__django
tests/forms_tests/widget_tests/test_splithiddendatetimewidget.py
{ "start": 177, "end": 4047 }
class ____(WidgetTest): widget = SplitHiddenDateTimeWidget() def test_render_empty(self): self.check_html( self.widget, "date", "", html=( '<input type="hidden" name="date_0"><input type="hidden" name="date_1">' ), ) def test_render_value(self): d = datetime(2007, 9, 17, 12, 51, 34, 482548) self.check_html( self.widget, "date", d, html=( '<input type="hidden" name="date_0" value="2007-09-17">' '<input type="hidden" name="date_1" value="12:51:34">' ), ) self.check_html( self.widget, "date", datetime(2007, 9, 17, 12, 51, 34), html=( '<input type="hidden" name="date_0" value="2007-09-17">' '<input type="hidden" name="date_1" value="12:51:34">' ), ) self.check_html( self.widget, "date", datetime(2007, 9, 17, 12, 51), html=( '<input type="hidden" name="date_0" value="2007-09-17">' '<input type="hidden" name="date_1" value="12:51:00">' ), ) @translation.override("de-at") def test_l10n(self): d = datetime(2007, 9, 17, 12, 51) self.check_html( self.widget, "date", d, html=( """ <input type="hidden" name="date_0" value="17.09.2007"> <input type="hidden" name="date_1" value="12:51:00"> """ ), ) def test_constructor_different_attrs(self): html = ( '<input type="hidden" class="foo" value="2006-01-10" name="date_0">' '<input type="hidden" class="bar" value="07:30:00" name="date_1">' ) widget = SplitHiddenDateTimeWidget( date_attrs={"class": "foo"}, time_attrs={"class": "bar"} ) self.check_html(widget, "date", datetime(2006, 1, 10, 7, 30), html=html) widget = SplitHiddenDateTimeWidget( date_attrs={"class": "foo"}, attrs={"class": "bar"} ) self.check_html(widget, "date", datetime(2006, 1, 10, 7, 30), html=html) widget = SplitHiddenDateTimeWidget( time_attrs={"class": "bar"}, attrs={"class": "foo"} ) self.check_html(widget, "date", datetime(2006, 1, 10, 7, 30), html=html) def test_fieldset(self): class TestForm(Form): template_name = "forms_tests/use_fieldset.html" field = SplitDateTimeField(widget=self.widget) form = TestForm() self.assertIs(self.widget.use_fieldset, True) self.assertHTMLEqual( '<input type="hidden" name="field_0" id="id_field_0">' '<input type="hidden" name="field_1" id="id_field_1">', form.render(), ) def test_fieldset_with_unhidden_field(self): class TestForm(Form): template_name = "forms_tests/use_fieldset.html" hidden_field = SplitDateTimeField(widget=self.widget) unhidden_field = SplitDateTimeField() form = TestForm() self.assertIs(self.widget.use_fieldset, True) self.assertHTMLEqual( "<div><fieldset><legend>Unhidden field:</legend>" '<input type="text" name="unhidden_field_0" required ' 'id="id_unhidden_field_0"><input type="text" ' 'name="unhidden_field_1" required id="id_unhidden_field_1">' '</fieldset><input type="hidden" name="hidden_field_0" ' 'id="id_hidden_field_0"><input type="hidden" ' 'name="hidden_field_1" id="id_hidden_field_1"></div>', form.render(), )
SplitHiddenDateTimeWidgetTest
python
pytorch__pytorch
torch/testing/_internal/distributed/rpc/rpc_test.py
{ "start": 17464, "end": 18353 }
class ____(nn.Module): def __init__(self, device): super().__init__() self.net = nn.Sequential( nn.Conv2d(1, 16, 3, 1), nn.ReLU(), nn.Conv2d(16, 32, 3, 1), nn.ReLU(), nn.MaxPool2d(2), nn.Flatten(1), nn.Linear(4608, 128), nn.ReLU(), nn.Linear(128, 10), ).to(device) self.device = device def forward(self, x, is_rref=False): x = x.to_here() if is_rref else x with torch.cuda.stream(torch.cuda.current_stream(self.device)): # intentionally adding delay to current CUDA stream torch.cuda._sleep(10 * FIFTY_MIL_CYCLES) return self.net(x) def __getstate__(self): # return an empty dict to avoid inspecting the model contents on the # owner return {}
MyConvNetForMNIST
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 522619, "end": 523286 }
class ____(sgqlc.types.relay.Connection): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("edges", "nodes", "page_info", "total_count") edges = sgqlc.types.Field( sgqlc.types.list_of("ProjectV2ItemFieldValueEdge"), graphql_name="edges" ) nodes = sgqlc.types.Field( sgqlc.types.list_of("ProjectV2ItemFieldValue"), graphql_name="nodes" ) page_info = sgqlc.types.Field( sgqlc.types.non_null(PageInfo), graphql_name="pageInfo" ) total_count = sgqlc.types.Field( sgqlc.types.non_null(Int), graphql_name="totalCount" )
ProjectV2ItemFieldValueConnection
python
jmcnamara__XlsxWriter
xlsxwriter/exceptions.py
{ "start": 1028, "end": 1115 }
class ____(XlsxFileError): """No size data found in image file."""
UndefinedImageSize
python
SmileyChris__easy-thumbnails
easy_thumbnails/tests/test_files.py
{ "start": 374, "end": 17517 }
class ____(test.BaseTest): def setUp(self): super().setUp() self.storage = test.TemporaryStorage() self.remote_storage = test.FakeRemoteStorage() # Save a test image in both storages. filename = self.create_image(self.storage, 'test.jpg') self.thumbnailer = files.get_thumbnailer(self.storage, filename) self.thumbnailer.thumbnail_storage = self.storage filename = self.create_image(self.remote_storage, 'test.jpg') self.remote_thumbnailer = files.get_thumbnailer( self.remote_storage, filename) self.remote_thumbnailer.thumbnail_storage = self.remote_storage # Create another thumbnailer for extension test. self.ext_thumbnailer = files.get_thumbnailer(self.storage, filename) self.ext_thumbnailer.thumbnail_storage = self.storage # Generate test transparent images. filename = self.create_image( self.storage, 'transparent.png', image_mode='RGBA', image_format='PNG') self.transparent_thumbnailer = files.get_thumbnailer( self.storage, filename) self.transparent_thumbnailer.thumbnail_storage = self.storage filename = self.create_image( self.storage, 'transparent-greyscale.png', image_mode='LA', image_format='PNG') self.transparent_greyscale_thumbnailer = files.get_thumbnailer( self.storage, filename) self.transparent_greyscale_thumbnailer.thumbnail_storage = self.storage def tearDown(self): self.storage.delete_temporary_storage() self.remote_storage.delete_temporary_storage() super().tearDown() def test_tag(self): local = self.thumbnailer.get_thumbnail({'size': (100, 100)}) remote = self.remote_thumbnailer.get_thumbnail({'size': (100, 100)}) self.assertEqual( local.tag(), '<img alt="" height="75" src="%s" width="100" ' '/>' % local.url) self.assertEqual( local.tag(alt='A & B'), '<img alt="A &amp; B" height="75" ' 'src="%s" width="100" />' % local.url) # Can turn off dimensions. self.assertEqual( remote.tag(use_size=False), '<img alt="" src="%s" />' % remote.url) # Even a remotely generated thumbnail has the dimensions cached if it # was just created. self.assertEqual( remote.tag(), '<img alt="" height="75" src="%s" width="100" />' % remote.url) # Future requests to thumbnails on remote storage don't get # dimensions... remote = self.remote_thumbnailer.get_thumbnail({'size': (100, 100)}) self.assertEqual( remote.tag(), '<img alt="" src="%s" />' % remote.url) # ...unless explicitly requested. self.assertEqual( remote.tag(use_size=True), '<img alt="" height="75" src="%s" width="100" />' % remote.url) # All other arguments are passed through as attributes. self.assertEqual( local.tag(**{'rel': 'A&B', 'class': 'fish'}), '<img alt="" class="fish" height="75" rel="A&amp;B" ' 'src="%s" width="100" />' % local.url) def test_tag_cached_dimensions(self): settings.THUMBNAIL_CACHE_DIMENSIONS = True self.remote_thumbnailer.get_thumbnail({'size': (100, 100)}) # Look up thumbnail again to ensure dimensions are a *really* cached. remote = self.remote_thumbnailer.get_thumbnail({'size': (100, 100)}) self.assertEqual( remote.tag(), '<img alt="" height="75" src="%s" width="100" />' % remote.url) def test_transparent_thumbnailing(self): thumb_file = self.thumbnailer.get_thumbnail( {'size': (100, 100)}) thumb_file.seek(0) with Image.open(thumb_file) as thumb: self.assertFalse( utils.is_transparent(thumb), "%s shouldn't be transparent." % thumb_file.name) thumb_file = self.transparent_thumbnailer.get_thumbnail( {'size': (100, 100)}) thumb_file.seek(0) with Image.open(thumb_file) as thumb: self.assertTrue( utils.is_transparent(thumb), "%s should be transparent." % thumb_file.name) thumb_file = self.transparent_greyscale_thumbnailer.get_thumbnail( {'size': (100, 100)}) thumb_file.seek(0) with Image.open(thumb_file) as thumb: self.assertTrue( utils.is_transparent(thumb), "%s should be transparent." % thumb_file.name) def test_missing_thumb(self): opts = {'size': (100, 100)} thumb = self.thumbnailer.get_thumbnail(opts) thumb_cache = self.thumbnailer.get_thumbnail_cache( thumbnail_name=thumb.name) thumb_cache.delete() thumb.storage.delete(thumb.name) self.thumbnailer.get_thumbnail(opts) def test_missing_thumb_from_storage(self): opts = {'size': (100, 100)} thumb = self.thumbnailer.get_thumbnail(opts) thumb.storage.delete(thumb.name) new_thumb = self.thumbnailer.get_thumbnail(opts) self.assertEqual(thumb.name, new_thumb.name) self.assertTrue(thumb.storage.exists(new_thumb.name)) def test_missing_remote_thumb(self): opts = {'size': (100, 100)} thumb = self.remote_thumbnailer.get_thumbnail(opts) thumb_cache = self.remote_thumbnailer.get_thumbnail_cache( thumbnail_name=thumb.name) thumb_cache.delete() thumb.storage.delete(thumb.name) self.remote_thumbnailer.get_thumbnail(opts) def test_missing_source(self): opts = {'size': (100, 100)} self.storage.delete(self.thumbnailer.name) self.assertRaises( exceptions.InvalidImageFormatError, self.thumbnailer.get_thumbnail, opts) def test_extensions(self): self.ext_thumbnailer.thumbnail_extension = 'png' thumb = self.ext_thumbnailer.get_thumbnail({'size': (100, 100)}) self.assertEqual(path.splitext(thumb.name)[1], '.png') self.ext_thumbnailer.thumbnail_preserve_extensions = ('foo',) thumb = self.ext_thumbnailer.get_thumbnail({'size': (100, 100)}) self.assertEqual(path.splitext(thumb.name)[1], '.png') self.ext_thumbnailer.thumbnail_preserve_extensions = True thumb = self.ext_thumbnailer.get_thumbnail({'size': (100, 100)}) self.assertEqual(path.splitext(thumb.name)[1], '.jpg') self.ext_thumbnailer.thumbnail_preserve_extensions = ('foo', 'jpg') thumb = self.ext_thumbnailer.get_thumbnail({'size': (100, 100)}) self.assertEqual(path.splitext(thumb.name)[1], '.jpg') def test_subsampling(self): samplings = { 0: (1, 1, 1, 1, 1, 1), 1: (2, 1, 1, 1, 1, 1), 2: (2, 2, 1, 1, 1, 1), } thumb = self.ext_thumbnailer.get_thumbnail({'size': (100, 100)}) with Image.open(thumb.path) as im: self.assertNotIn('ss', thumb.name) sampling = im.layer[0][1:3] + im.layer[1][1:3] + im.layer[2][1:3] self.assertEqual(sampling, samplings[2]) thumb = self.ext_thumbnailer.get_thumbnail( {'size': (100, 100), 'subsampling': 1}) with Image.open(thumb.path) as im: self.assertIn('ss1', thumb.name) sampling = im.layer[0][1:3] + im.layer[1][1:3] + im.layer[2][1:3] self.assertEqual(sampling, samplings[1]) thumb = self.ext_thumbnailer.get_thumbnail( {'size': (100, 100), 'subsampling': 0}) with Image.open(thumb.path) as im: self.assertIn('ss0', thumb.name) sampling = im.layer[0][1:3] + im.layer[1][1:3] + im.layer[2][1:3] self.assertEqual(sampling, samplings[0]) def test_default_subsampling(self): settings.THUMBNAIL_DEFAULT_OPTIONS = {'subsampling': 1} thumb = self.ext_thumbnailer.get_thumbnail({'size': (100, 100)}) with Image.open(thumb.path) as im: self.assertIn('ss1', thumb.name) sampling = im.layer[0][1:3] + im.layer[1][1:3] + im.layer[2][1:3] self.assertEqual(sampling, (2, 1, 1, 1, 1, 1)) @unittest.skipIf( 'easy_thumbnails.optimize' not in settings.INSTALLED_APPS, 'optimize app not installed') def test_postprocessor(self): """use a mock image optimizing post processor doing nothing""" settings.THUMBNAIL_OPTIMIZE_COMMAND = { 'png': 'easy_thumbnails/tests/mockoptim.py {filename}'} with LogCapture() as logcap: self.ext_thumbnailer.thumbnail_extension = 'png' self.ext_thumbnailer.get_thumbnail({'size': (10, 10)}) actual = tuple(logcap.actual())[-1] self.assertEqual(actual[0], 'easy_thumbnails.optimize') self.assertEqual(actual[1], 'INFO') self.assertRegex( actual[2], '^easy_thumbnails/tests/mockoptim.py [^ ]+ returned nothing$') @unittest.skipIf( 'easy_thumbnails.optimize' not in settings.INSTALLED_APPS, 'optimize app not installed') @unittest.skipIf(LogCapture is None, 'testfixtures not installed') def test_postprocessor_fail(self): """use a mock image optimizing post processor doing nothing""" settings.THUMBNAIL_OPTIMIZE_COMMAND = { 'png': 'easy_thumbnails/tests/mockoptim_fail.py {filename}'} with LogCapture() as logcap: self.ext_thumbnailer.thumbnail_extension = 'png' self.ext_thumbnailer.get_thumbnail({'size': (10, 10)}) actual = tuple(logcap.actual())[-1] self.assertEqual(actual[0], 'easy_thumbnails.optimize') self.assertEqual(actual[1], 'ERROR') self.assertRegex( actual[2], r'^Command .+returned non-zero exit status 1.*$') def test_USE_TZ(self): settings.USE_TZ = True self.thumbnailer.get_thumbnail({'size': (10, 20)}) settings.USE_TZ = False self.thumbnailer.get_thumbnail({'size': (20, 40)}) def test_thumbnailfile_options(self): opts = {'size': (50, 50), 'crop': True, 'upscale': True} thumb = self.thumbnailer.get_thumbnail(opts) self.assertEqual(thumb.thumbnail_options, ThumbnailOptions(opts)) def test_get_thumbnail_name(self): opts = { 'size': (50, 50), 'crop': 'smart', 'upscale': True, 'target': (10, 10)} self.assertEqual( self.thumbnailer.get_thumbnail_name(opts), 'test.jpg.50x50_q85_crop-smart_target-10,10_upscale.jpg') def test_default_options_setting(self): settings.THUMBNAIL_DEFAULT_OPTIONS = {'crop': True} opts = {'size': (50, 50)} thumb = self.thumbnailer.get_thumbnail(opts) self.assertEqual((thumb.width, thumb.height), (50, 50)) def test_dimensions_of_cached_image(self): opts = {'size': (50, 50)} thumb = self.thumbnailer.get_thumbnail(opts) self.assertEqual((thumb.width, thumb.height), (50, 38)) # Now the thumb has been created, check that retrieving this still # gives access to the dimensions. thumb = self.thumbnailer.get_thumbnail(opts) self.assertEqual((thumb.width, thumb.height), (50, 38)) def test_cached_dimensions_of_cached_image(self): settings.THUMBNAIL_CACHE_DIMENSIONS = True opts = {'size': (50, 50)} thumb = self.thumbnailer.get_thumbnail(opts) self.assertEqual((thumb.width, thumb.height), (50, 38)) # Now the thumb has been created, check that dimensions are in the # database. dimensions = models.ThumbnailDimensions.objects.all()[0] self.assertEqual( (thumb.width, thumb.height), (dimensions.width, dimensions.height)) def test_remote_cached_dimensions_queries(self): settings.THUMBNAIL_CACHE_DIMENSIONS = True opts = {'size': (50, 50)} thumb = self.remote_thumbnailer.get_thumbnail(opts) thumb.height # Trigger dimension caching. # Get thumb again (which now has cached dimensions). thumb = self.remote_thumbnailer.get_thumbnail(opts) with self.assertNumQueries(0): self.assertEqual(thumb.width, 50) def test_add_dimension_cache(self): settings.THUMBNAIL_CACHE_DIMENSIONS = True opts = {'size': (50, 50)} thumb = self.thumbnailer.get_thumbnail(opts) self.assertEqual((thumb.width, thumb.height), (50, 38)) # Delete the created dimensions. models.ThumbnailDimensions.objects.all().delete() # Now access the thumbnail again. thumb = self.thumbnailer.get_thumbnail(opts) self.assertEqual(models.ThumbnailDimensions.objects.count(), 0) thumb.height dimensions = models.ThumbnailDimensions.objects.get() # and make sure they match when fetched again. thumb = self.thumbnailer.get_thumbnail(opts) self.assertEqual( (thumb.width, thumb.height), (dimensions.width, dimensions.height)) # close the filefield (cause unclosed file ResourceWarning) thumb.close() def test_thumbnail_created_signal(self): def signal_handler(sender, **kwargs): sender.signal_received = True signals.thumbnail_created.connect(signal_handler) try: thumb = self.thumbnailer.get_thumbnail({'size': (10, 20)}) self.assertTrue(hasattr(thumb, 'signal_received')) finally: signals.thumbnail_created.disconnect(signal_handler) def test_passive_thumbnailer(self): options = {'size': (10, 10)} # Explicitly using the generate=False option on get_thumbnail won't # generate a missing thumb. thumb = self.thumbnailer.get_thumbnail(options, generate=False) self.assertEqual(thumb, None) # If the thumbnailer has generate=False, get_thumbnail won't generate a # missing thumb by default. self.thumbnailer.generate = False thumb = self.thumbnailer.get_thumbnail(options) self.assertEqual(thumb, None) # If the thumbnailer has generate=False, get_thumbnail with # generate=True will stiff force generation a missing thumb. thumb = self.thumbnailer.get_thumbnail(options, generate=True) self.assertTrue(thumb) # If the thumbnailer has generate=False, get_thumbnail will still # return existing thumbnails. thumb = self.thumbnailer.get_thumbnail(options) self.assertTrue(thumb) # Explicitly using the generate=False option on get_thumbnail will # still return existing thumbnails. thumb = self.thumbnailer.get_thumbnail(options, generate=False) self.assertTrue(thumb) def test_thumbnail_missed_signal(self): def signal_handler(sender, **kwargs): sender.missed_signal = kwargs.get('options') signals.thumbnail_missed.connect(signal_handler) try: # Standard generation doesn't trigger signal. self.thumbnailer.get_thumbnail({'size': (100, 100)}) self.assertFalse(hasattr(self.thumbnailer, 'missed_signal')) # Retrieval doesn't trigger signal. self.thumbnailer.get_thumbnail( {'size': (100, 100)}, generate=False) self.assertFalse(hasattr(self.thumbnailer, 'missed_signal')) # A thumbnail miss does trigger it. options = {'size': (10, 20)} thumb = self.thumbnailer.get_thumbnail(options, generate=False) self.assertEqual(thumb, None) self.assertEqual( self.thumbnailer.missed_signal, ThumbnailOptions(options)) finally: signals.thumbnail_created.disconnect(signal_handler) def test_progressive_encoding(self): thumb = self.thumbnailer.generate_thumbnail( {'size': (99, 99), 'crop': True}) with Image.open(thumb) as thumb_image: self.assertFalse(utils.is_progressive(thumb_image)) thumb = self.thumbnailer.generate_thumbnail( {'size': (1, 100), 'crop': True}) with Image.open(thumb) as thumb_image: self.assertTrue(utils.is_progressive(thumb_image)) thumb = self.thumbnailer.generate_thumbnail( {'size': (100, 1), 'crop': True}) with Image.open(thumb) as thumb_image: self.assertTrue(utils.is_progressive(thumb_image)) thumb = self.thumbnailer.generate_thumbnail({'size': (200, 200)}) with Image.open(thumb) as thumb_image: self.assertTrue(utils.is_progressive(thumb_image)) def test_no_progressive_encoding(self): settings.THUMBNAIL_PROGRESSIVE = False thumb = self.thumbnailer.generate_thumbnail({'size': (200, 200)}) with Image.open(thumb) as thumb_image: self.assertFalse(utils.is_progressive(thumb_image))
FilesTest
python
apache__airflow
providers/google/tests/unit/google/cloud/operators/test_bigtable.py
{ "start": 21339, "end": 25957 }
class ____: @mock.patch("airflow.providers.google.cloud.operators.bigtable.BigtableHook") def test_delete_execute(self, mock_hook): op = BigtableDeleteInstanceOperator( project_id=PROJECT_ID, instance_id=INSTANCE_ID, task_id="id", gcp_conn_id=GCP_CONN_ID, impersonation_chain=IMPERSONATION_CHAIN, ) op.execute(None) mock_hook.assert_called_once_with( gcp_conn_id=GCP_CONN_ID, impersonation_chain=IMPERSONATION_CHAIN, ) mock_hook.return_value.delete_instance.assert_called_once_with( project_id=PROJECT_ID, instance_id=INSTANCE_ID ) @mock.patch("airflow.providers.google.cloud.operators.bigtable.BigtableHook") def test_delete_execute_empty_project_id(self, mock_hook): op = BigtableDeleteInstanceOperator( instance_id=INSTANCE_ID, task_id="id", gcp_conn_id=GCP_CONN_ID, impersonation_chain=IMPERSONATION_CHAIN, ) op.execute(None) mock_hook.assert_called_once_with( gcp_conn_id=GCP_CONN_ID, impersonation_chain=IMPERSONATION_CHAIN, ) mock_hook.return_value.delete_instance.assert_called_once_with( project_id=None, instance_id=INSTANCE_ID ) @pytest.mark.parametrize( ("missing_attribute", "project_id", "instance_id"), [("instance_id", PROJECT_ID, "")], ) @mock.patch("airflow.providers.google.cloud.operators.bigtable.BigtableHook") def test_empty_attribute(self, mock_hook, missing_attribute, project_id, instance_id): with pytest.raises(AirflowException) as ctx: BigtableDeleteInstanceOperator(project_id=project_id, instance_id=instance_id, task_id="id") err = ctx.value assert str(err) == f"Empty parameter: {missing_attribute}" mock_hook.assert_not_called() @mock.patch("airflow.providers.google.cloud.operators.bigtable.BigtableHook") def test_deleting_instance_that_doesnt_exists(self, mock_hook): op = BigtableDeleteInstanceOperator( project_id=PROJECT_ID, instance_id=INSTANCE_ID, task_id="id", gcp_conn_id=GCP_CONN_ID, impersonation_chain=IMPERSONATION_CHAIN, ) mock_hook.return_value.delete_instance.side_effect = mock.Mock( side_effect=google.api_core.exceptions.NotFound("Instance not found.") ) op.execute(None) mock_hook.assert_called_once_with( gcp_conn_id=GCP_CONN_ID, impersonation_chain=IMPERSONATION_CHAIN, ) mock_hook.return_value.delete_instance.assert_called_once_with( project_id=PROJECT_ID, instance_id=INSTANCE_ID ) @mock.patch("airflow.providers.google.cloud.operators.bigtable.BigtableHook") def test_deleting_instance_that_doesnt_exists_empty_project_id(self, mock_hook): op = BigtableDeleteInstanceOperator( instance_id=INSTANCE_ID, task_id="id", gcp_conn_id=GCP_CONN_ID, impersonation_chain=IMPERSONATION_CHAIN, ) mock_hook.return_value.delete_instance.side_effect = mock.Mock( side_effect=google.api_core.exceptions.NotFound("Instance not found.") ) op.execute(None) mock_hook.assert_called_once_with( gcp_conn_id=GCP_CONN_ID, impersonation_chain=IMPERSONATION_CHAIN, ) mock_hook.return_value.delete_instance.assert_called_once_with( project_id=None, instance_id=INSTANCE_ID ) @mock.patch("airflow.providers.google.cloud.operators.bigtable.BigtableHook") def test_different_error_reraised(self, mock_hook): op = BigtableDeleteInstanceOperator( project_id=PROJECT_ID, instance_id=INSTANCE_ID, task_id="id", gcp_conn_id=GCP_CONN_ID, impersonation_chain=IMPERSONATION_CHAIN, ) mock_hook.return_value.delete_instance.side_effect = mock.Mock( side_effect=google.api_core.exceptions.GoogleAPICallError("error") ) with pytest.raises(google.api_core.exceptions.GoogleAPICallError): op.execute(None) mock_hook.assert_called_once_with( gcp_conn_id=GCP_CONN_ID, impersonation_chain=IMPERSONATION_CHAIN, ) mock_hook.return_value.delete_instance.assert_called_once_with( project_id=PROJECT_ID, instance_id=INSTANCE_ID )
TestBigtableInstanceDelete
python
spack__spack
var/spack/test_repos/spack_repo/builtin_mock/packages/parent_foo/package.py
{ "start": 217, "end": 634 }
class ____(Package): """This package has a variant "foo", which is True by default, and depends on another package which has the same variant defaulting to False. """ homepage = "http://www.example.com" url = "http://www.example.com/c-1.0.tar.gz" version("1.0", md5="0123456789abcdef0123456789abcdef") variant("foo", default=True, description="") depends_on("client-not-foo")
ParentFoo
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_chart_bar01.py
{ "start": 315, "end": 1445 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("chart_bar01.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file.""" workbook = Workbook(self.got_filename) worksheet = workbook.add_worksheet() chart = workbook.add_chart({"type": "bar"}) chart.axis_ids = [64052224, 64055552] data = [ [1, 2, 3, 4, 5], [2, 4, 6, 8, 10], [3, 6, 9, 12, 15], ] worksheet.write_column("A1", data[0]) worksheet.write_column("B1", data[1]) worksheet.write_column("C1", data[2]) chart.add_series( {"categories": "=Sheet1!$A$1:$A$5", "values": "=Sheet1!$B$1:$B$5"} ) chart.add_series( { "categories": "=Sheet1!$A$1:$A$5", "values": "=Sheet1!$C$1:$C$5", } ) worksheet.insert_chart("E9", chart) workbook.close() self.assertExcelEqual()
TestCompareXLSXFiles
python
tensorflow__tensorflow
tensorflow/compiler/tests/concat_ops_test.py
{ "start": 13744, "end": 14996 }
class ____(xla_test.XLATestCase): def testBasic(self): with self.session(): with self.test_scope(): s0 = constant_op.constant([2, 3, 5], dtypes.int32) s1 = constant_op.constant([2, 7, 5], dtypes.int32) s2 = constant_op.constant([2, 20, 5], dtypes.int32) packed = array_ops_stack.stack([s0, s1, s2]) ans = self.evaluate(packed) self.assertAllEqual(ans, [[2, 3, 5], [2, 7, 5], [2, 20, 5]]) def testScalars(self): with self.session(): with self.test_scope(): s0 = constant_op.constant(2, dtypes.int32) s1 = constant_op.constant(3, dtypes.int32) s2 = constant_op.constant(5, dtypes.int32) packed = array_ops_stack.stack([s0, s1, s2]) ans = self.evaluate(packed) self.assertAllEqual(ans, [2, 3, 5]) def testEmpty(self): with self.session(): with self.test_scope(): s0 = constant_op.constant([[]], dtypes.int32) s1 = constant_op.constant([[]], dtypes.int32) s2 = constant_op.constant([[]], dtypes.int32) packed = array_ops_stack.stack([s0, s1, s2]) ans = self.evaluate(packed) self.assertAllEqual(ans, [[[]], [[]], [[]]]) if __name__ == "__main__": googletest.main()
PackTest
python
getsentry__sentry
tests/sentry/api/endpoints/release_thresholds/utils/test_get_errors_counts_timeseries.py
{ "start": 310, "end": 1738 }
class ____(TestCase): def setUp(self) -> None: super().setUp() self.org = self.create_organization() self.project = self.create_project(name="foo", organization=self.org) @mock.patch("sentry.api.endpoints.release_thresholds.utils.snuba.raw_snql_query") def test_errors_timeseries_snuba_fetch(self, mock_snql_query: mock.MagicMock) -> None: now = timezone.now() get_errors_counts_timeseries_by_project_and_release( end=now, organization_id=self.org.id, project_id_list=[], release_value_list=[], start=now, ) assert mock_snql_query.call_count == 1 @mock.patch("sentry.api.endpoints.release_thresholds.utils.snuba.raw_snql_query") def test_errors_timeseries_snuba_fetch_called_with_env( self, mock_snql_query: mock.MagicMock ) -> None: now = timezone.now() env_list = ["foo"] get_errors_counts_timeseries_by_project_and_release( end=now, organization_id=self.org.id, project_id_list=[], release_value_list=[], start=now, environments_list=env_list, ) env_condition = Condition(Column("environment"), Op.IN, env_list) call_conditions = mock_snql_query.call_args[1]["request"].query.where assert env_condition in call_conditions
GetErrorCountTimeseriesTest
python
pytorch__pytorch
test/distributed/checkpoint/test_hsdp_checkpoint.py
{ "start": 1532, "end": 2069 }
class ____(torch.nn.Module): def __init__(self) -> None: super().__init__() self.net1 = nn.Linear(5, 10) self.relu = nn.ReLU() self.net2 = nn.Linear(10, 15) self.net3 = nn.Linear(15, 30) self.net4 = nn.Linear(30, 5) def forward(self, x): x = F.relu(self.net1(x)) x = F.relu(self.net2(x)) x = F.relu(self.net3(x)) x = F.relu(self.net4(x)) return x def get_input(self): return torch.rand(4, 5, device=device_type)
SimpleModelUneven
python
ray-project__ray
python/ray/tune/schedulers/trial_scheduler.py
{ "start": 4321, "end": 5484 }
class ____(TrialScheduler): """Simple scheduler that just runs trials in submission order.""" def __init__(self): super().__init__() def on_trial_add(self, tune_controller: "TuneController", trial: Trial): pass def on_trial_error(self, tune_controller: "TuneController", trial: Trial): pass def on_trial_result( self, tune_controller: "TuneController", trial: Trial, result: Dict ) -> str: return TrialScheduler.CONTINUE def on_trial_complete( self, tune_controller: "TuneController", trial: Trial, result: Dict ): pass def on_trial_remove(self, tune_controller: "TuneController", trial: Trial): pass def choose_trial_to_run(self, tune_controller: "TuneController") -> Optional[Trial]: for trial in tune_controller.get_trials(): if trial.status == Trial.PENDING: return trial for trial in tune_controller.get_trials(): if trial.status == Trial.PAUSED: return trial return None def debug_string(self) -> str: return "Using FIFO scheduling algorithm."
FIFOScheduler
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 641086, "end": 641429 }
class ____(sgqlc.types.Type): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("cursor", "node") cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor") node = sgqlc.types.Field("StatusCheckRollupContext", graphql_name="node")
StatusCheckRollupContextEdge
python
ionelmc__pytest-benchmark
src/pytest_benchmark/cli.py
{ "start": 5954, "end": 6690 }
class ____: def __init__(self): self._tw = TerminalWriter() def ensure_newline(self): pass def write(self, content, **markup): self._tw.write(content, **markup) def write_line(self, line, **markup): if not isinstance(line, str): line = line.decode(errors='replace') self._tw.line(line, **markup) def rewrite(self, line, **markup): line = str(line) self._tw.write('\r' + line, **markup) def write_sep(self, sep, title=None, **markup): self._tw.sep(sep, title, **markup) def section(self, title, sep='=', **kw): self._tw.sep(sep, title, **kw) def line(self, msg, **kw): self._tw.line(msg, **kw)
TerminalReporter
python
TheAlgorithms__Python
graphs/deep_clone_graph.py
{ "start": 318, "end": 1741 }
class ____: value: int = 0 neighbors: list["Node"] | None = None def __post_init__(self) -> None: """ >>> Node(3).neighbors [] """ self.neighbors = self.neighbors or [] def __hash__(self) -> int: """ >>> hash(Node(3)) != 0 True """ return id(self) def clone_graph(node: Node | None) -> Node | None: """ This function returns a clone of a connected undirected graph. >>> clone_graph(Node(1)) Node(value=1, neighbors=[]) >>> clone_graph(Node(1, [Node(2)])) Node(value=1, neighbors=[Node(value=2, neighbors=[])]) >>> clone_graph(None) is None True """ if not node: return None originals_to_clones = {} # map nodes to clones stack = [node] while stack: original = stack.pop() if original in originals_to_clones: continue originals_to_clones[original] = Node(original.value) stack.extend(original.neighbors or []) for original, clone in originals_to_clones.items(): for neighbor in original.neighbors or []: cloned_neighbor = originals_to_clones[neighbor] if not clone.neighbors: clone.neighbors = [] clone.neighbors.append(cloned_neighbor) return originals_to_clones[node] if __name__ == "__main__": import doctest doctest.testmod()
Node
python
celery__celery
t/unit/utils/test_platforms.py
{ "start": 2161, "end": 2551 }
class ____: def test_raises_EBADF(self): with ignore_errno('EBADF'): exc = OSError() exc.errno = errno.EBADF raise exc def test_otherwise(self): with pytest.raises(OSError): with ignore_errno('EBADF'): exc = OSError() exc.errno = errno.ENOENT raise exc
test_ignore_errno
python
streamlit__streamlit
lib/streamlit/errors.py
{ "start": 20842, "end": 21406 }
class ____(LocalizableStreamlitException): """Exception raised when an invalid height value is provided.""" def __init__(self, height: Any, allow_content: bool = False) -> None: valid_values = "an integer (pixels) or 'stretch'" if allow_content: valid_values = "an integer (pixels), 'stretch', or 'content'" super().__init__( "Invalid height value: {height}. Height must be either {valid_values}.", height=repr(height), valid_values=valid_values, )
StreamlitInvalidHeightError
python
apache__airflow
dev/breeze/src/airflow_breeze/utils/parallel.py
{ "start": 3958, "end": 4203 }
class ____(AbstractProgressInfoMatcher): def get_best_matching_lines(self, output: Output) -> list[str] | None: last_lines, _ = get_last_lines_of_file(output.file_name, num_lines=1) return last_lines
ShowLastLineProgressMatcher
python
pytorch__pytorch
torch/_inductor/dependencies.py
{ "start": 28837, "end": 31333 }
class ____(DefaultHandler): symbols: OrderedSet[sympy.Symbol] def __init__(self, unbacked_only: bool = True) -> None: self.symbols = OrderedSet() self.get_symbols = free_unbacked_symbols if unbacked_only else free_symbols def _default(self, name: str, args: tuple[Any, ...], kwargs: dict[str, Any]) -> Any: for a in itertools.chain(args, kwargs.values()): if isinstance(a, (sympy.Expr, sympy.logic.boolalg.Boolean)): self.symbols |= self.get_symbols(a) def indirect_indexing( self, index_var: Any, size: Union[int, sympy.Expr], check: bool = True, wrap_neg: bool = True, ) -> sympy.Symbol: assert not isinstance(index_var, (sympy.Expr, sympy.logic.boolalg.Boolean)) self.symbols |= self.get_symbols(size) return sympy_index_symbol(f"({str(index_var)})") def frexp(self, x: Any) -> tuple[None, ...]: return (None,) * 2 def scan( self, dtypes: Any, combine_fn: Any, values: Sequence[Any] ) -> tuple[None, ...]: return (None,) * len(values) def sort( self, dtypes: Any, values: Sequence[Any], stable: Any, descending: Any ) -> tuple[None, ...]: return (None,) * len(values) def reduction( self, dtype: torch.dtype, src_dtype: torch.dtype, reduction_type: ReductionType, value: Union[None, tuple[None, ...]], ) -> Union[None, tuple[None, ...]]: num_values = reduction_num_outputs(reduction_type) return (None,) * num_values if num_values > 1 else None def masked(self, mask: Any, body: Callable[..., Any], other: Any) -> None: assert callable(body), "masked body must always be callable." # The body can make additional calls, for e.g. ops.indirect_indexing body() def extract_free_symbols( fn: Callable[..., Any], index: Sequence[sympy.Expr], rindex: Optional[Sequence[sympy.Expr]] = None, unbacked_only: bool = True, ) -> OrderedSet[sympy.Symbol]: from .ir import FlexibleLayout args = [index, rindex] if rindex is not None else [index] handler = FreeSymbolsOpsHandler(unbacked_only) # NB: I cargo culted the allow_indexing patch here, I don't understand why # people do this all over with ( V.set_ops_handler(handler), patch.object(FlexibleLayout, "allow_indexing", True), ): fn(*args) return handler.symbols
FreeSymbolsOpsHandler
python
joerick__pyinstrument
test/low_level/test_threaded.py
{ "start": 247, "end": 1226 }
class ____: def __init__(self, thread) -> None: self.thread = thread self.count = 0 def __call__(self, *args: Any, **kwds: Any) -> Any: assert self.thread is threading.current_thread() self.count += 1 def test_threaded(): # assert that each thread gets its own callbacks, and check that it # doesn't crash! counters: list[CallCounter | None] = [None for _ in range(10)] stop = False def profile_a_busy_wait(i): thread = threads[i] counter = CallCounter(thread) counters[i] = counter setstatprofile(counter, 0.001) while not stop: do_nothing() setstatprofile(None) threads = [threading.Thread(target=profile_a_busy_wait, args=(i,)) for i in range(10)] for thread in threads: thread.start() while not stop: stop = all(c is not None and c.count > 10 for c in counters) for thread in threads: thread.join()
CallCounter
python
dagster-io__dagster
python_modules/dagster/dagster/_utils/log.py
{ "start": 2082, "end": 2928 }
class ____( NamedTuple( "_StructuredLoggerMessage", [ ("name", str), ("message", str), ("level", int), ("meta", Mapping[str, object]), ("record", logging.LogRecord), ], ) ): def __new__( cls, name: str, message: str, level: int, meta: Mapping[str, object], record: logging.LogRecord, ): return super().__new__( cls, check.str_param(name, "name"), check.str_param(message, "message"), coerce_valid_log_level(level), check.mapping_param(meta, "meta"), check.inst_param(record, "record", logging.LogRecord), ) StructuredLoggerCallback: TypeAlias = Callable[[StructuredLoggerMessage], None]
StructuredLoggerMessage
python
facebook__pyre-check
source/interprocedural_analyses/taint/test/integration/constant_fields.py
{ "start": 238, "end": 1106 }
class ____(Enum): TRACKED_FIELD = "A" UNTRACKED_field = "B" untracked_field = "C" def tracked_index(): d = {} d[CustomEnum.TRACKED_FIELD] = _test_source() return d[CustomEnum.TRACKED_FIELD] def untracked_index_a(): d = {} d[CustomEnum.untracked_field] = _test_source() return d[CustomEnum.untracked_field] def untracked_index_b(): d = {} d[CustomEnum.UNTRACKED_field] = _test_source() return d[CustomEnum.UNTRACKED_field] CONSTANT_A = "A" CONSTANT_B = {"a": "b"} untracked_constant = "1" def tracked_constant_A(): d = {} d[CONSTANT_A] = _test_source() return d[CONSTANT_A] def tracked_constant_B(): d = {} d[CONSTANT_B] = _test_source() return d[CONSTANT_B] def test_untracked_constant(): d = {} d[untracked_constant] = _test_source() return d[untracked_constant]
CustomEnum
python
prabhupant__python-ds
data_structures/binary_trees/right_view.py
{ "start": 244, "end": 924 }
class ____: def __init__(self, val): self.val = val self.left = None self.right = None def right_view_util(root, max_level, level): if not root: return if max_level[0] < level: print(root.val) max_level[0] = level right_view_util(root.right, max_level, level+1) right_view_util(root.left, max_level, level+1) def right_view(root): max_level = [0] right_view_util(root, max_level, 1) root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) root.right.left = Node(6) root.right.right = Node(7) root.right.left.right = Node(8) right_view(root)
Node
python
dask__distributed
distributed/diagnostics/progress.py
{ "start": 4360, "end": 9063 }
class ____(Progress): """Progress variant that keeps track of different groups of keys See Progress for most details. Parameters ---------- func : Callable (deprecated) Function that splits keys. This defaults to ``key_split`` which aligns with naming conventions chosen in the dask project (tuples, hyphens, etc..) group_by : Callable | Literal["spans"] | Literal["prefix"], default: "prefix" How to group keys to display multiple bars. Defaults to "prefix", which uses ``key_split`` from dask project State ----- keys: dict Maps group name to set of not-yet-complete keys for that group all_keys: dict Maps group name to set of all keys for that group Examples -------- >>> split = lambda s: s.split('-')[0] >>> p = MultiProgress(['y-2'], func=split) # doctest: +SKIP >>> p.keys # doctest: +SKIP {'x': {'x-1', 'x-2', 'x-3'}, 'y': {'y-1', 'y-2'}} """ def __init__( self, keys, scheduler=None, *, func=None, group_by="prefix", minimum=0, dt=0.1, complete=False, ): if func is not None: warnings.warn( "`func` is deprecated, use `group_by`", category=DeprecationWarning ) group_by = func self.group_by = key_split if group_by in (None, "prefix") else group_by self.func = None name = f"multi-progress-{tokenize(keys, group_by, minimum, dt, complete)}" super().__init__( keys, scheduler, minimum=minimum, dt=dt, complete=complete, name=name ) async def setup(self): keys = self.keys while not keys.issubset(self.scheduler.tasks): await asyncio.sleep(0.05) tasks = [self.scheduler.tasks[k] for k in keys] self.keys = None self.scheduler.add_plugin(self) # subtle race condition here self.all_keys, errors = dependent_keys(tasks, complete=self.complete) if not self.complete: self.keys = self.all_keys.copy() else: self.keys, _ = dependent_keys(tasks, complete=False) self.all_keys.update(keys) self.keys |= errors & self.all_keys if not self.keys: self.stop(exception=None, key=None) if self.group_by == "spans": spans_ext = self.scheduler.extensions["spans"] span_defs = spans_ext.spans if spans_ext else None def group_key(k): span_id = self.scheduler.tasks[k].group.span_id span_name = ", ".join(span_defs[span_id].name) if span_defs else span_id return span_name, span_id group_keys = {k: group_key(k) for k in self.all_keys} self.func = group_keys.get elif self.group_by == "prefix": self.func = key_split else: self.func = self.group_by # Group keys by func name self.keys = valmap(set, groupby(self.func, self.keys)) self.all_keys = valmap(set, groupby(self.func, self.all_keys)) for k in self.all_keys: if k not in self.keys: self.keys[k] = set() for k in errors: self.transition( k, None, "erred", stimulus_id="multiprogress-setup", exception=True ) logger.debug("Set up Progress keys") def transition(self, key, start, finish, *args, **kwargs): if start == "processing" and finish == "memory": s = self.keys.get(self.func(key), None) if s and key in s: s.remove(key) if not self.keys or not any(self.keys.values()): self.stop() if finish == "erred": logger.debug("Progress sees task erred") k = self.func(key) if k in self.all_keys and key in self.all_keys[k]: self.stop(exception=kwargs.get("exception"), key=key) if finish == "forgotten": k = self.func(key) if k in self.all_keys and key in self.all_keys[k]: logger.debug("A task was cancelled (%s), stopping progress", key) self.stop(exception=True) def format_time(t): """Format seconds into a human readable form. >>> format_time(10.4) '10.4s' >>> format_time(1000.4) '16min 40.4s' >>> format_time(100000.4) '27hr 46min 40.4s' """ m, s = divmod(t, 60) h, m = divmod(m, 60) if h: return f"{h:2.0f}hr {m:2.0f}min {s:4.1f}s" elif m: return f"{m:2.0f}min {s:4.1f}s" else: return f"{s:4.1f}s"
MultiProgress
python
pytorch__pytorch
torch/_inductor/mkldnn_ir.py
{ "start": 22775, "end": 26776 }
class ____(ExternKernelAlloc): def __init__( self, layout, inputs, constant_args=(), ) -> None: """ Needs input/weight/output qparams if bias is not None - inputs = [x, x_scale, x_zp, w, w_scale, w_zp, accum, b] - const_args = [stride, padding, dilation, groups, o_scale, o_zp, output_dtype, accum_scale, accum_zp, binary_attr, alpha, unary_attr, unary_scalars, unary_algorithm] else - inputs = [x, x_scale, x_zp, w, w_scale, w_zp, accum] - const_args [b, stride, padding, dilation, groups, o_scale, o_zp, output_dtype, accum_scale, accum_zp, binary_attr, alpha, unary_attr, unary_scalars, unary_algorithm] """ self.device_type = get_device_type(inputs[0]) self.has_bias = len(inputs) == 8 self.idx_for_inplace_sum = 6 super().__init__( layout, inputs, constant_args, None, op_overload=torch.ops.onednn.qconv2d_pointwise.binary_tensor, cpp_kernel_name=( f"aoti_torch_{self.device_type}__qconv2d_pointwise_binary_tensor" ), ) def codegen(self, wrapper): wrapper.include_extra_header( f"torch/csrc/inductor/aoti_torch/c/shim_{self.device_type}.h" ) super().codegen(wrapper) if isinstance(self.layout, Layout): self.codegen_size_asserts(wrapper) def get_mutation_names(self) -> Sequence[str]: return [self.input_name(self.idx_for_inplace_sum)] def get_unbacked_symbol_defs(self) -> OrderedSet[sympy.Symbol]: return OrderedSet() @classmethod def create( cls, qx: "TensorBox", x_scale: "TensorBox", x_zero_point: "TensorBox", qw: "TensorBox", # packed_weight w_scale, w_zero_point, qaccum: "TensorBox", bias: "TensorBox", stride: list[int], padding: list[int], dilation: list[int], groups: int, output_scale: "TensorBox", output_zero_point: "TensorBox", output_dtype, accum_scale, accum_zero_point, binary_attr, alpha, unary_attr, unary_scalars, unary_algorithm, ): transposed = False output_padding = None ( inputs, constant_args, _kernel_layout, req_stride_order, qaccum, ) = _prepare_convolution_fusion_create( cls, qx, qw, bias, padding, stride, dilation, groups, transposed, output_padding, [x_scale, x_zero_point, w_scale, w_zero_point], qaccum, ) # swap padding and stride to align with functional conv arg order if bias is None: constant_args[1], constant_args[2] = constant_args[2], constant_args[1] else: constant_args[0], constant_args[1] = constant_args[1], constant_args[0] constant_args = constant_args + [ output_scale, output_zero_point, output_dtype, accum_scale, accum_zero_point, binary_attr, alpha, unary_attr, may_convert_to_optional(unary_scalars), unary_algorithm, ] assert binary_attr == "sum", ( "For now, only post op sum is supported in QConvPointWiseBinaryPT2E." ) V.graph.mark_buffer_mutated(qaccum.get_name()) packed = QConvPointWiseBinaryPT2E( layout=NoneLayout(device=qaccum.get_device()), inputs=inputs, constant_args=constant_args, ) # Return accum since it has been inplace changed. return packed.inputs[packed.idx_for_inplace_sum]
QConvPointWiseBinaryPT2E
python
google__pytype
pytype/types/classes.py
{ "start": 1047, "end": 1621 }
class ____: """Represents a class member variable. Members: name: field name typ: field python type init: Whether the field should be included in the generated __init__ kw_only: Whether the field is kw_only in the generated __init__ default: Default value kind: Kind of attribute Used in overlays that reflect on class attributes. """ name: str typ: Any init: bool kw_only: bool default: Any kind: str = "" # TODO(mdemello): Are these tied to the current implementation? init_type: Any = None pytd_const: Any = None
Attribute
python
getsentry__sentry
src/sentry/rules/conditions/base.py
{ "start": 464, "end": 797 }
class ____(RuleBase, abc.ABC): rule_type = "condition/event" @abc.abstractmethod def passes(self, event: GroupEvent, state: EventState) -> bool: pass def get_activity( self, start: datetime, end: datetime, limit: int ) -> Sequence[ConditionActivity]: raise NotImplementedError
EventCondition
python
pyparsing__pyparsing
pyparsing/core.py
{ "start": 153743, "end": 154905 }
class ____(PositionToken): """Matches if the current position is at the end of a :class:`Word`, and is not followed by any character in a given set of ``word_chars`` (default= ``printables``). To emulate the ``\b`` behavior of regular expressions, use ``WordEnd(alphanums)``. ``WordEnd`` will also match at the end of the string being parsed, or at the end of a line. """ def __init__(self, word_chars: str = printables, **kwargs) -> None: wordChars: str = deprecate_argument(kwargs, "wordChars", printables) wordChars = word_chars if wordChars == printables else wordChars super().__init__() self.wordChars = set(wordChars) self.skipWhitespace = False self.set_name("end of a word") def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: instrlen = len(instring) if instrlen > 0 and loc < instrlen: if ( instring[loc] in self.wordChars or instring[loc - 1] not in self.wordChars ): raise ParseException(instring, loc, self.errmsg, self) return loc, []
WordEnd
python
apache__airflow
providers/github/tests/unit/github/hooks/test_github.py
{ "start": 1174, "end": 5899 }
class ____: # TODO: Potential performance issue, converted setup_class to a setup_connections function level fixture @pytest.fixture(autouse=True) def setup_connections(self, create_connection_without_db): create_connection_without_db( Connection( conn_id="github_default", conn_type="github", password="my-access-token", host="https://mygithub.com/api/v3", ) ) create_connection_without_db( Connection( conn_id="github_app_conn", conn_type="github", host="https://mygithub.com/api/v3", extra={ "app_id": "123456", "installation_id": 654321, "key_path": "FAKE_PRIVATE_KEY.pem", "token_permissions": {"issues": "write", "pull_requests": "read"}, }, ) ) @patch( "airflow.providers.github.hooks.github.GithubClient", autospec=True, return_value=github_client_mock ) def test_github_client_connection(self, github_mock): github_hook = GithubHook() assert github_mock.called assert isinstance(github_hook.client, Mock) assert github_hook.client.name == github_mock.return_value.name @pytest.mark.parametrize("conn_id", ["github_default", "github_app_conn"]) @patch( "airflow.providers.github.hooks.github.open", new_callable=mock_open, read_data="FAKE_PRIVATE_KEY_CONTENT", ) def test_connection_success(self, mock_file, conn_id): hook = GithubHook(github_conn_id=conn_id) hook.client = Mock(spec=Github) hook.client.get_user.return_value = NamedUser.NamedUser status, msg = hook.test_connection() assert status is True assert msg == "Successfully connected to GitHub." @pytest.mark.parametrize("conn_id", ["github_default", "github_app_conn"]) @patch( "airflow.providers.github.hooks.github.open", new_callable=mock_open, read_data="FAKE_PRIVATE_KEY_CONTENT", ) def test_connection_failure(self, mock_file, conn_id): hook = GithubHook(github_conn_id=conn_id) hook.client.get_user = Mock( side_effect=BadCredentialsException( status=401, data={"message": "Bad credentials"}, headers={}, ) ) status, msg = hook.test_connection() assert status is False assert msg == '401 {"message": "Bad credentials"}' @pytest.mark.parametrize( ( "conn_id", "extra", "expected_error_message", ), [ # Wrong key file extension ( "invalid_key_path", {"app_id": "1", "installation_id": 1, "key_path": "wrong_ext.txt"}, "Unrecognised key file: expected a .pem private key", ), # Missing key_path ( "missing_key_path", {"app_id": "1", "installation_id": 1}, "No key_path provided for GitHub App authentication.", ), # installation_id is not integer ( "invalid_install_id", {"app_id": "1", "installation_id": "654321_string", "key_path": "key.pem"}, "The provided installation_id should be integer.", ), # app_id is not integer or string ( "invalid_app_id", {"app_id": ["123456_list"], "installation_id": 1, "key_path": "key.pem"}, "The provided app_id should be integer or string.", ), # No access token or authentication method provided ( "no_auth_conn", {}, "No access token or authentication method provided.", ), ], ) @patch("airflow.providers.github.hooks.github.GithubHook.get_connection") @patch( "airflow.providers.github.hooks.github.open", new_callable=mock_open, read_data="FAKE_PRIVATE_KEY_CONTENT", ) def test_get_conn_value_error_cases( self, mock_file, get_connection_mock, conn_id, extra, expected_error_message, ): mock_conn = Connection( conn_id=conn_id, conn_type="github", extra=extra, ) get_connection_mock.return_value = mock_conn with pytest.raises(ValueError, match=expected_error_message): GithubHook(github_conn_id=conn_id)
TestGithubHook
python
airbytehq__airbyte
airbyte-ci/connectors/pipelines/pipelines/airbyte_ci/connectors/migrate_to_manifest_only/declarative_component_schema.py
{ "start": 37372, "end": 37489 }
class ____(Enum): string = "string" number = "number" integer = "integer" boolean = "boolean"
ValueType
python
weaviate__weaviate-python-client
weaviate/rbac/models.py
{ "start": 2504, "end": 2644 }
class ____(TypedDict): userId: str roles: List[str] groups: List[str] active: bool dbUserType: str
WeaviateDBUserRoleNames
python
run-llama__llama_index
llama-index-core/llama_index/core/llama_dataset/evaluator_evaluation.py
{ "start": 11015, "end": 12255 }
class ____(BaseLlamaPredictionDataset): """Pairwise evaluation predictions dataset class.""" _prediction_type = PairwiseEvaluatorExamplePrediction def to_pandas(self) -> Any: """Create pandas dataframe.""" try: import pandas as pd except ImportError: raise ImportError( "pandas is required for this function. Please install it with `pip install pandas`." ) data: Dict[str, List] = { "feedback": [], "score": [], "ordering": [], } for prediction in self.predictions: if not isinstance(prediction, PairwiseEvaluatorExamplePrediction): raise ValueError( "PairwiseEvaluatorPredictionDataset can only contain PairwiseEvaluatorExamplePrediction instances." ) data["feedback"].append(prediction.feedback) data["score"].append(prediction.score) data["ordering"].append(str(prediction.evaluation_source)) return pd.DataFrame(data) @property def class_name(self) -> str: """Class name.""" return "PairwiseEvaluatorPredictionDataset"
PairwiseEvaluatorPredictionDataset
python
apache__airflow
providers/amazon/src/airflow/providers/amazon/aws/transfers/sql_to_s3.py
{ "start": 1410, "end": 1835 }
class ____(enum.Enum): """Possible file formats.""" CSV = enum.auto() JSON = enum.auto() PARQUET = enum.auto() FileOptions = namedtuple("FileOptions", ["mode", "suffix", "function"]) FILE_OPTIONS_MAP = { FILE_FORMAT.CSV: FileOptions("r+", ".csv", "to_csv"), FILE_FORMAT.JSON: FileOptions("r+", ".json", "to_json"), FILE_FORMAT.PARQUET: FileOptions("rb+", ".parquet", "to_parquet"), }
FILE_FORMAT
python
getsentry__sentry
src/sentry/seer/models.py
{ "start": 2703, "end": 2890 }
class ____(Exception): def __init__(self, message: str): self.message = message def __str__(self): return f"Seer permission error: {self.message}"
SeerPermissionError
python
gevent__gevent
src/gevent/events.py
{ "start": 11178, "end": 11286 }
class ____(GeventPatchEvent): """ Implementation of `IGeventDidPatchEvent`. """
GeventDidPatchEvent
python
pytorch__pytorch
torch/distributed/_composable/replicate_with_fsdp.py
{ "start": 1366, "end": 2587 }
class ____: """This has state shared across Replicate states.""" def __init__(self) -> None: # All Replicate states in the root state's module tree self.all_states: list[_ReplicateState] = [] # Iteration's forward root runs the once-per-forward logic; this root # may not be the overall root set by lazy initialization in cases where # only a submodule runs forward (e.g. encoder-only for eval) self.iter_forward_root: Optional[_ReplicateState] = None # Final callback should only be queued once per backward self.post_backward_final_callback_queued: bool = False # Whether to finalize backward in this backward's final callback self.is_last_backward: bool = True # Optional user-provided event recorded after optimizer for the # all-gather streams to wait on in the root pre-forward self.post_optim_event: Optional[torch.Event] = None def _get_module_replicate_state(module: nn.Module) -> Optional[_ReplicateState]: """Checks if module state is ReplicateState""" state = _get_module_state(module) if isinstance(state, _ReplicateState): return state return None
_ReplicateStateContext
python
jazzband__django-model-utils
tests/test_choices.py
{ "start": 6010, "end": 9580 }
class ____(TestCase, ChoicesTestsMixin[int]): def setUp(self) -> None: self.STATUS = Choices( (0, 'DRAFT', 'is draft'), (1, 'PUBLISHED', 'is published'), (2, 'DELETED', 'is deleted')) def test_iteration(self) -> None: self.assertEqual(tuple(self.STATUS), ( (0, 'is draft'), (1, 'is published'), (2, 'is deleted'), )) def test_reversed(self) -> None: self.assertEqual(tuple(reversed(self.STATUS)), ( (2, 'is deleted'), (1, 'is published'), (0, 'is draft'), )) def test_indexing(self) -> None: self.assertEqual(self.STATUS[1], 'is published') def test_getattr(self) -> None: self.assertEqual(self.STATUS.DRAFT, 0) def test_len(self) -> None: self.assertEqual(len(self.STATUS), 3) def test_repr(self) -> None: self.assertEqual(repr(self.STATUS), "Choices" + repr(( (0, 'DRAFT', 'is draft'), (1, 'PUBLISHED', 'is published'), (2, 'DELETED', 'is deleted'), ))) def test_contains_value(self) -> None: self.assertTrue(0 in self.STATUS) self.assertTrue(1 in self.STATUS) self.assertTrue(2 in self.STATUS) def test_doesnt_contain_value(self) -> None: self.assertFalse(3 in self.STATUS) def test_doesnt_contain_display_value(self) -> None: self.assertFalse('is draft' in self.STATUS) # type: ignore[operator] def test_doesnt_contain_python_attr(self) -> None: self.assertFalse('PUBLISHED' in self.STATUS) # type: ignore[operator] def test_equality(self) -> None: self.assertEqual(self.STATUS, Choices( (0, 'DRAFT', 'is draft'), (1, 'PUBLISHED', 'is published'), (2, 'DELETED', 'is deleted') )) def test_inequality(self) -> None: self.assertNotEqual(self.STATUS, [ (0, 'DRAFT', 'is draft'), (1, 'PUBLISHED', 'is published'), (2, 'DELETED', 'is deleted') ]) self.assertNotEqual(self.STATUS, Choices('DRAFT')) def test_composability(self) -> None: self.assertEqual( Choices( (0, 'DRAFT', 'is draft'), (1, 'PUBLISHED', 'is published') ) + Choices( (2, 'DELETED', 'is deleted'), ), self.STATUS ) self.assertEqual( Choices( (0, 'DRAFT', 'is draft'), (1, 'PUBLISHED', 'is published') ) + ( (2, 'DELETED', 'is deleted'), ), self.STATUS ) self.assertEqual( ( (0, 'DRAFT', 'is draft'), (1, 'PUBLISHED', 'is published') ) + Choices( (2, 'DELETED', 'is deleted'), ), self.STATUS ) def test_option_groups(self) -> None: if TYPE_CHECKING: c = Choices[int]( ('group a', [(1, 'ONE', 'one'), (2, 'TWO', 'two')]), ('group b', ((3, 'THREE', 'three'),)) ) else: c = Choices( ('group a', [(1, 'ONE', 'one'), (2, 'TWO', 'two')]), ['group b', ((3, 'THREE', 'three'),)] ) self.assertEqual( list(c), [ ('group a', [(1, 'one'), (2, 'two')]), ('group b', [(3, 'three')]), ], )
IdentifierChoicesTests
python
Pylons__pyramid
docs/tutorials/wiki2/src/authorization/tutorial/routes.py
{ "start": 1044, "end": 1545 }
class ____: def __init__(self, pagename): self.pagename = pagename def __acl__(self): return [ (Allow, 'role:editor', 'create'), (Allow, 'role:basic', 'create'), ] def page_factory(request): pagename = request.matchdict['pagename'] page = request.dbsession.scalars( sa.select(models.Page).where(models.Page.name == pagename) ).one_or_none() if page is None: raise HTTPNotFound return PageResource(page)
NewPage
python
tensorflow__tensorflow
tensorflow/python/framework/python_api_dispatcher_test.py
{ "start": 1410, "end": 10421 }
class ____(test_util.TensorFlowTestCase): def testInstanceChecker(self): t = constant_op.constant([1, 2, 3]) rt = ragged_factory_ops.constant([[1, 2], [3, 4, 5]]) with self.subTest('int checker'): int_checker = dispatch.MakeInstanceChecker(int) self.assertEqual(int_checker.Check(3), MATCH) self.assertEqual(int_checker.Check(3.0), NO_MATCH) self.assertEqual(int_checker.Check(t), NO_MATCH) self.assertEqual(int_checker.cost(), 1) self.assertEqual(repr(int_checker), '<PyTypeChecker int>') with self.subTest('tensor checker'): tensor_checker = dispatch.MakeInstanceChecker(tensor.Tensor) self.assertEqual(tensor_checker.Check(t), MATCH) self.assertEqual(tensor_checker.Check(3), NO_MATCH) self.assertEqual(tensor_checker.Check(3.0), NO_MATCH) self.assertEqual(tensor_checker.cost(), 1) self.assertEqual(repr(tensor_checker), '<PyTypeChecker Tensor>') with self.subTest('ragged checker'): ragged_checker = dispatch.MakeInstanceChecker(ragged_tensor.RaggedTensor) self.assertEqual(ragged_checker.Check(rt), MATCH_DISPATCHABLE) self.assertEqual(ragged_checker.Check(3), NO_MATCH) self.assertEqual(ragged_checker.Check(t), NO_MATCH) self.assertEqual(ragged_checker.cost(), 1) self.assertEqual(repr(ragged_checker), '<PyTypeChecker RaggedTensor>') with self.subTest('int or float checker'): int_checker = dispatch.MakeInstanceChecker(int, float) self.assertEqual(int_checker.Check(3), MATCH) self.assertEqual(int_checker.Check(3.0), MATCH) self.assertEqual(int_checker.Check(t), NO_MATCH) self.assertEqual(int_checker.cost(), 2) self.assertEqual(repr(int_checker), '<PyTypeChecker int, float>') with self.subTest('subclasses'): class A(object): pass class B(A): pass class C(object): pass class D(C, B): pass checker = dispatch.MakeInstanceChecker(A) self.assertEqual(checker.Check(A()), MATCH) self.assertEqual(checker.Check(B()), MATCH) self.assertEqual(checker.Check(C()), NO_MATCH) self.assertEqual(checker.Check(D()), MATCH) def testInstanceCheckerCache(self): checker = dispatch.MakeInstanceChecker(tuple) MyTuple = collections.namedtuple('MyTuple', ['a', 'b']) # Subclass of tuple self.assertEqual(checker.cache_size(), 0) self.assertEqual(checker.Check(5), NO_MATCH) self.assertEqual(checker.cache_size(), 1) # cache miss self.assertEqual(checker.Check(12), NO_MATCH) self.assertEqual(checker.cache_size(), 1) # cache hit self.assertEqual(checker.Check(1.3), NO_MATCH) self.assertEqual(checker.cache_size(), 2) # cache miss self.assertEqual(checker.Check([1]), NO_MATCH) self.assertEqual(checker.cache_size(), 3) # cache miss self.assertEqual(checker.Check((1,)), MATCH) self.assertEqual(checker.cache_size(), 4) # cache miss self.assertEqual(checker.Check((1, 2, 3)), MATCH) self.assertEqual(checker.cache_size(), 4) # cache hit self.assertEqual(checker.Check(MyTuple(1, 2)), MATCH) self.assertEqual(checker.cache_size(), 5) # cache miss self.assertEqual(checker.Check(MyTuple(3, 4)), MATCH) self.assertEqual(checker.cache_size(), 5) # cache miss self.assertEqual(checker.Check(()), MATCH) self.assertEqual(checker.cache_size(), 5) # cache hit def testUnionChecker(self): int_checker = dispatch.MakeInstanceChecker(int) float_checker = dispatch.MakeInstanceChecker(float) str_checker = dispatch.MakeInstanceChecker(str) none_checker = dispatch.MakeInstanceChecker(type(None)) tensor_checker = dispatch.MakeInstanceChecker(tensor.Tensor) ragged_checker = dispatch.MakeInstanceChecker(ragged_tensor.RaggedTensor) t = constant_op.constant([1, 2, 3]) rt = ragged_factory_ops.constant([[1, 2], [3, 4, 5]]) with self.subTest('Union[int, float, str]'): checker = dispatch.MakeUnionChecker( [int_checker, float_checker, str_checker]) self.assertEqual(checker.Check(3), MATCH) self.assertEqual(checker.Check(3.0), MATCH) self.assertEqual(checker.Check('x'), MATCH) self.assertEqual(checker.Check('x'), MATCH) self.assertEqual(checker.Check(None), NO_MATCH) self.assertEqual(checker.Check(t), NO_MATCH) self.assertEqual(checker.cost(), 4) self.assertEqual(repr(checker), '<PyTypeChecker Union[int, float, str]>') with self.subTest('Optional[int] (aka Union[int, None])'): checker = dispatch.MakeUnionChecker([int_checker, none_checker]) self.assertEqual(checker.Check(3), MATCH) self.assertEqual(checker.Check(3.0), NO_MATCH) self.assertEqual(checker.Check(None), MATCH) self.assertEqual(checker.Check(t), NO_MATCH) self.assertEqual(checker.cost(), 3) self.assertEqual(repr(checker), '<PyTypeChecker Union[int, NoneType]>') with self.subTest('Union[Tensor, RaggedTensor]'): checker = dispatch.MakeUnionChecker([tensor_checker, ragged_checker]) self.assertEqual(checker.Check(3), NO_MATCH) self.assertEqual(checker.Check(3.0), NO_MATCH) self.assertEqual(checker.Check(None), NO_MATCH) self.assertEqual(checker.Check(t), MATCH) self.assertEqual(checker.Check(rt), MATCH_DISPATCHABLE) self.assertEqual(checker.cost(), 3) self.assertEqual( repr(checker), '<PyTypeChecker Union[Tensor, RaggedTensor]>') def testListChecker(self): int_checker = dispatch.MakeInstanceChecker(int) tensor_checker = dispatch.MakeInstanceChecker(tensor.Tensor) ragged_checker = dispatch.MakeInstanceChecker(ragged_tensor.RaggedTensor) np_int_checker = dispatch.MakeInstanceChecker(np.integer) t = constant_op.constant([1, 2, 3]) rt = ragged_factory_ops.constant([[1, 2], [3, 4, 5]]) a = [1, 2, 3] b = ['a', 2, t] c = [t, t * 2, t - 2] d = [t, rt] e = [] f = (1, 2, 3) g = (rt,) h = {1: 2, 3: 4} i = np.array([1, 2, 3]) with self.subTest('List[int]'): checker = dispatch.MakeListChecker(int_checker) self.assertEqual(checker.Check(a), MATCH) self.assertEqual(checker.Check(b), NO_MATCH) self.assertEqual(checker.Check(c), NO_MATCH) self.assertEqual(checker.Check(d), NO_MATCH) self.assertEqual(checker.Check(e), MATCH) self.assertEqual(checker.Check(f), MATCH) self.assertEqual(checker.Check(iter(a)), NO_MATCH) self.assertEqual(checker.Check(iter(b)), NO_MATCH) self.assertEqual(checker.Check(reversed(e)), NO_MATCH) self.assertEqual(checker.Check(h), NO_MATCH) self.assertEqual(checker.Check(i), NO_MATCH) self.assertEqual(checker.cost(), 10) self.assertEqual(repr(checker), '<PyTypeChecker List[int]>') with self.subTest('List[Tensor]'): checker = dispatch.MakeListChecker(tensor_checker) self.assertEqual(checker.Check(a), NO_MATCH) self.assertEqual(checker.Check(b), NO_MATCH) self.assertEqual(checker.Check(c), MATCH) self.assertEqual(checker.Check(d), NO_MATCH) self.assertEqual(checker.Check(e), MATCH) self.assertEqual(checker.cost(), 10) self.assertEqual(repr(checker), '<PyTypeChecker List[Tensor]>') with self.subTest('List[Union[Tensor, RaggedTensor]]'): checker = dispatch.MakeListChecker( dispatch.MakeUnionChecker([tensor_checker, ragged_checker])) self.assertEqual(checker.Check(a), NO_MATCH) self.assertEqual(checker.Check(b), NO_MATCH) self.assertEqual(checker.Check(c), MATCH) self.assertEqual(checker.Check(d), MATCH_DISPATCHABLE) self.assertEqual(checker.Check(e), MATCH) self.assertEqual(checker.Check(f), NO_MATCH) self.assertEqual(checker.Check(g), MATCH_DISPATCHABLE) self.assertEqual(checker.cost(), 30) self.assertEqual( repr(checker), '<PyTypeChecker List[Union[Tensor, RaggedTensor]]>') with self.subTest('List[Union[int, np.integer]]'): # Note: np.integer is a subtype of int in *some* Python versions. checker = dispatch.MakeListChecker( dispatch.MakeUnionChecker([int_checker, np_int_checker])) self.assertEqual(checker.Check(a), MATCH) self.assertEqual(checker.Check(np.array(a)), NO_MATCH) self.assertEqual(checker.Check(np.array(a) * 1.5), NO_MATCH) def testRegisterDispatchableType(self): @dispatch.register_dispatchable_type class A(object): pass checker = dispatch.MakeInstanceChecker(A) self.assertEqual(checker.Check(A()), MATCH_DISPATCHABLE) def testRegisterDispatchableTypeError(self): with self.assertRaisesRegex(ValueError, 'Expected a type object'): dispatch.register_dispatchable_type(3) with self.assertRaisesRegex(ValueError, 'Type .* has already been registered'): dispatch.register_dispatchable_type(ragged_tensor.RaggedTensor) @test_util.run_all_in_graph_and_eager_modes
PythonTypeCheckerTest
python
django__django
django/db/models/fields/__init__.py
{ "start": 48002, "end": 48710 }
class ____(CharField): default_validators = [validators.validate_comma_separated_integer_list] description = _("Comma-separated integers") system_check_removed_details = { "msg": ( "CommaSeparatedIntegerField is removed except for support in " "historical migrations." ), "hint": ( "Use CharField(validators=[validate_comma_separated_integer_list]) " "instead." ), "id": "fields.E901", } def _to_naive(value): if timezone.is_aware(value): value = timezone.make_naive(value, datetime.UTC) return value def _get_naive_now(): return _to_naive(timezone.now())
CommaSeparatedIntegerField
python
allegroai__clearml
clearml/backend_api/services/v2_20/events.py
{ "start": 58223, "end": 63575 }
class ____(Request): """ Get the debug image events for the requested amount of iterations per each task :param metrics: List of metrics and variants :type metrics: Sequence[TaskMetricVariants] :param iters: Max number of latest iterations for which to return debug images :type iters: int :param navigate_earlier: If set then events are retreived from latest iterations to earliest ones. Otherwise from earliest iterations to the latest. The default is True :type navigate_earlier: bool :param refresh: If set then scroll will be moved to the latest iterations. The default is False :type refresh: bool :param scroll_id: Scroll ID of previous call (used for getting more results) :type scroll_id: str """ _service = "events" _action = "debug_images" _version = "2.20" _schema = { "definitions": { "task_metric_variants": { "properties": { "metric": {"description": "Metric name", "type": "string"}, "task": {"description": "Task ID", "type": "string"}, "variants": { "description": "Metric variant names", "items": {"type": "string"}, "type": "array", }, }, "required": ["task"], "type": "object", } }, "properties": { "iters": { "description": "Max number of latest iterations for which to return debug images", "type": "integer", }, "metrics": { "description": "List of metrics and variants", "items": {"$ref": "#/definitions/task_metric_variants"}, "type": "array", }, "navigate_earlier": { "description": "If set then events are retreived from latest iterations to earliest ones. Otherwise from earliest iterations to the latest. The default is True", "type": "boolean", }, "refresh": { "description": "If set then scroll will be moved to the latest iterations. The default is False", "type": "boolean", }, "scroll_id": { "description": "Scroll ID of previous call (used for getting more results)", "type": "string", }, }, "required": ["metrics"], "type": "object", } def __init__( self, metrics: List[Any], iters: Optional[int] = None, navigate_earlier: Optional[bool] = None, refresh: Optional[bool] = None, scroll_id: Optional[str] = None, **kwargs: Any ) -> None: super(DebugImagesRequest, self).__init__(**kwargs) self.metrics = metrics self.iters = iters self.navigate_earlier = navigate_earlier self.refresh = refresh self.scroll_id = scroll_id @schema_property("metrics") def metrics(self) -> List[Any]: return self._property_metrics @metrics.setter def metrics(self, value: List[Any]) -> None: if value is None: self._property_metrics = None return self.assert_isinstance(value, "metrics", (list, tuple)) if any((isinstance(v, dict) for v in value)): value = [TaskMetricVariants.from_dict(v) if isinstance(v, dict) else v for v in value] else: self.assert_isinstance(value, "metrics", TaskMetricVariants, is_array=True) self._property_metrics = value @schema_property("iters") def iters(self) -> Optional[int]: return self._property_iters @iters.setter def iters(self, value: Optional[int]) -> None: if value is None: self._property_iters = None return if isinstance(value, float) and value.is_integer(): value = int(value) self.assert_isinstance(value, "iters", six.integer_types) self._property_iters = value @schema_property("navigate_earlier") def navigate_earlier(self) -> Optional[bool]: return self._property_navigate_earlier @navigate_earlier.setter def navigate_earlier(self, value: Optional[bool]) -> None: if value is None: self._property_navigate_earlier = None return self.assert_isinstance(value, "navigate_earlier", (bool,)) self._property_navigate_earlier = value @schema_property("refresh") def refresh(self) -> Optional[bool]: return self._property_refresh @refresh.setter def refresh(self, value: Optional[bool]) -> None: if value is None: self._property_refresh = None return self.assert_isinstance(value, "refresh", (bool,)) self._property_refresh = value @schema_property("scroll_id") def scroll_id(self) -> Optional[str]: return self._property_scroll_id @scroll_id.setter def scroll_id(self, value: Optional[str]) -> None: if value is None: self._property_scroll_id = None return self.assert_isinstance(value, "scroll_id", six.string_types) self._property_scroll_id = value
DebugImagesRequest
python
pydata__xarray
xarray/core/indexing.py
{ "start": 23456, "end": 27678 }
class ____(ExplicitlyIndexedNDArrayMixin): """Wrap an array to make basic and outer indexing lazy.""" __slots__ = ("_shape", "array", "key") def __init__(self, array: Any, key: ExplicitIndexer | None = None): """ Parameters ---------- array : array_like Array like object to index. key : ExplicitIndexer, optional Array indexer. If provided, it is assumed to already be in canonical expanded form. """ if isinstance(array, type(self)) and key is None: # unwrap key = array.key # type: ignore[has-type, unused-ignore] array = array.array # type: ignore[has-type, unused-ignore] if key is None: key = BasicIndexer((slice(None),) * array.ndim) self.array = as_indexable(array) self.key = key shape: _Shape = () for size, k in zip(self.array.shape, self.key.tuple, strict=True): if isinstance(k, slice): shape += (len(range(*k.indices(size))),) elif isinstance(k, np.ndarray): shape += (k.size,) self._shape = shape def _updated_key(self, new_key: ExplicitIndexer) -> BasicIndexer | OuterIndexer: iter_new_key = iter(expanded_indexer(new_key.tuple, self.ndim)) full_key: list[OuterIndexerType] = [] for size, k in zip(self.array.shape, self.key.tuple, strict=True): if isinstance(k, integer_types): full_key.append(k) else: full_key.append(_index_indexer_1d(k, next(iter_new_key), size)) full_key_tuple = tuple(full_key) if all(isinstance(k, integer_types + (slice,)) for k in full_key_tuple): return BasicIndexer(cast(tuple[BasicIndexerType, ...], full_key_tuple)) return OuterIndexer(full_key_tuple) @property def shape(self) -> _Shape: return self._shape def get_duck_array(self): from xarray.backends.common import BackendArray if isinstance(self.array, BackendArray): array = self.array[self.key] else: array = apply_indexer(self.array, self.key) if isinstance(array, ExplicitlyIndexed): array = array.get_duck_array() return _wrap_numpy_scalars(array) async def async_get_duck_array(self): from xarray.backends.common import BackendArray if isinstance(self.array, BackendArray): array = await self.array.async_getitem(self.key) else: array = apply_indexer(self.array, self.key) if isinstance(array, ExplicitlyIndexed): array = await array.async_get_duck_array() return _wrap_numpy_scalars(array) def transpose(self, order): return LazilyVectorizedIndexedArray(self.array, self.key).transpose(order) def _oindex_get(self, indexer: OuterIndexer): return type(self)(self.array, self._updated_key(indexer)) def _vindex_get(self, indexer: VectorizedIndexer): array = LazilyVectorizedIndexedArray(self.array, self.key) return array.vindex[indexer] def __getitem__(self, indexer: ExplicitIndexer): self._check_and_raise_if_non_basic_indexer(indexer) return type(self)(self.array, self._updated_key(indexer)) def _vindex_set(self, key: VectorizedIndexer, value: Any) -> None: raise NotImplementedError( "Lazy item assignment with the vectorized indexer is not yet " "implemented. Load your data first by .load() or compute()." ) def _oindex_set(self, key: OuterIndexer, value: Any) -> None: full_key = self._updated_key(key) self.array.oindex[full_key] = value def __setitem__(self, key: BasicIndexer, value: Any) -> None: self._check_and_raise_if_non_basic_indexer(key) full_key = self._updated_key(key) self.array[full_key] = value def __repr__(self) -> str: return f"{type(self).__name__}(array={self.array!r}, key={self.key!r})" # keep an alias to the old name for external backends pydata/xarray#5111 LazilyOuterIndexedArray = LazilyIndexedArray
LazilyIndexedArray
python
getsentry__sentry
src/sentry/tagstore/base.py
{ "start": 947, "end": 9965 }
class ____(Service): __read_methods__ = frozenset( [ "get_tag_key", "get_tag_keys", "get_tag_values", "get_group_tag_key", "get_group_tag_keys", "get_group_list_tag_value", "get_generic_group_list_tag_value", "get_tag_keys_for_projects", "get_groups_user_counts", "get_generic_groups_user_counts", "get_group_tag_value_count", "get_top_group_tag_values", "get_first_release", "get_last_release", "get_release_tags", "get_group_tag_keys_and_top_values", "get_tag_value_paginator", "get_group_tag_value_paginator", "get_tag_value_paginator_for_projects", "get_group_tag_value_iter", ] ) __all__ = ( frozenset( [ "is_reserved_key", "prefix_reserved_key", "get_standardized_key", "get_tag_key_label", "get_tag_value_label", ] ) | __read_methods__ ) def is_reserved_key(self, key: str) -> bool: return key in INTERNAL_TAG_KEYS def prefix_reserved_key(self, key: str) -> str: # XXX(dcramer): kill sentry prefix for internal reserved tags if self.is_reserved_key(key): return f"sentry:{key}" else: return key def get_standardized_key(self, key: str) -> str: return key.split("sentry:", 1)[-1] def get_tag_key_label(self, key: str) -> str: return TAG_LABELS.get(key) or key.replace("_", " ").title() def get_tag_value_label(self, key: str, value) -> str: label = value if key == "sentry:user" and value: if value.startswith("id:"): label = value[len("id:") :] elif value.startswith("email:"): label = value[len("email:") :] elif value.startswith("username:"): label = value[len("username:") :] elif value.startswith("ip:"): label = value[len("ip:") :] return label def get_tag_key( self, project_id, environment_id, key: str, status=TagKeyStatus.ACTIVE, tenant_ids=None ): """ >>> get_tag_key(1, 2, "key1") """ raise NotImplementedError def get_tag_keys( self, project_id, environment_id, status=TagKeyStatus.ACTIVE, include_values_seen=False, denylist=None, tenant_ids=None, ): """ >>> get_tag_keys(1, 2) """ raise NotImplementedError def get_tag_keys_for_projects( self, projects, environments, start, end, dataset: Dataset = Dataset.Events, status=TagKeyStatus.ACTIVE, use_cache: bool = False, tenant_ids=None, ): """ >>> get_tag_key([1], [2]) """ raise NotImplementedError def get_tag_values(self, project_id, environment_id, key: str, tenant_ids=None): """ >>> get_tag_values(1, 2, "key1") """ raise NotImplementedError def get_group_tag_key( self, group, environment_id, key: str, tenant_ids=None, ): """ >>> get_group_tag_key(group, 3, "key1") """ raise NotImplementedError def get_group_tag_keys( self, group, environment_ids, limit=None, keys: list[str] | None = None, tenant_ids=None ): """ >>> get_group_tag_key(group, 2, [3]) """ raise NotImplementedError def get_group_list_tag_value( self, project_ids, group_id_list, environment_ids, key: str, value, tenant_ids=None ): """ >>> get_group_list_tag_value([1, 2], [1, 2, 3, 4, 5], [3], "key1", "value1") """ raise NotImplementedError def get_generic_group_list_tag_value( self, project_ids, group_id_list, environment_ids, key: str, value, tenant_ids=None ): raise NotImplementedError def get_tag_value_paginator( self, project_id, environment_id, key: str, start=None, end=None, query=None, order_by="-last_seen", tenant_ids=None, ): """ >>> get_tag_value_paginator(1, 2, 'environment', query='prod') """ raise NotImplementedError def get_tag_value_paginator_for_projects( self, projects, environments, key: str, start=None, end=None, dataset: Dataset | None = None, query=None, order_by="-last_seen", include_transactions: bool = False, include_sessions: bool = False, include_replays: bool = False, tenant_ids=None, ): """ Includes tags and also snuba columns, with the arrayjoin when they are nested. Also supports a query parameter to do a substring match on the tag/column values. >>> get_tag_value_paginator_for_projects([1], [2], 'environment', query='prod') """ raise NotImplementedError def get_group_tag_value_iter( self, group: Group, environment_ids: Sequence[int | None], key: str, orderby: str = "-first_seen", limit: int = 1000, offset: int = 0, tenant_ids: dict[str, int | str] | None = None, ) -> Sequence[GroupTagValue]: """ >>> get_group_tag_value_iter(group, 2, 3, 'environment') """ raise NotImplementedError def get_group_tag_value_paginator( self, group, environment_ids, key: str, order_by="-id", tenant_ids=None, ): """ >>> get_group_tag_value_paginator(group, 3, 'environment') """ raise NotImplementedError def get_groups_user_counts( self, project_ids: Sequence[int], group_ids: Sequence[int], environment_ids: Sequence[int] | None, start: datetime | None = None, end: datetime | None = None, tenant_ids: dict[str, str | int] | None = None, referrer: str = "tagstore.get_groups_user_counts", ) -> dict[int, int]: """ >>> get_groups_user_counts([1, 2], [2, 3], [4, 5]) `start` and `end` are only used by the snuba backend """ raise NotImplementedError def get_generic_groups_user_counts( self, project_ids: Sequence[int], group_ids: Sequence[int], environment_ids: Sequence[int] | None, start: datetime | None = None, end: datetime | None = None, tenant_ids: dict[str, str | int] | None = None, referrer: str = "tagstore.get_generic_groups_user_counts", ) -> dict[int, int]: raise NotImplementedError def get_group_tag_value_count( self, group, environment_id, key: str, tenant_ids=None, ): """ >>> get_group_tag_value_count(group, 3, 'key1') """ raise NotImplementedError def get_top_group_tag_values( self, group, environment_id, key: str, limit=TOP_VALUES_DEFAULT_LIMIT, tenant_ids=None, ): """ >>> get_top_group_tag_values(group, 3, 'key1') """ raise NotImplementedError def get_first_release(self, project_id, group_id): """ >>> get_first_release(1, 2) """ raise NotImplementedError def get_last_release(self, project_id, group_id): """ >>> get_last_release(1, 2) """ raise NotImplementedError def get_release_tags(self, organization_id, project_ids, environment_id, versions): """ >>> get_release_tags([1, 2], 3, ["1", "2"]) """ raise NotImplementedError def get_group_tag_keys_and_top_values( self, group, environment_ids, keys: list[str] | None = None, value_limit=TOP_VALUES_DEFAULT_LIMIT, tenant_ids=None, **kwargs, ): # only the snuba backend supports multi env, and that overrides this method if environment_ids and len(environment_ids) > 1: environment_ids = environment_ids[:1] # If keys is unspecified, we will grab all tag keys for this group. tag_keys = self.get_group_tag_keys(group, environment_ids, keys=keys, tenant_ids=tenant_ids) environment_id = environment_ids[0] if environment_ids else None for tk in tag_keys: tk.top_values = self.get_top_group_tag_values( group, environment_id, tk.key, limit=value_limit ) if tk.count is None: tk.count = self.get_group_tag_value_count(group, environment_id, tk.key) return tag_keys
TagStorage
python
dagster-io__dagster
python_modules/libraries/dagster-airbyte/dagster_airbyte/resources.py
{ "start": 32896, "end": 40715 }
class ____(BaseAirbyteWorkspace): """This resource allows users to programatically interface with the Airbyte Cloud REST API to launch syncs and monitor their progress for a given Airbyte Cloud workspace. **Examples:** .. code-block:: python from dagster_airbyte import AirbyteCloudWorkspace, build_airbyte_assets_definitions import dagster as dg airbyte_workspace = AirbyteCloudWorkspace( workspace_id=dg.EnvVar("AIRBYTE_CLOUD_WORKSPACE_ID"), client_id=dg.EnvVar("AIRBYTE_CLOUD_CLIENT_ID"), client_secret=dg.EnvVar("AIRBYTE_CLOUD_CLIENT_SECRET"), ) all_airbyte_assets = build_airbyte_assets_definitions(workspace=airbyte_workspace) defs = dg.Definitions( assets=all_airbyte_assets, resources={"airbyte": airbyte_workspace}, ) """ rest_api_base_url: ClassVar[str] = AIRBYTE_CLOUD_REST_API_BASE_URL configuration_api_base_url: ClassVar[str] = AIRBYTE_CLOUD_CONFIGURATION_API_BASE_URL workspace_id: str = Field(..., description="The Airbyte workspace ID") client_id: str = Field(..., description="The Airbyte client ID.") client_secret: str = Field(..., description="The Airbyte client secret.") @cached_method def get_client(self) -> AirbyteClient: return AirbyteClient( rest_api_base_url=self.rest_api_base_url, configuration_api_base_url=self.configuration_api_base_url, workspace_id=self.workspace_id, client_id=self.client_id, client_secret=self.client_secret, request_max_retries=self.request_max_retries, request_retry_delay=self.request_retry_delay, request_timeout=self.request_timeout, max_items_per_page=self.max_items_per_page, poll_interval=self.poll_interval, poll_timeout=self.poll_timeout, cancel_on_termination=self.cancel_on_termination, poll_previous_running_sync=self.poll_previous_running_sync, ) @public @beta def load_airbyte_asset_specs( workspace: BaseAirbyteWorkspace, dagster_airbyte_translator: Optional[DagsterAirbyteTranslator] = None, connection_selector_fn: Optional[Callable[[AirbyteConnection], bool]] = None, ) -> Sequence[AssetSpec]: """Returns a list of AssetSpecs representing the Airbyte content in the workspace. Args: workspace (BaseAirbyteWorkspace): The Airbyte workspace to fetch assets from. dagster_airbyte_translator (Optional[DagsterAirbyteTranslator], optional): The translator to use to convert Airbyte content into :py:class:`dagster.AssetSpec`. Defaults to :py:class:`DagsterAirbyteTranslator`. connection_selector_fn (Optional[Callable[[AirbyteConnection], bool]]): A function that allows for filtering which Airbyte connection assets are created for. Returns: List[AssetSpec]: The set of assets representing the Airbyte content in the workspace. Examples: Loading the asset specs for a given Airbyte workspace: .. code-block:: python from dagster_airbyte import AirbyteWorkspace, load_airbyte_asset_specs import dagster as dg airbyte_workspace = AirbyteWorkspace( workspace_id=dg.EnvVar("AIRBYTE_WORKSPACE_ID"), client_id=dg.EnvVar("AIRBYTE_CLIENT_ID"), client_secret=dg.EnvVar("AIRBYTE_CLIENT_SECRET"), ) airbyte_specs = load_airbyte_asset_specs(airbyte_workspace) dg.Definitions(assets=airbyte_specs) Filter connections by name: .. code-block:: python from dagster_airbyte import AirbyteWorkspace, load_airbyte_asset_specs import dagster as dg airbyte_workspace = AirbyteWorkspace( workspace_id=dg.EnvVar("AIRBYTE_WORKSPACE_ID"), client_id=dg.EnvVar("AIRBYTE_CLIENT_ID"), client_secret=dg.EnvVar("AIRBYTE_CLIENT_SECRET"), ) airbyte_specs = load_airbyte_asset_specs( workspace=airbyte_workspace, connection_selector_fn=lambda connection: connection.name in ["connection1", "connection2"] ) dg.Definitions(assets=airbyte_specs) """ dagster_airbyte_translator = dagster_airbyte_translator or DagsterAirbyteTranslator() with workspace.process_config_and_initialize_cm_cached() as initialized_workspace: return [ spec.merge_attributes( metadata={DAGSTER_AIRBYTE_TRANSLATOR_METADATA_KEY: dagster_airbyte_translator} ) for spec in check.is_list( AirbyteWorkspaceDefsLoader( workspace=initialized_workspace, translator=dagster_airbyte_translator, connection_selector_fn=connection_selector_fn, ) .build_defs() .assets, AssetSpec, ) ] @public @superseded(additional_warn_text="Use load_airbyte_asset_specs instead.") def load_airbyte_cloud_asset_specs( workspace: AirbyteCloudWorkspace, dagster_airbyte_translator: Optional[DagsterAirbyteTranslator] = None, connection_selector_fn: Optional[Callable[[AirbyteConnection], bool]] = None, ) -> Sequence[AssetSpec]: """Returns a list of AssetSpecs representing the Airbyte content in the workspace. Args: workspace (AirbyteCloudWorkspace): The Airbyte Cloud workspace to fetch assets from. dagster_airbyte_translator (Optional[DagsterAirbyteTranslator], optional): The translator to use to convert Airbyte content into :py:class:`dagster.AssetSpec`. Defaults to :py:class:`DagsterAirbyteTranslator`. connection_selector_fn (Optional[Callable[[AirbyteConnection], bool]]): A function that allows for filtering which Airbyte connection assets are created for. Returns: List[AssetSpec]: The set of assets representing the Airbyte content in the workspace. Examples: Loading the asset specs for a given Airbyte Cloud workspace: .. code-block:: python from dagster_airbyte import AirbyteCloudWorkspace, load_airbyte_cloud_asset_specs import dagster as dg airbyte_cloud_workspace = AirbyteCloudWorkspace( workspace_id=dg.EnvVar("AIRBYTE_CLOUD_WORKSPACE_ID"), client_id=dg.EnvVar("AIRBYTE_CLOUD_CLIENT_ID"), client_secret=dg.EnvVar("AIRBYTE_CLOUD_CLIENT_SECRET"), ) airbyte_cloud_specs = load_airbyte_cloud_asset_specs(airbyte_cloud_workspace) dg.Definitions(assets=airbyte_cloud_specs) Filter connections by name: .. code-block:: python from dagster_airbyte import AirbyteCloudWorkspace, load_airbyte_cloud_asset_specs import dagster as dg airbyte_cloud_workspace = AirbyteCloudWorkspace( workspace_id=dg.EnvVar("AIRBYTE_CLOUD_WORKSPACE_ID"), client_id=dg.EnvVar("AIRBYTE_CLOUD_CLIENT_ID"), client_secret=dg.EnvVar("AIRBYTE_CLOUD_CLIENT_SECRET"), ) airbyte_cloud_specs = load_airbyte_cloud_asset_specs( workspace=airbyte_cloud_workspace, connection_selector_fn=lambda connection: connection.name in ["connection1", "connection2"] ) dg.Definitions(assets=airbyte_cloud_specs) """ return load_airbyte_asset_specs( workspace=workspace, dagster_airbyte_translator=dagster_airbyte_translator, connection_selector_fn=connection_selector_fn, ) @record
AirbyteCloudWorkspace
python
jpadilla__pyjwt
jwt/exceptions.py
{ "start": 1034, "end": 1184 }
class ____(InvalidTokenError): """Raised when a token's ``nbf`` or ``iat`` claims represent a time in the future""" pass
ImmatureSignatureError
python
apache__airflow
providers/google/src/airflow/providers/google/marketing_platform/operators/campaign_manager.py
{ "start": 4806, "end": 9629 }
class ____(BaseOperator): """ Retrieves a report and uploads it to GCS bucket. .. seealso:: Check official API docs: `https://developers.google.com/doubleclick-advertisers/rest/v4/reports/get` .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:GoogleCampaignManagerDownloadReportOperator` :param profile_id: The DFA user profile ID. :param report_id: The ID of the report. :param file_id: The ID of the report file. :param bucket_name: The bucket to upload to. :param report_name: The report name to set when uploading the local file. :param gzip: Option to compress local file or file data for upload :param chunk_size: File will be downloaded in chunks of this many bytes. :param api_version: The version of the api that will be requested, for example 'v4'. :param gcp_conn_id: The connection ID to use when fetching connection info. :param impersonation_chain: Optional service account to impersonate using short-term credentials, or chained list of accounts required to get the access_token of the last account in the list, which will be impersonated in the request. If set as a string, the account must grant the originating account the Service Account Token Creator IAM role. If set as a sequence, the identities from the list must grant Service Account Token Creator IAM role to the directly preceding identity, with first account from the list granting this role to the originating account (templated). """ template_fields: Sequence[str] = ( "profile_id", "report_id", "file_id", "bucket_name", "report_name", "chunk_size", "api_version", "gcp_conn_id", "impersonation_chain", ) def __init__( self, *, profile_id: str, report_id: str, file_id: str, bucket_name: str, report_name: str | None = None, gzip: bool = True, chunk_size: int = 10 * 1024 * 1024, api_version: str = "v4", gcp_conn_id: str = "google_cloud_default", impersonation_chain: str | Sequence[str] | None = None, **kwargs, ) -> None: super().__init__(**kwargs) self.profile_id = profile_id self.report_id = report_id self.file_id = file_id self.api_version = api_version self.chunk_size = chunk_size self.gzip = gzip self.bucket_name = bucket_name self.report_name = report_name self.gcp_conn_id = gcp_conn_id self.impersonation_chain = impersonation_chain def _resolve_file_name(self, name: str) -> str: csv = ".csv" gzip = ".gz" if not name.endswith(csv): name += csv if self.gzip: name += gzip return name @staticmethod def _set_bucket_name(name: str) -> str: bucket = name if not name.startswith("gs://") else name[5:] return bucket.strip("/") def execute(self, context: Context) -> None: hook = GoogleCampaignManagerHook( gcp_conn_id=self.gcp_conn_id, api_version=self.api_version, impersonation_chain=self.impersonation_chain, ) gcs_hook = GCSHook( gcp_conn_id=self.gcp_conn_id, impersonation_chain=self.impersonation_chain, ) # Get name of the report report = hook.get_report(file_id=self.file_id, profile_id=self.profile_id, report_id=self.report_id) report_name = self.report_name or report.get("fileName", str(uuid.uuid4())) report_name = self._resolve_file_name(report_name) # Download the report self.log.info("Starting downloading report %s", self.report_id) request = hook.get_report_file( profile_id=self.profile_id, report_id=self.report_id, file_id=self.file_id ) with tempfile.NamedTemporaryFile() as temp_file: downloader = http.MediaIoBaseDownload(fd=temp_file, request=request, chunksize=self.chunk_size) download_finished = False while not download_finished: _, download_finished = downloader.next_chunk() temp_file.flush() # Upload the local file to bucket bucket_name = self._set_bucket_name(self.bucket_name) gcs_hook.upload( bucket_name=bucket_name, object_name=report_name, gzip=self.gzip, filename=temp_file.name, mime_type="text/csv", ) context["task_instance"].xcom_push(key="report_name", value=report_name)
GoogleCampaignManagerDownloadReportOperator
python
joke2k__faker
faker/providers/color/hy_AM/__init__.py
{ "start": 80, "end": 6419 }
class ____(ColorProvider): """Implement color provider for ``hy_AM`` locale.""" all_colors = OrderedDict( ( ("Ալիսի կապույտ", "#F0F8FF"), ("Անանուխի կրեմ", "#F5FFFA"), ("Անտառային կանաչ", "#228B22"), ("Արծաթագույն", "#C0C0C0"), ("Արքայական կապույտ", "#4169E1"), ("Բաց դեղին", "#FFFFE0"), ("Բաց դեղնաոսկեգույն", "#FAFAD2"), ("Բաց երկնագույն", "#87CEFA"), ("Բաց ծովային կանաչ", "#20B2AA"), ("Բաց կաթնագույն", "#FFFFF0"), ("Բաց կանաչ", "#90EE90"), ("Բաց կապույտ", "#ADD8E6"), ("Բաց կապտականաչ", "#E0FFFF"), ("Բաց կորալ", "#F08080"), ("Բաց մանուշակագույն", "#EE82EE"), ("Բաց մոխրագույն թերթաքար", "#778899"), ("Բաց մոխրագույն", "#D3D3D3"), ("Բաց նշագույն", "#FFEBCD"), ("Բաց պողպատե կապույտ", "#B0C4DE"), ("Բաց սաղմոնագույն", "#FFA07A"), ("Բաց վարդագույն", "#FFB6C1"), ("Բեժ", "#F5F5DC"), ("Բոսորագույն", "#DC143C"), ("Գարնանային կանաչ", "#00FF7F"), ("Գեյնսբորրո", "#DCDCDC"), ("Գունատ կանաչ", "#98FB98"), ("Գունատ կարմիր մանուշակագույն", "#DB7093"), ("Գունատ ոսկեգույն", "#EEE8AA"), ("Գունատ փիրուզագույն", "#AFEEEE"), ("Գրասենյակային կանաչ", "#008000"), ("Դարչնագույն ավազ", "#F4A460"), ("Դարչնագույն", "#964B00"), ("Դեղին", "#FFFF00"), ("Դեղձի կրեմ", "#FFDAB9"), ("Դեղնականաչ", "#9ACD3"), ("Դոդջերս կապույտ", "#1E90FF"), ("Եգիպտացորենի մազիկներ", "#FFF8DC"), ("Երկնագույն մառախուղ", "#F0FFFF"), ("Երկնագույն", "#87CEEB"), ("Զինվորական կանաչ", "#6B8E23"), ("Թամբի դարչնագույն", "#8B4513"), ("Թեժ վարդագույն", "#FF69B4"), ("Թուխ", "#D2B48C"), ("Ինդիգո", "#4B0082"), ("Լայմի կանաչ", "#32CD32"), ("Լավանդ", "#E6E6FA"), ("Լոլիկ", "#FF6347"), ("Խակի", "#F0E68C"), ("Խոլորձագույն", "#DA70D6"), ("Ծխագույն", "#F5F5F5"), ("Ծովախեցի", "#FFF5EE"), ("Ծովակնագույն", "#7FFFD4"), ("Ծովային կանաչ", "#2E8B57"), ("Կադետների կապույտ", "#5F9EA0"), ("Կաթնագույն", "#FFFAF0"), ("Կակաոյի դարչնագույն", "#D2691E"), ("Կանաչ", "#00FF00"), ("Կանաչադեղին", "#ADFF2F"), ("Կապույտ թերթաքար", "#6A5ACD"), ("Կապույտ մանուշակագույն", "#8A2BE2"), ("Կապույտ փոշի", "#B0E0E6"), ("Կապույտ", "#0000FF"), ("Կապտականաչ", "#00FFFF"), ("Կարմիր դարչնագույն", "#A52A2A"), ("Կարմիր լավանդ", "#FFF0F5"), ("Կարմիր մանուշակագույն", "#C71585"), ("Կարմիր", "#FF0000"), ("Կեսգիշերային կապույտ", "#191970"), ("Կիտրոնի շիֆոն", "#FFFACD"), ("Կորալ", "#FF7F50"), ("Հարած պապայա", "#FFEFD5"), ("Հին ժանյակ", "#FDF5E6"), ("Հնաոճ սպիտակ", "#FAEBD7"), ("Հնդկական կարմիր", "#CD5C5C"), ("Հրակայուն աղյուս", "#B22222"), ("Ձիթապտղի գույն", "#808000"), ("Ձյունաճերմակ", "#FFFAFA"), ("Մանուշակագույն", "#800080"), ("Մեղրացող սեխ", "#F0FFF0"), ("Միջին գարնանային կանաչ", "#00FA9A"), ("Միջին խոլորձագույն", "#BA55D3"), ("Միջին ծովակնագույն", "#66CDAA"), ("Միջին ծովային կանաչ", "#3CB371"), ("Միջին կապույտ թերթաքար", "#7B68EE"), ("Միջին կապույտ", "#0000CD"), ("Միջին կապտականաչ", "#9370DB"), ("Միջին փիրուզագույն", "#48D1CC"), ("Մոխրագույն թերթաքար", "#708090"), ("Մոխրագույն", "#808080"), ("Մոկասին", "#FFE4B5"), ("Մուգ երկնագույն", "#00BFFF"), ("Մուգ խակի", "#BDB76B"), ("Մուգ խոլորձագույն", "#9932CC"), ("Մուգ ծովային կանաչ", "#8FBC8F"), ("Մուգ կանաչ", "#006400"), ("Մուգ կապույտ թերթաքար", "#483D8B"), ("Մուգ կապույտ", "#00008B"), ("Մուգ կապտականաչ", "#008080"), ("Մուգ կարմիր", "#8B0000"), ("Մուգ ձիթապտղի կանաչ", "#556B2F"), ("Մուգ մանուշակագույն", "#9400D3"), ("Մուգ մոխրագույն թերթաքար", "#2F4F4F"), ("Մուգ մոխրագույն", "#696969"), ("Մուգ մոխրագույն", "#A9A9A9"), ("Մուգ նարնջագույն", "#FF8C00"), ("Մուգ ոսկեգույն", "#B8860B"), ("Մուգ սաղմոնագույն", "#E9967A"), ("Մուգ վառ մանուշակագույն", "#8B008B"), ("Մուգ վարդագույն", "#FF1493"), ("Մուգ փիրուզագույն", "#00CED1"), ("Նավահո սպիտակ", "#FFDEAD"), ("Նավատորմի կապույտ", "#000080"), ("Նարնջագույն կարմիր", "#FF4500"), ("Նարնջագույն", "#FFA500"), ("Նշագույն", "#FFE4C4"), ("Շագանակագույն", "#800000"), ("Շարտրուզ", "#7FFF00"), ("Ոսկեգույն ձող", "#DAA520"), ("Ոսկեգույն", "#FFD700"), ("Պերու", "#CD853F"), ("Պողպատե կապույտ", "#4682B4"), ("Սալոր", "#DDA0DD"), ("Սաղմոնագույն", "#FA8072"), ("Սիենա", "#A0522D"), ("Սիզամարգի կանաչ", "#7CFC00"), ("Սպիտակ ստվեր", "#F8F8FF"), ("Սպիտակ", "#FFFFFF"), ("Սև", "#000000"), ("Վառ մանուշակագույն", "#FF00FF"), ("Վարդագույն", "#FFC0CB"), ("Վարդագույն", "#FFE4E1"), ("Վարդադարչնագույն", "#BC8F8F"), ("Վուշ", "#FAF0E6"), ("Տատասկ", "#D8BFD8"), ("Տերեփուկի կապույտ", "#6495ED"), ("Ցորենագույն", "#F5DEB3"), ("Փիրուզագույն", "#40E0D0"), ("Փխրուն փայտ", "#DEB887"), ) ) safe_colors = ( "սև", "շագանակագույն", "կանաչ", "նավատորմի կապույտ", "ձիթապտղի գույն", "մանուշակագույն", "մուգ կապտականաչ", "լայմ", "կապույտ", "արծաթագույն", "մոխրագույն", "դեղին", "վառ մանուշակագույն", "կապտականաչ", "սպիտակ", )
Provider
python
tensorflow__tensorflow
tensorflow/python/ops/ragged/ragged_expand_dims_op_test.py
{ "start": 1040, "end": 4725 }
class ____(test_util.TensorFlowTestCase, parameterized.TestCase): # An example 4-d ragged tensor with shape [3, (D2), (D3), 2], and the # expected result calling for expand_dims on each axis. c.f. the table of # expected result shapes in the ragged_array_ops.expand_dims docstring. EXAMPLE4D = [[[[1, 1], [2, 2]], [[3, 3]]], [], [[], [[4, 4], [5, 5], [6, 6]]]] # pyformat: disable EXAMPLE4D_EXPAND_AXIS = { 0: [EXAMPLE4D], 1: [[d0] for d0 in EXAMPLE4D], 2: [[[d1] for d1 in d0] for d0 in EXAMPLE4D], 3: [[[[d2] for d2 in d1] for d1 in d0] for d0 in EXAMPLE4D], 4: [[[[[d3] for d3 in d2] for d2 in d1] for d1 in d0] for d0 in EXAMPLE4D] } @parameterized.parameters([ #========================================================================= # Docstring examples: 2D Ragged Inputs dict(rt_input=[[1, 2], [3]], axis=0, expected=[[[1, 2], [3]]], expected_shape=[1, 2, None]), dict(rt_input=[[1, 2], [3]], axis=1, expected=[[[1, 2]], [[3]]], expected_shape=[2, 1, None]), dict(rt_input=[[1, 2], [3]], axis=2, expected=[[[1], [2]], [[3]]], expected_shape=[2, None, 1]), #========================================================================= # 2D Tensor Inputs dict(rt_input=[[1, 2], [3, 4], [5, 6]], ragged_rank=0, axis=0, expected=[[[1, 2], [3, 4], [5, 6]]], expected_shape=[1, 3, 2]), dict(rt_input=[[1, 2], [3, 4], [5, 6]], ragged_rank=0, axis=1, expected=[[[1, 2]], [[3, 4]], [[5, 6]]], expected_shape=[3, 1, 2]), dict(rt_input=[[1, 2], [3, 4], [5, 6]], ragged_rank=0, axis=2, expected=[[[1], [2]], [[3], [4]], [[5], [6]]], expected_shape=[3, 2, 1]), #========================================================================= # 4D Ragged Inputs: [3, (D2), (D3), 2] # c.f. the table of expected result shapes in the expand_dims docstring. dict(rt_input=EXAMPLE4D, ragged_rank=2, axis=0, expected=EXAMPLE4D_EXPAND_AXIS[0], expected_shape=[1, 3, None, None, 2]), dict(rt_input=EXAMPLE4D, ragged_rank=2, axis=1, expected=EXAMPLE4D_EXPAND_AXIS[1], expected_shape=[3, 1, None, None, 2]), dict(rt_input=EXAMPLE4D, ragged_rank=2, axis=2, expected=EXAMPLE4D_EXPAND_AXIS[2], expected_shape=[3, None, 1, None, 2]), dict(rt_input=EXAMPLE4D, ragged_rank=2, axis=3, expected=EXAMPLE4D_EXPAND_AXIS[3], expected_shape=[3, None, None, 1, 2]), dict(rt_input=EXAMPLE4D, ragged_rank=2, axis=4, expected=EXAMPLE4D_EXPAND_AXIS[4], expected_shape=[3, None, None, 2, 1]), ]) # pyformat: disable def testRaggedExpandDims(self, rt_input, axis, expected, ragged_rank=None, expected_shape=None): rt = ragged_factory_ops.constant(rt_input, ragged_rank=ragged_rank) expanded = ragged_array_ops.expand_dims(rt, axis=axis) self.assertEqual(expanded.shape.ndims, rt.shape.ndims + 1) if expected_shape is not None: self.assertEqual(expanded.shape.as_list(), expected_shape) self.assertAllEqual(expanded, expected) if __name__ == '__main__': googletest.main()
RaggedExpandDimsOpTest
python
kamyu104__LeetCode-Solutions
Python/pancake-sorting.py
{ "start": 3389, "end": 3906 }
class ____(object): def pancakeSort(self, A): """ :type A: List[int] :rtype: List[int] """ def reverse(l, begin, end): for i in xrange((end-begin) // 2): l[begin+i], l[end-1-i] = l[end-1-i], l[begin+i] result = [] for n in reversed(xrange(1, len(A)+1)): i = A.index(n) reverse(A, 0, i+1) result.append(i+1) reverse(A, 0, n) result.append(n) return result
Solution3
python
automl__auto-sklearn
autosklearn/pipeline/components/base.py
{ "start": 2733, "end": 5466 }
class ____(BaseEstimator): @staticmethod def get_properties(dataset_properties=None): """Get the properties of the underlying algorithm. Find more information at :ref:`get_properties` Parameters ---------- dataset_properties : dict, optional (default=None) Returns ------- dict """ raise NotImplementedError() @staticmethod def get_hyperparameter_search_space( feat_type: Optional[FEAT_TYPE_TYPE] = None, dataset_properties=None ): """Return the configuration space of this classification algorithm. Parameters ---------- feat_type : FEAT_TYPE_TYPE (default=None) dataset_properties : dict, optional (default=None) Returns ------- Configspace.configuration_space.ConfigurationSpace The configuration space of this classification algorithm. """ raise NotImplementedError() def fit(self, X, y): """The fit function calls the fit function of the underlying scikit-learn model and returns `self`. Parameters ---------- X : array-like, shape = (n_samples, n_features) Training data y : array-like, shape = (n_samples,) or shape = (n_sample, n_labels) Returns ------- self : returns an instance of self. Targets Notes ----- Please see the `scikit-learn API documentation <https://scikit-learn.org/stable/developers/develop.html#apis-of-scikit-learn-objects>`_ for further information.""" raise NotImplementedError() def set_hyperparameters( self, configuration, feat_type: Optional[FEAT_TYPE_TYPE] = None, init_params=None, ): params = configuration.get_dictionary() for param, value in params.items(): if not hasattr(self, param): raise ValueError( "Cannot set hyperparameter %s for %s because " "the hyperparameter does not exist." % (param, str(self)) ) setattr(self, param, value) if init_params is not None: for param, value in init_params.items(): if not hasattr(self, param): raise ValueError( "Cannot set init param %s for %s because " "the init param does not exist." % (param, str(self)) ) setattr(self, param, value) return self def __str__(self): name = self.get_properties()["name"] return "autosklearn.pipeline %s" % name
AutoSklearnComponent
python
airbytehq__airbyte
airbyte-integrations/connectors/source-braze/components.py
{ "start": 1460, "end": 4282 }
class ____(DatetimeBasedCursor): """ Extends DatetimeBasedCursor for Braze's API requirements where instead of using explicit start_time/end_time parameters, the API expects: - An end_time (ending_at) - A length parameter indicating how many days before end_time to fetch The length parameter represents the number of days in the time window, counting both start and end dates inclusively. For example, a window from 2023-01-01 to 2023-01-03 has a length of 3 days (counting Jan 1, 2, and 3). Length must be between 1-100 days as per Braze's API requirements. Example API request: GET /campaigns/data_series?campaign_id=xxx&ending_at=2023-01-03&length=3 This would fetch data from 2023-01-01 to 2023-01-03 inclusive. Args: step_option: Configuration for injecting the length parameter into requests """ step_option: Optional[RequestOption] = field(default=None) def __post_init__(self, parameters: Mapping[str, Any]): super().__post_init__(parameters=parameters) if self.step_option is None: raise ValueError("step_option is required for DatetimeIncrementalSyncComponent") def _get_request_options(self, option_type: RequestOptionType, stream_slice: Optional[StreamSlice] = None) -> Mapping[str, Any]: options: dict[str, Any] = {} if stream_slice is not None and self.step_option is not None: base_options = super()._get_request_options(option_type, stream_slice) options.update(base_options) if self.step_option.inject_into == option_type: # Get start and end times from the stream slice start_field = self._partition_field_start.eval(self.config) end_field = self._partition_field_end.eval(self.config) start_str = stream_slice.get(start_field) end_str = stream_slice.get(end_field) if isinstance(start_str, str) and isinstance(end_str, str): start_time = self._parser.parse(start_str, self.datetime_format) end_time = self._parser.parse(end_str, self.datetime_format) # Add 1 to include both start and end dates in the count # e.g., 2023-01-01 to 2023-01-03 = 3 days (Jan 1, 2, and 3) length_days = min(100, max(1, (end_time - start_time).days + 1)) field_name = ( self.step_option.field_name.eval(config=self.config) if isinstance(self.step_option.field_name, InterpolatedString) else self.step_option.field_name ) options[field_name] = length_days return options @dataclass
DatetimeIncrementalSyncComponent
python
neetcode-gh__leetcode
python/0448-find-all-numbers-disappeared-in-an-array.py
{ "start": 0, "end": 304 }
class ____: def findDisappearedNumbers(self, nums: List[int]) -> List[int]: for n in nums: i = abs(n) - 1 nums[i] = -1 * abs(nums[i]) res = [] for i, n in enumerate(nums): if n > 0: res.append(i + 1) return res
Solution
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/metadata/metadata_value.py
{ "start": 19125, "end": 19630 }
class ____(MetadataValue[str]): """Container class for URL metadata entry data. Args: url (Optional[str]): The URL as a string. """ url: PublicAttr[Optional[str]] = "" # type: ignore @public @property def value(self) -> str: """Optional[str]: The wrapped URL.""" return self.url if self.url is not None else "" @public @whitelist_for_serdes(storage_name="PathMetadataEntryData") @record_custom(field_to_new_mapping={"fspath": "path"})
UrlMetadataValue
python
kamyu104__LeetCode-Solutions
Python/shortest-palindrome.py
{ "start": 694, "end": 1441 }
class ____(object): def shortestPalindrome(self, s): """ :type s: str :rtype: str """ def getPrefix(pattern): prefix = [-1] * len(pattern) j = -1 for i in xrange(1, len(pattern)): while j > -1 and pattern[j+1] != pattern[i]: j = prefix[j] if pattern[j+1] == pattern[i]: j += 1 prefix[i] = j return prefix if not s: return s A = s + s[::-1] prefix = getPrefix(A) i = prefix[-1] while i >= len(s): i = prefix[i] return s[i+1:][::-1] + s # Time: O(n) # Space: O(n) # Manacher's Algorithm
Solution2
python
getsentry__sentry
src/sentry/similarity/backends/dummy.py
{ "start": 71, "end": 885 }
class ____(AbstractIndexBackend): def classify(self, scope, items, limit=None, timestamp=None): return [] def compare(self, scope, key, items, limit=None, timestamp=None): return [] def record(self, scope, key, items, timestamp=None): return {} def merge(self, scope, destination, items, timestamp=None) -> bool: return False def delete(self, scope, items, timestamp=None) -> bool: return False def scan(self, scope, indices, batch=1000, timestamp=None): # empty generator return yield def flush(self, scope, indices, batch=1000, timestamp=None): pass def export(self, scope, items, timestamp=None): return {} def import_(self, scope, items, timestamp=None): return {}
DummyIndexBackend
python
numba__numba
numba/tests/test_extending.py
{ "start": 35961, "end": 43157 }
class ____(TestCase): def test_void_return(self): """ Verify that returning a None from codegen function is handled automatically for void functions, otherwise raise exception. """ @intrinsic def void_func(typingctx, a): sig = types.void(types.int32) def codegen(context, builder, signature, args): pass # do nothing, return None, should be turned into # dummy value return sig, codegen @intrinsic def non_void_func(typingctx, a): sig = types.int32(types.int32) def codegen(context, builder, signature, args): pass # oops, should be returning a value here, raise exception return sig, codegen @jit(nopython=True) def call_void_func(): void_func(1) return 0 @jit(nopython=True) def call_non_void_func(): non_void_func(1) return 0 # void func should work self.assertEqual(call_void_func(), 0) # not void function should raise exception with self.assertRaises(LoweringError) as e: call_non_void_func() self.assertIn("non-void function returns None", e.exception.msg) def test_ll_pointer_cast(self): """ Usecase test: custom reinterpret cast to turn int values to pointers """ from ctypes import CFUNCTYPE, POINTER, c_float, c_int # Use intrinsic to make a reinterpret_cast operation def unsafe_caster(result_type): assert isinstance(result_type, types.CPointer) @intrinsic def unsafe_cast(typingctx, src): self.assertIsInstance(typingctx, typing.Context) if isinstance(src, types.Integer): sig = result_type(types.uintp) # defines the custom code generation def codegen(context, builder, signature, args): [src] = args rtype = signature.return_type llrtype = context.get_value_type(rtype) return builder.inttoptr(src, llrtype) return sig, codegen return unsafe_cast # make a nopython function to use our cast op. # this is not usable from cpython due to the returning of a pointer. def unsafe_get_ctypes_pointer(src): raise NotImplementedError("not callable from python") @overload(unsafe_get_ctypes_pointer, strict=False) def array_impl_unsafe_get_ctypes_pointer(arrtype): if isinstance(arrtype, types.Array): unsafe_cast = unsafe_caster(types.CPointer(arrtype.dtype)) def array_impl(arr): return unsafe_cast(src=arr.ctypes.data) return array_impl # the ctype wrapped function for use in nopython mode def my_c_fun_raw(ptr, n): for i in range(n): print(ptr[i]) prototype = CFUNCTYPE(None, POINTER(c_float), c_int) my_c_fun = prototype(my_c_fun_raw) # Call our pointer-cast in a @jit compiled function and use # the pointer in a ctypes function @jit(nopython=True) def foo(arr): ptr = unsafe_get_ctypes_pointer(arr) my_c_fun(ptr, arr.size) # Test arr = np.arange(10, dtype=np.float32) with captured_stdout() as buf: foo(arr) got = buf.getvalue().splitlines() buf.close() expect = list(map(str, arr)) self.assertEqual(expect, got) def test_serialization(self): """ Test serialization of intrinsic objects """ # define a intrinsic @intrinsic def identity(context, x): def codegen(context, builder, signature, args): return args[0] sig = x(x) return sig, codegen # use in a jit function @jit(nopython=True) def foo(x): return identity(x) self.assertEqual(foo(1), 1) # get serialization memo memo = _Intrinsic._memo memo_size = len(memo) # pickle foo and check memo size serialized_foo = pickle.dumps(foo) # increases the memo size memo_size += 1 self.assertEqual(memo_size, len(memo)) # unpickle foo_rebuilt = pickle.loads(serialized_foo) self.assertEqual(memo_size, len(memo)) # check rebuilt foo self.assertEqual(foo(1), foo_rebuilt(1)) # pickle identity directly serialized_identity = pickle.dumps(identity) # memo size unchanged self.assertEqual(memo_size, len(memo)) # unpickle identity_rebuilt = pickle.loads(serialized_identity) # must be the same object self.assertIs(identity, identity_rebuilt) # memo size unchanged self.assertEqual(memo_size, len(memo)) def test_deserialization(self): """ Test deserialization of intrinsic """ def defn(context, x): def codegen(context, builder, signature, args): return args[0] return x(x), codegen memo = _Intrinsic._memo memo_size = len(memo) # invoke _Intrinsic indirectly to avoid registration which keeps an # internal reference inside the compiler original = _Intrinsic("foo", defn) self.assertIs(original._defn, defn) pickled = pickle.dumps(original) # by pickling, a new memo entry is created memo_size += 1 self.assertEqual(memo_size, len(memo)) del original # remove original before unpickling # by deleting, the memo entry is NOT removed due to recent # function queue self.assertEqual(memo_size, len(memo)) # Manually force clear of _recent queue _Intrinsic._recent.clear() memo_size -= 1 self.assertEqual(memo_size, len(memo)) rebuilt = pickle.loads(pickled) # verify that the rebuilt object is different self.assertIsNot(rebuilt._defn, defn) # the second rebuilt object is the same as the first second = pickle.loads(pickled) self.assertIs(rebuilt._defn, second._defn) def test_docstring(self): @intrinsic def void_func(typingctx, a: int): """void_func docstring""" sig = types.void(types.int32) def codegen(context, builder, signature, args): pass # do nothing, return None, should be turned into # dummy value return sig, codegen self.assertEqual("numba.tests.test_extending", void_func.__module__) self.assertEqual("void_func", void_func.__name__) self.assertEqual("TestIntrinsic.test_docstring.<locals>.void_func", void_func.__qualname__) self.assertDictEqual({'a': int}, inspect.get_annotations(void_func)) self.assertEqual("void_func docstring", void_func.__doc__)
TestIntrinsic
python
kubernetes-client__python
kubernetes/client/models/v1alpha1_cluster_trust_bundle_spec.py
{ "start": 383, "end": 7397 }
class ____(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ openapi_types = { 'signer_name': 'str', 'trust_bundle': 'str' } attribute_map = { 'signer_name': 'signerName', 'trust_bundle': 'trustBundle' } def __init__(self, signer_name=None, trust_bundle=None, local_vars_configuration=None): # noqa: E501 """V1alpha1ClusterTrustBundleSpec - a model defined in OpenAPI""" # noqa: E501 if local_vars_configuration is None: local_vars_configuration = Configuration() self.local_vars_configuration = local_vars_configuration self._signer_name = None self._trust_bundle = None self.discriminator = None if signer_name is not None: self.signer_name = signer_name self.trust_bundle = trust_bundle @property def signer_name(self): """Gets the signer_name of this V1alpha1ClusterTrustBundleSpec. # noqa: E501 signerName indicates the associated signer, if any. In order to create or update a ClusterTrustBundle that sets signerName, you must have the following cluster-scoped permission: group=certificates.k8s.io resource=signers resourceName=<the signer name> verb=attest. If signerName is not empty, then the ClusterTrustBundle object must be named with the signer name as a prefix (translating slashes to colons). For example, for the signer name `example.com/foo`, valid ClusterTrustBundle object names include `example.com:foo:abc` and `example.com:foo:v1`. If signerName is empty, then the ClusterTrustBundle object's name must not have such a prefix. List/watch requests for ClusterTrustBundles can filter on this field using a `spec.signerName=NAME` field selector. # noqa: E501 :return: The signer_name of this V1alpha1ClusterTrustBundleSpec. # noqa: E501 :rtype: str """ return self._signer_name @signer_name.setter def signer_name(self, signer_name): """Sets the signer_name of this V1alpha1ClusterTrustBundleSpec. signerName indicates the associated signer, if any. In order to create or update a ClusterTrustBundle that sets signerName, you must have the following cluster-scoped permission: group=certificates.k8s.io resource=signers resourceName=<the signer name> verb=attest. If signerName is not empty, then the ClusterTrustBundle object must be named with the signer name as a prefix (translating slashes to colons). For example, for the signer name `example.com/foo`, valid ClusterTrustBundle object names include `example.com:foo:abc` and `example.com:foo:v1`. If signerName is empty, then the ClusterTrustBundle object's name must not have such a prefix. List/watch requests for ClusterTrustBundles can filter on this field using a `spec.signerName=NAME` field selector. # noqa: E501 :param signer_name: The signer_name of this V1alpha1ClusterTrustBundleSpec. # noqa: E501 :type: str """ self._signer_name = signer_name @property def trust_bundle(self): """Gets the trust_bundle of this V1alpha1ClusterTrustBundleSpec. # noqa: E501 trustBundle contains the individual X.509 trust anchors for this bundle, as PEM bundle of PEM-wrapped, DER-formatted X.509 certificates. The data must consist only of PEM certificate blocks that parse as valid X.509 certificates. Each certificate must include a basic constraints extension with the CA bit set. The API server will reject objects that contain duplicate certificates, or that use PEM block headers. Users of ClusterTrustBundles, including Kubelet, are free to reorder and deduplicate certificate blocks in this file according to their own logic, as well as to drop PEM block headers and inter-block data. # noqa: E501 :return: The trust_bundle of this V1alpha1ClusterTrustBundleSpec. # noqa: E501 :rtype: str """ return self._trust_bundle @trust_bundle.setter def trust_bundle(self, trust_bundle): """Sets the trust_bundle of this V1alpha1ClusterTrustBundleSpec. trustBundle contains the individual X.509 trust anchors for this bundle, as PEM bundle of PEM-wrapped, DER-formatted X.509 certificates. The data must consist only of PEM certificate blocks that parse as valid X.509 certificates. Each certificate must include a basic constraints extension with the CA bit set. The API server will reject objects that contain duplicate certificates, or that use PEM block headers. Users of ClusterTrustBundles, including Kubelet, are free to reorder and deduplicate certificate blocks in this file according to their own logic, as well as to drop PEM block headers and inter-block data. # noqa: E501 :param trust_bundle: The trust_bundle of this V1alpha1ClusterTrustBundleSpec. # noqa: E501 :type: str """ if self.local_vars_configuration.client_side_validation and trust_bundle is None: # noqa: E501 raise ValueError("Invalid value for `trust_bundle`, must not be `None`") # noqa: E501 self._trust_bundle = trust_bundle def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, V1alpha1ClusterTrustBundleSpec): return False return self.to_dict() == other.to_dict() def __ne__(self, other): """Returns true if both objects are not equal""" if not isinstance(other, V1alpha1ClusterTrustBundleSpec): return True return self.to_dict() != other.to_dict()
V1alpha1ClusterTrustBundleSpec
python
PrefectHQ__prefect
src/prefect/client/schemas/filters.py
{ "start": 24428, "end": 24631 }
class ____(PrefectBaseModel): """Filter by `BlockDocument.id`.""" any_: Optional[List[UUID]] = Field( default=None, description="A list of block ids to include" )
BlockDocumentFilterId
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/vertex_ai/dataset.py
{ "start": 4966, "end": 8199 }
class ____(GoogleCloudBaseOperator): """ Get a Dataset. :param project_id: Required. The ID of the Google Cloud project the cluster belongs to. :param region: Required. The Cloud Dataproc region in which to handle the request. :param dataset_id: Required. The ID of the Dataset to get. :param retry: Designation of what errors, if any, should be retried. :param timeout: The timeout for this request. :param metadata: Strings which should be sent along with the request as metadata. :param gcp_conn_id: The connection ID to use connecting to Google Cloud. :param impersonation_chain: Optional service account to impersonate using short-term credentials, or chained list of accounts required to get the access_token of the last account in the list, which will be impersonated in the request. If set as a string, the account must grant the originating account the Service Account Token Creator IAM role. If set as a sequence, the identities from the list must grant Service Account Token Creator IAM role to the directly preceding identity, with first account from the list granting this role to the originating account (templated). """ template_fields = ("region", "dataset_id", "project_id", "impersonation_chain") operator_extra_links = (VertexAIDatasetLink(),) def __init__( self, *, region: str, project_id: str, dataset_id: str, read_mask: str | None = None, retry: Retry | _MethodDefault = DEFAULT, timeout: float | None = None, metadata: Sequence[tuple[str, str]] = (), gcp_conn_id: str = "google_cloud_default", impersonation_chain: str | Sequence[str] | None = None, **kwargs, ) -> None: super().__init__(**kwargs) self.region = region self.project_id = project_id self.dataset_id = dataset_id self.read_mask = read_mask self.retry = retry self.timeout = timeout self.metadata = metadata self.gcp_conn_id = gcp_conn_id self.impersonation_chain = impersonation_chain @property def extra_links_params(self) -> dict[str, Any]: return { "region": self.region, "project_id": self.project_id, } def execute(self, context: Context): hook = DatasetHook( gcp_conn_id=self.gcp_conn_id, impersonation_chain=self.impersonation_chain, ) try: self.log.info("Get dataset: %s", self.dataset_id) dataset_obj = hook.get_dataset( project_id=self.project_id, region=self.region, dataset=self.dataset_id, read_mask=self.read_mask, retry=self.retry, timeout=self.timeout, metadata=self.metadata, ) VertexAIDatasetLink.persist(context=context, dataset_id=self.dataset_id) self.log.info("Dataset was gotten.") return Dataset.to_dict(dataset_obj) except NotFound: self.log.info("The Dataset ID %s does not exist.", self.dataset_id)
GetDatasetOperator
python
spyder-ide__spyder
spyder/plugins/shortcuts/plugin.py
{ "start": 1468, "end": 9089 }
class ____(SpyderPluginV2, SpyderShortcutsMixin): """ Shortcuts Plugin. """ NAME = 'shortcuts' # TODO: Fix requires to reflect the desired order in the preferences REQUIRES = [Plugins.Preferences] OPTIONAL = [Plugins.MainMenu] CONF_WIDGET_CLASS = ShortcutsConfigPage CONF_SECTION = NAME CONF_FILE = False CAN_BE_DISABLED = False # ---- Signals # ------------------------------------------------------------------------- sig_shortcuts_updated = Signal() """ This signal is emitted to inform shortcuts have been updated. """ # ---- SpyderPluginV2 API # ------------------------------------------------------------------------- @staticmethod def get_name(): return _("Keyboard shortcuts") @staticmethod def get_description(): return _("Manage application, pane and actions shortcuts.") @classmethod def get_icon(cls): return cls.create_icon('keyboard') def on_initialize(self): self._shortcut_data: List[ShortcutData] = [] self._shortcut_sequences = set({}) self.create_action( ShortcutActions.ShortcutSummaryAction, text=_("Shortcuts summary"), triggered=self.show_summary, register_shortcut=True, context=Qt.ApplicationShortcut, ) @on_plugin_available(plugin=Plugins.Preferences) def on_preferences_available(self): preferences = self.get_plugin(Plugins.Preferences) preferences.register_plugin_preferences(self) @on_plugin_available(plugin=Plugins.MainMenu) def on_main_menu_available(self): mainmenu = self.get_plugin(Plugins.MainMenu) shortcuts_action = self.get_action( ShortcutActions.ShortcutSummaryAction) # Add to Help menu. mainmenu.add_item_to_application_menu( shortcuts_action, menu_id=ApplicationMenus.Help, section=HelpMenuSections.Documentation, before_section=HelpMenuSections.ExternalDocumentation, ) @on_plugin_teardown(plugin=Plugins.Preferences) def on_preferences_teardown(self): preferences = self.get_plugin(Plugins.Preferences) preferences.deregister_plugin_preferences(self) @on_plugin_teardown(plugin=Plugins.MainMenu) def on_main_menu_teardown(self): mainmenu = self.get_plugin(Plugins.MainMenu) mainmenu.remove_item_from_application_menu( ShortcutActions.ShortcutSummaryAction, menu_id=ApplicationMenus.Help ) def on_mainwindow_visible(self): self.apply_shortcuts() # ---- Public API # ------------------------------------------------------------------------- def get_shortcut_data(self): """Return the registered shortcut data.""" # We need to include the second list here so that those shortcuts are # displayed in Preferences. But they are updated using a different # mechanism (see SpyderShortcutsMixin.register_shortcut_for_widget). return self._shortcut_data + SHORTCUTS_FOR_WIDGETS_DATA def reset_shortcuts(self): """Reset shrotcuts.""" if self._conf: self._conf.reset_shortcuts() @Slot() def show_summary(self): """Reset shortcuts.""" dlg = ShortcutsSummaryDialog(None) dlg.exec_() def register_shortcut(self, qaction_or_qshortcut, context, name, add_shortcut_to_tip=True, plugin_name=None): """ Register QAction or QShortcut to Spyder main application, with shortcut (context, name, default) """ # Name and context are saved in lowercase in our config system, so we # need to use them like that here. # Note: That's how the Python ConfigParser class saves options. name = name.lower() context = context.lower() self._shortcut_data.append( ShortcutData( qobject=qaction_or_qshortcut, name=name, context=context, plugin_name=plugin_name, add_shortcut_to_tip=add_shortcut_to_tip, ) ) def unregister_shortcut(self, qaction_or_qshortcut, context, name, add_shortcut_to_tip=True, plugin_name=None): """ Unregister QAction or QShortcut from Spyder main application. """ # Name and context are saved in lowercase in our config system, so we # need to use them like that here. # Note: That's how the Python ConfigParser class saves options. name = name.lower() context = context.lower() data = ShortcutData( qobject=qaction_or_qshortcut, name=name, context=context, plugin_name=plugin_name, add_shortcut_to_tip=add_shortcut_to_tip, ) if data in self._shortcut_data: self._shortcut_data.remove(data) def apply_shortcuts(self): """ Apply shortcuts settings to all widgets/plugins. """ toberemoved = [] # TODO: Check shortcut existence based on action existence, so that we # can update shortcut names without showing the old ones on the # preferences for index, data in enumerate(self._shortcut_data): try: shortcut_sequence = self.get_shortcut( data.name, data.context, data.plugin_name ) except (configparser.NoSectionError, configparser.NoOptionError): # If shortcut does not exist, save it to CONF. This is an # action for which there is no shortcut assigned (yet) in # the configuration self.set_shortcut( "", data.name, data.context, data.plugin_name ) shortcut_sequence = '' if shortcut_sequence: if shortcut_sequence in self._shortcut_sequences: continue self._shortcut_sequences |= {(data.context, shortcut_sequence)} keyseq = QKeySequence(shortcut_sequence) else: # Needed to remove old sequences that were cleared. # See spyder-ide/spyder#12992 keyseq = QKeySequence() # Do not register shortcuts for the toggle view action. # The shortcut will be displayed only on the menus and handled by # about to show/hide signals. if any( [ data.name.startswith(f"switch to {plugin}") for plugin in PLUGIN_REGISTRY.enabled_plugins ] ) and isinstance(data.qobject, SpyderAction): keyseq = QKeySequence() # Register shortcut for the associated qobject try: if isinstance(data.qobject, QAction): data.qobject.setShortcut(keyseq) if data.add_shortcut_to_tip: add_shortcut_to_tooltip( data.qobject, data.context, data.name ) elif isinstance(data.qobject, QShortcut): data.qobject.setKey(keyseq) except RuntimeError: # Object has been deleted toberemoved.append(index) for index in sorted(toberemoved, reverse=True): self._shortcut_data.pop(index) self.sig_shortcuts_updated.emit()
Shortcuts
python
google__pytype
pytype/overlays/typing_overlay.py
{ "start": 19750, "end": 21075 }
class ____(overlay_utils.TypingContainer): """Implementation of typing.Literal.""" def _build_value(self, node, inner, ellipses): values = [] errors = [] for i, param in enumerate(inner): # TODO(b/173742489): Once the enum overlay is enabled, we should # stop allowing unsolvable and handle enums here. if ( param == self.ctx.convert.none or isinstance(param, abstract.LiteralClass) or param == self.ctx.convert.unsolvable and i not in ellipses ): value = param elif isinstance(param, abstract.ConcreteValue) and isinstance( param.pyval, (int, str, bytes) ): value = abstract.LiteralClass(param, self.ctx) elif isinstance(param, abstract.Instance) and param.cls.is_enum: value = abstract.LiteralClass(param, self.ctx) else: if i in ellipses: invalid_param = "..." else: invalid_param = param.name errors.append((invalid_param, i)) value = self.ctx.convert.unsolvable values.append(value) if errors: self.ctx.errorlog.invalid_annotation( self.ctx.vm.frames, self, "\n".join("Bad parameter %r at index %d" % e for e in errors), ) return self.ctx.convert.merge_values(values)
Literal
python
google__jax
tests/extend_test.py
{ "start": 982, "end": 2643 }
class ____(jtu.JaxTestCase): def test_symbols(self): # Assume these are tested in random_test.py, only check equivalence self.assertIs(jex.random.seed_with_impl, prng.seed_with_impl) self.assertIs(jex.random.threefry2x32_p, prng.threefry2x32_p) self.assertIs(jex.random.threefry_2x32, prng.threefry_2x32) self.assertIs(jex.random.threefry_prng_impl, prng.threefry_prng_impl) self.assertIs(jex.random.rbg_prng_impl, prng.rbg_prng_impl) self.assertIs(jex.random.unsafe_rbg_prng_impl, prng.unsafe_rbg_prng_impl) # Assume these are tested elsewhere, only check equivalence self.assertIs(jex.backend.backends, xla_bridge.backends) self.assertIs(jex.backend.backend_xla_version, xla_bridge.backend_xla_version) self.assertIs(jex.backend.clear_backends, api.clear_backends) self.assertIs(jex.backend.get_backend, xla_bridge.get_backend) self.assertIs(jex.backend.register_backend_factory, xla_bridge.register_backend_factory) self.assertIs(jex.core.array_types, abstract_arrays.array_types) self.assertIs(jex.linear_util.StoreException, linear_util.StoreException) self.assertIs(jex.linear_util.WrappedFun, linear_util.WrappedFun) self.assertIs(jex.linear_util.cache, linear_util.cache) self.assertIs(jex.linear_util.merge_linear_aux, linear_util.merge_linear_aux) self.assertIs(jex.linear_util.transformation, linear_util.transformation) self.assertIs(jex.linear_util.transformation_with_aux, linear_util.transformation_with_aux) # TODO(necula): revert this change once we deprecate the old wrap_init # self.assertIs(jex.linear_util.wrap_init, linear_util.wrap_init)
ExtendTest
python
graphql-python__graphene
graphene/relay/tests/test_node_custom.py
{ "start": 181, "end": 555 }
class ____(Node): class Meta: name = "Node" @staticmethod def to_global_id(type_, id): return id @staticmethod def get_node_from_global_id(info, id, only_type=None): assert info.schema is graphql_schema if id in user_data: return user_data.get(id) else: return photo_data.get(id)
CustomNode
python
matplotlib__matplotlib
lib/mpl_toolkits/axisartist/angle_helper.py
{ "start": 5166, "end": 5349 }
class ____(LocatorBase): def __call__(self, v1, v2): return select_step360(v1, v2, self.nbins, self._include_last, threshold_factor=1)
LocatorD
python
bokeh__bokeh
tests/unit/bokeh/embed/test_util__embed.py
{ "start": 23195, "end": 24060 }
class ____: def test_no_docs(self) -> None: p1 = SomeModel() p2 = SomeModel() beu._dispose_temp_doc([p1, p2]) assert p1.document is None assert p2.document is None def test_with_docs(self) -> None: d1 = Document() d2 = Document() p1 = SomeModel() d1.add_root(p1) p2 = OtherModel(child=SomeModel()) d2.add_root(p2.child) beu._create_temp_doc([p1, p2]) beu._dispose_temp_doc([p1, p2]) assert p1.document is d1 assert p2.document is None assert p2.child.document is d2 def test_with_temp_docs(self) -> None: p1 = SomeModel() p2 = SomeModel() beu._create_temp_doc([p1, p2]) beu._dispose_temp_doc([p1, p2]) assert p1.document is None assert p2.document is None
Test__dispose_temp_doc
python
huggingface__transformers
src/transformers/models/big_bird/tokenization_big_bird.py
{ "start": 1103, "end": 8733 }
class ____(TokenizersBackend): """ Construct a "fast" BigBird tokenizer (backed by HuggingFace's *tokenizers* library). Based on [Unigram](https://huggingface.co/docs/tokenizers/python/latest/components.html?highlight=unigram#models). This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should refer to this superclass for more information regarding those methods Args: vocab (`dict`, *optional*): Custom vocabulary dictionary. If not provided, vocabulary is loaded from vocab_file. unk_token (`str`, *optional*, defaults to `"<unk>"`): The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this token instead. bos_token (`str`, *optional*, defaults to `"<s>"`): The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token. <Tip> When building a sequence using special tokens, this is not the token that is used for the beginning of sequence. The token used is the `cls_token`. </Tip> eos_token (`str`, *optional*, defaults to `"</s>"`): The end of sequence token. .. note:: When building a sequence using special tokens, this is not the token that is used for the end of sequence. The token used is the `sep_token`. pad_token (`str`, *optional*, defaults to `"<pad>"`): The token used for padding, for example when batching sequences of different lengths. sep_token (`str`, *optional*, defaults to `"[SEP]"`): The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for sequence classification or for a text and a question for question answering. It is also used as the last token of a sequence built with special tokens. mask_token (`str`, *optional*, defaults to `"[MASK]"`): The token used for masking values. This is the token used when training this model with masked language modeling. This is the token which the model will try to predict. cls_token (`str`, *optional*, defaults to `"[CLS]"`): The classifier token which is used when doing sequence classification (classification of the whole sequence instead of per-token classification). It is the first token of the sequence when built with special tokens. add_prefix_space (`bool`, *optional*, defaults to `True`): Whether or not to add an initial space to the input. This allows to treat the leading word just as any other word. vocab_file (`str`, *optional*): [SentencePiece](https://github.com/google/sentencepiece) file (generally has a *.spm* extension) that contains the vocabulary necessary to instantiate a tokenizer. tokenizer_file (`str`, *optional*): Path to a tokenizers JSON file containing the serialization of a tokenizer. """ vocab_files_names = VOCAB_FILES_NAMES model_input_names = ["input_ids", "attention_mask"] prefix_tokens: list[int] = [] def __init__( self, vocab=None, unk_token="<unk>", bos_token="<s>", eos_token="</s>", pad_token="<pad>", sep_token="[SEP]", mask_token="[MASK]", cls_token="[CLS]", add_prefix_space=True, vocab_file=None, tokenizer_file=None, **kwargs, ): bos_token = AddedToken(bos_token, lstrip=False, rstrip=False) if isinstance(bos_token, str) else bos_token eos_token = AddedToken(eos_token, lstrip=False, rstrip=False) if isinstance(eos_token, str) else eos_token unk_token = AddedToken(unk_token, lstrip=False, rstrip=False) if isinstance(unk_token, str) else unk_token pad_token = AddedToken(pad_token, lstrip=False, rstrip=False) if isinstance(pad_token, str) else pad_token cls_token = AddedToken(cls_token, lstrip=False, rstrip=False) if isinstance(cls_token, str) else cls_token sep_token = AddedToken(sep_token, lstrip=False, rstrip=False) if isinstance(sep_token, str) else sep_token mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token self.add_prefix_space = add_prefix_space self.vocab_file = vocab_file # Convert vocab to list of (token, score) tuples if vocab is None: vocab_scores = [(str(pad_token), 0.0), (str(eos_token), 0.0), (str(bos_token), 0.0)] elif isinstance(vocab, dict): vocab_scores = [(str(token), float(score)) for token, score in vocab.items()] elif isinstance(vocab, list) and len(vocab) > 0: if isinstance(vocab[0], (tuple, list)): vocab_scores = [(str(token), float(score)) for token, score in vocab] else: vocab_scores = [(str(token), 0.0) for token in vocab] else: vocab_scores = [(str(pad_token), 0.0), (str(eos_token), 0.0), (str(bos_token), 0.0)] # Find unk_id in vocab unk_token_content = str(unk_token) unk_id = next((idx for idx, (token, _) in enumerate(vocab_scores) if token == unk_token_content), None) if unk_id is None: unk_id = min(len(vocab_scores), 100) if len(vocab_scores) > 100: vocab_scores.insert(100, (unk_token_content, 0.0)) else: vocab_scores.append((unk_token_content, 0.0)) # Ensure cls_token and sep_token are in vocab cls_token_str = str(cls_token) sep_token_str = str(sep_token) cls_token_id = next((idx for idx, (token, _) in enumerate(vocab_scores) if token == cls_token_str), None) sep_token_id = next((idx for idx, (token, _) in enumerate(vocab_scores) if token == sep_token_str), None) if cls_token_id is None: cls_token_id = len(vocab_scores) vocab_scores.append((cls_token_str, 0.0)) if sep_token_id is None: sep_token_id = len(vocab_scores) vocab_scores.append((sep_token_str, 0.0)) self._tokenizer = Tokenizer(Unigram(vocab_scores, unk_id=unk_id, byte_fallback=False)) self._tokenizer.normalizer = normalizers.Sequence( [normalizers.Strip(left=False, right=True), normalizers.Replace(Regex(r" {2,}"), SPIECE_UNDERLINE)] ) prepend_scheme = "always" if add_prefix_space else "never" self._tokenizer.pre_tokenizer = pre_tokenizers.Metaspace( replacement="▁", prepend_scheme=prepend_scheme, split=True ) self._tokenizer.decoder = decoders.Metaspace(replacement="▁", prepend_scheme=prepend_scheme, split=True) super().__init__( tokenizer_object=self._tokenizer, bos_token=bos_token, eos_token=eos_token, unk_token=unk_token, pad_token=pad_token, mask_token=mask_token, cls_token=cls_token, sep_token=sep_token, **kwargs, ) self.init_kwargs["add_prefix_space"] = add_prefix_space self._tokenizer.post_processor = processors.TemplateProcessing( single=f"{cls_token_str}:0 $A:0 {sep_token_str}:0", pair=f"{cls_token_str}:0 $A:0 {sep_token_str}:0 $B:1 {sep_token_str}:1", special_tokens=[(cls_token_str, cls_token_id), (sep_token_str, sep_token_id)], ) __all__ = ["BigBirdTokenizer"]
BigBirdTokenizer