code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def mock_remote_command(self, cmd: str | list[str], **kwargs) -> ReturnValues: """Mocks a command, returning the next response for the command.""" if isinstance(cmd, list): try: cmd = ' '.join(cmd) except TypeError as ex: logging.warning( 'Tried joining command %s but not...
Mocks a command, returning the next response for the command.
mock_remote_command
python
GoogleCloudPlatform/PerfKitBenchmarker
tests/mock_command.py
https://github.com/GoogleCloudPlatform/PerfKitBenchmarker/blob/master/tests/mock_command.py
Apache-2.0
def MockIssueCommand( self, call_to_response: dict[str, list[tuple[str, str, int]]], ) -> mock_command.MockIssueCommand: """Mocks IssueCommand, returning response for the given call. Args: call_to_response: A dictionary of commands to a list of responses. Commands just need to be a ...
Mocks IssueCommand, returning response for the given call. Args: call_to_response: A dictionary of commands to a list of responses. Commands just need to be a substring of the actual command. Each response is given in order, like with mock's normal iterating side_effect. Returns:...
MockIssueCommand
python
GoogleCloudPlatform/PerfKitBenchmarker
tests/pkb_common_test_case.py
https://github.com/GoogleCloudPlatform/PerfKitBenchmarker/blob/master/tests/pkb_common_test_case.py
Apache-2.0
def MockRemoteCommand( self, call_to_response: dict[str, list[tuple[str, str]]], vm: virtual_machine.BaseVirtualMachine | None = None, ) -> virtual_machine.BaseVirtualMachine: """Mocks vm.RemoteCommand, returning response for the given call. Args: call_to_response: A dictionary of com...
Mocks vm.RemoteCommand, returning response for the given call. Args: call_to_response: A dictionary of commands to a list of responses. Commands just need to be a substring of the actual command. Each response is given in order, like with mock's normal iterating side_effect. vm:...
MockRemoteCommand
python
GoogleCloudPlatform/PerfKitBenchmarker
tests/pkb_common_test_case.py
https://github.com/GoogleCloudPlatform/PerfKitBenchmarker/blob/master/tests/pkb_common_test_case.py
Apache-2.0
def MockRunCommand( self, call_to_response: dict[str, list[tuple[str, str, int]]], cli: command_interface.CommandInterface | None = None, ) -> command_interface.CommandInterface: """Mocks RunCommand, returning response for the given call. Args: call_to_response: A dictionary of comman...
Mocks RunCommand, returning response for the given call. Args: call_to_response: A dictionary of commands to a list of responses. Commands just need to be a substring of the actual command. Each response is given in order, like with mock's normal iterating side_effect. cli: A mo...
MockRunCommand
python
GoogleCloudPlatform/PerfKitBenchmarker
tests/pkb_common_test_case.py
https://github.com/GoogleCloudPlatform/PerfKitBenchmarker/blob/master/tests/pkb_common_test_case.py
Apache-2.0
def testScratchDisks(self): """Test for creating and deleting scratch disks. This test creates two scratch disks on a vm and deletes them, ensuring that the proper calls to create, format, mount, and delete are made. """ vm = self._CreateVm() disk_spec = self.GetDiskSpec(mount_point='/mountpoi...
Test for creating and deleting scratch disks. This test creates two scratch disks on a vm and deletes them, ensuring that the proper calls to create, format, mount, and delete are made.
testScratchDisks
python
GoogleCloudPlatform/PerfKitBenchmarker
tests/scratch_disk_test.py
https://github.com/GoogleCloudPlatform/PerfKitBenchmarker/blob/master/tests/scratch_disk_test.py
Apache-2.0
def _GetScratchDiskName( self, vm_group_name: str, multi_writer_group_name: str ) -> str: """Get the name of the scratch disk. Args: vm_group_name: name of the vm_group multi_writer_group_name: name of the multiwriter group name (optional) Returns: scratch disk name """ ...
Get the name of the scratch disk. Args: vm_group_name: name of the vm_group multi_writer_group_name: name of the multiwriter group name (optional) Returns: scratch disk name
_GetScratchDiskName
python
GoogleCloudPlatform/PerfKitBenchmarker
tests/scratch_disk_test.py
https://github.com/GoogleCloudPlatform/PerfKitBenchmarker/blob/master/tests/scratch_disk_test.py
Apache-2.0
def testMultiWriterDiskName(self): """Test Case: Multiwriter Disk Name. Scenario: Verify that the multiwriter disk name adheres to the following convention: 'pkb-xxxx-multiwriter-{groupName}-{xx}'. If 'disk_spec.multi_writer_group_name' is provided, ensure 'groupName' in the disk name i...
Test Case: Multiwriter Disk Name. Scenario: Verify that the multiwriter disk name adheres to the following convention: 'pkb-xxxx-multiwriter-{groupName}-{xx}'. If 'disk_spec.multi_writer_group_name' is provided, ensure 'groupName' in the disk name is set to this specified value. If 'd...
testMultiWriterDiskName
python
GoogleCloudPlatform/PerfKitBenchmarker
tests/scratch_disk_test.py
https://github.com/GoogleCloudPlatform/PerfKitBenchmarker/blob/master/tests/scratch_disk_test.py
Apache-2.0
def testInvalidValue(self): """Passing an unrecognized value is not allowed.""" exp_str = 'test: Invalid value for --timing_measurements' exp_regex = r'^%s$' % re.escape(exp_str) with self.assertRaisesRegex(flags.ValidationError, exp_regex): timing_util.ValidateMeasurementsFlag(['test'])
Passing an unrecognized value is not allowed.
testInvalidValue
python
GoogleCloudPlatform/PerfKitBenchmarker
tests/timing_util_test.py
https://github.com/GoogleCloudPlatform/PerfKitBenchmarker/blob/master/tests/timing_util_test.py
Apache-2.0
def testNoneWithAnother(self): """Passing none with another value is not allowed.""" exp_str = 'none: Cannot combine with other --timing_measurements options' exp_regex = r'^%s$' % re.escape(exp_str) with self.assertRaisesRegex(flags.ValidationError, exp_regex): timing_util.ValidateMeasurementsFla...
Passing none with another value is not allowed.
testNoneWithAnother
python
GoogleCloudPlatform/PerfKitBenchmarker
tests/timing_util_test.py
https://github.com/GoogleCloudPlatform/PerfKitBenchmarker/blob/master/tests/timing_util_test.py
Apache-2.0
def testMeasureSequential(self): """Verify correct interval tuple generation in sequential measurements.""" timer = timing_util.IntervalTimer() self.assertEqual(timer.intervals, []) with timer.Measure('First Interval'): pass with timer.Measure('Second Interval'): pass self.assertEqua...
Verify correct interval tuple generation in sequential measurements.
testMeasureSequential
python
GoogleCloudPlatform/PerfKitBenchmarker
tests/timing_util_test.py
https://github.com/GoogleCloudPlatform/PerfKitBenchmarker/blob/master/tests/timing_util_test.py
Apache-2.0
def testMeasureNested(self): """Verify correct interval tuple generation in nested measurements.""" timer = timing_util.IntervalTimer() self.assertEqual(timer.intervals, []) with timer.Measure('Outer Interval'): with timer.Measure('Inner Interval'): pass self.assertEqual(len(timer.inte...
Verify correct interval tuple generation in nested measurements.
testMeasureNested
python
GoogleCloudPlatform/PerfKitBenchmarker
tests/timing_util_test.py
https://github.com/GoogleCloudPlatform/PerfKitBenchmarker/blob/master/tests/timing_util_test.py
Apache-2.0
def testGenerateSamplesMeasureNotCalled(self): """GenerateSamples should return an empty list if Measure was not called.""" timer = timing_util.IntervalTimer() self.assertEqual(timer.intervals, []) samples = timer.GenerateSamples() self.assertEqual(timer.intervals, []) self.assertEqual(samples, ...
GenerateSamples should return an empty list if Measure was not called.
testGenerateSamplesMeasureNotCalled
python
GoogleCloudPlatform/PerfKitBenchmarker
tests/timing_util_test.py
https://github.com/GoogleCloudPlatform/PerfKitBenchmarker/blob/master/tests/timing_util_test.py
Apache-2.0
def testGenerateSamplesRuntimeNoTimestamps(self): """Test generating runtime sample but no timestamp samples.""" timer = timing_util.IntervalTimer() with timer.Measure('First'): pass with timer.Measure('Second'): pass start0 = timer.intervals[0][1] stop0 = timer.intervals[0][2] s...
Test generating runtime sample but no timestamp samples.
testGenerateSamplesRuntimeNoTimestamps
python
GoogleCloudPlatform/PerfKitBenchmarker
tests/timing_util_test.py
https://github.com/GoogleCloudPlatform/PerfKitBenchmarker/blob/master/tests/timing_util_test.py
Apache-2.0
def testGenerateSamplesRuntimeAndTimestamps(self): """Test generating both runtime and timestamp samples.""" timer = timing_util.IntervalTimer() with timer.Measure('First'): pass with timer.Measure('Second'): pass start0 = timer.intervals[0][1] stop0 = timer.intervals[0][2] start...
Test generating both runtime and timestamp samples.
testGenerateSamplesRuntimeAndTimestamps
python
GoogleCloudPlatform/PerfKitBenchmarker
tests/timing_util_test.py
https://github.com/GoogleCloudPlatform/PerfKitBenchmarker/blob/master/tests/timing_util_test.py
Apache-2.0
def HaveSleepSubprocess(): """Checks if the current process has a sleep subprocess.""" for child in psutil.Process(os.getpid()).children(recursive=True): if 'sleep' in child.cmdline(): return True return False
Checks if the current process has a sleep subprocess.
HaveSleepSubprocess
python
GoogleCloudPlatform/PerfKitBenchmarker
tests/vm_util_test.py
https://github.com/GoogleCloudPlatform/PerfKitBenchmarker/blob/master/tests/vm_util_test.py
Apache-2.0
def _CheckBucket(self, bucket): """Make sure that we are only passed one bucket name. Args: bucket: the name of a bucket. Raises: ValueError, if this object has been passed a different bucket name previously. """ if self.bucket is None: self.bucket = bucket elif self.bucket !=...
Make sure that we are only passed one bucket name. Args: bucket: the name of a bucket. Raises: ValueError, if this object has been passed a different bucket name previously.
_CheckBucket
python
GoogleCloudPlatform/PerfKitBenchmarker
tests/integration/scripts/object_storage_worker_integration_tests.py
https://github.com/GoogleCloudPlatform/PerfKitBenchmarker/blob/master/tests/integration/scripts/object_storage_worker_integration_tests.py
Apache-2.0
def _run_throughput_directly( command: str, throughput_script: str, vm: virtual_machine.BaseVirtualMachine, burst_requests: int, ) -> list[throughput_load_driver.CommandResponse]: """Calls throughput_load_driver directly rather than via VM.""" del throughput_script ...
Calls throughput_load_driver directly rather than via VM.
_run_throughput_directly
python
GoogleCloudPlatform/PerfKitBenchmarker
tests/linux_benchmarks/ai_model_throughput_benchmark_test.py
https://github.com/GoogleCloudPlatform/PerfKitBenchmarker/blob/master/tests/linux_benchmarks/ai_model_throughput_benchmark_test.py
Apache-2.0
def _AssertSamples(self, results, delta, values): """ "Asserts that the samples matching delta correspond to values.""" delta_metric = [r for r in results if r[1] == delta] self.assertEqual(1, len(delta_metric), delta) # The bidirectional_network_tests run in parallel and are grouped by # <test nu...
"Asserts that the samples matching delta correspond to values.
_AssertSamples
python
GoogleCloudPlatform/PerfKitBenchmarker
tests/linux_benchmarks/bidirectional_network_benchmark_test.py
https://github.com/GoogleCloudPlatform/PerfKitBenchmarker/blob/master/tests/linux_benchmarks/bidirectional_network_benchmark_test.py
Apache-2.0
def _AssertSample(self, results, metric, value, unit): """Asserts results contains a sample matching metric/value/unit.""" match = [ r for r in results if ( r.metric == metric and r.unit == unit and abs(r.value - value) < TOLERANCE ) ] ...
Asserts results contains a sample matching metric/value/unit.
_AssertSample
python
GoogleCloudPlatform/PerfKitBenchmarker
tests/linux_benchmarks/bidirectional_network_benchmark_test.py
https://github.com/GoogleCloudPlatform/PerfKitBenchmarker/blob/master/tests/linux_benchmarks/bidirectional_network_benchmark_test.py
Apache-2.0
def vm_mock(index: int, timestamp: float) -> mock.Mock: """Creates a mock vm and Adds the needed vm attributes to the mock vm. Args: index: an integer which specifies index of vm in the list of vms. timestamp: a timestamp which is used to determine delete start time and end time. Returns: A mo...
Creates a mock vm and Adds the needed vm attributes to the mock vm. Args: index: an integer which specifies index of vm in the list of vms. timestamp: a timestamp which is used to determine delete start time and end time. Returns: A mock vm.
vm_mock
python
GoogleCloudPlatform/PerfKitBenchmarker
tests/linux_benchmarks/cluster_boot_benchmark_test.py
https://github.com/GoogleCloudPlatform/PerfKitBenchmarker/blob/master/tests/linux_benchmarks/cluster_boot_benchmark_test.py
Apache-2.0
def vm_mock_given_delete_times( index: int, delete_start_time: float | None = None, delete_end_time: float | None = None, ) -> mock.Mock: """Creates a mock vm with a provided delete_start_time and delete_end_time. Args: index: an integer which specifies index of vm in the list of vms. delete_st...
Creates a mock vm with a provided delete_start_time and delete_end_time. Args: index: an integer which specifies index of vm in the list of vms. delete_start_time: mock timestamp indicating the start of the VM delete process. May be passed in as None to test MeasureDelete logic. delete_end_time: mo...
vm_mock_given_delete_times
python
GoogleCloudPlatform/PerfKitBenchmarker
tests/linux_benchmarks/cluster_boot_benchmark_test.py
https://github.com/GoogleCloudPlatform/PerfKitBenchmarker/blob/master/tests/linux_benchmarks/cluster_boot_benchmark_test.py
Apache-2.0
def testMeasureDeleteNoValidVMs(self): """MeasureDelete test where no VMs have valid delete measurements.""" timestamp = 1625863325.003580 vm_with_neither = vm_mock_given_delete_times(index=0) vm_with_start_only = vm_mock_given_delete_times( index=1, delete_start_time=timestamp ) # We ne...
MeasureDelete test where no VMs have valid delete measurements.
testMeasureDeleteNoValidVMs
python
GoogleCloudPlatform/PerfKitBenchmarker
tests/linux_benchmarks/cluster_boot_benchmark_test.py
https://github.com/GoogleCloudPlatform/PerfKitBenchmarker/blob/master/tests/linux_benchmarks/cluster_boot_benchmark_test.py
Apache-2.0
def testMeasureDeleteAttributeChecks(self): """MeasureDelete test where some VMs do not have valid delete measurements.""" timestamp = 1625863325.003580 vm_with_neither = vm_mock_given_delete_times(index=0) vm_with_start_only = vm_mock_given_delete_times( index=1, delete_start_time=timestamp ...
MeasureDelete test where some VMs do not have valid delete measurements.
testMeasureDeleteAttributeChecks
python
GoogleCloudPlatform/PerfKitBenchmarker
tests/linux_benchmarks/cluster_boot_benchmark_test.py
https://github.com/GoogleCloudPlatform/PerfKitBenchmarker/blob/master/tests/linux_benchmarks/cluster_boot_benchmark_test.py
Apache-2.0
def testParseOutput(self): """Tests parsing valid output from running Coremark.""" with open(_SAMPLE_OUTPUT_FILE) as f: output = f.read() samples = coremark_benchmark._ParseOutputForSamples(output, 8) self.assertEqual('Coremark Score', samples[0].metric) self.assertAlmostEqual(160665.153736, s...
Tests parsing valid output from running Coremark.
testParseOutput
python
GoogleCloudPlatform/PerfKitBenchmarker
tests/linux_benchmarks/coremark_benchmark_test.py
https://github.com/GoogleCloudPlatform/PerfKitBenchmarker/blob/master/tests/linux_benchmarks/coremark_benchmark_test.py
Apache-2.0
def testParseInvalidOutput(self): """Tests failing when Coremark does not report valid output.""" with open(_SAMPLE_OUTPUT_FILE) as f: output = f.read() output = output.replace('Correct operation validated', 'Invalid run') with self.assertRaises(errors.Benchmarks.RunError): coremark_benchmar...
Tests failing when Coremark does not report valid output.
testParseInvalidOutput
python
GoogleCloudPlatform/PerfKitBenchmarker
tests/linux_benchmarks/coremark_benchmark_test.py
https://github.com/GoogleCloudPlatform/PerfKitBenchmarker/blob/master/tests/linux_benchmarks/coremark_benchmark_test.py
Apache-2.0
def testGetGccVersion(self): """Tests regex calls to parse gcc version.""" mock_vm = mock.Mock() mock_vm.RemoteCommand.return_value = None, 'gcc version 7.4.0 20190909' self.assertEqual(_TEST_GCC_VERSION, glibc.GetGccVersion(mock_vm))
Tests regex calls to parse gcc version.
testGetGccVersion
python
GoogleCloudPlatform/PerfKitBenchmarker
tests/linux_benchmarks/glibc_benchmark_test.py
https://github.com/GoogleCloudPlatform/PerfKitBenchmarker/blob/master/tests/linux_benchmarks/glibc_benchmark_test.py
Apache-2.0
def CallParseOutput(self, filename, upper_key, results, metadata): """Read sample outputs of glibc_benchmark and call ParseOutput function. Args: filename: The name of the sample output file required to run the benchmark. upper_key: The first dimension key of the glibc_output dict. re...
Read sample outputs of glibc_benchmark and call ParseOutput function. Args: filename: The name of the sample output file required to run the benchmark. upper_key: The first dimension key of the glibc_output dict. results: A list to which the ParseOutput function will append new samples ...
CallParseOutput
python
GoogleCloudPlatform/PerfKitBenchmarker
tests/linux_benchmarks/glibc_benchmark_test.py
https://github.com/GoogleCloudPlatform/PerfKitBenchmarker/blob/master/tests/linux_benchmarks/glibc_benchmark_test.py
Apache-2.0
def testParseOutputAttachesCorrectCommonMetadata(self): """Tests that a run of ParseOutput attaches the correct common metadata.""" metadata = { 'gcc': _TEST_GCC_VERSION, 'glibc_benchset': glibc_benchmark.glibc_default_benchset, 'glibc_version': glibc.GLIBC_VERSION, 'num_machines...
Tests that a run of ParseOutput attaches the correct common metadata.
testParseOutputAttachesCorrectCommonMetadata
python
GoogleCloudPlatform/PerfKitBenchmarker
tests/linux_benchmarks/glibc_benchmark_test.py
https://github.com/GoogleCloudPlatform/PerfKitBenchmarker/blob/master/tests/linux_benchmarks/glibc_benchmark_test.py
Apache-2.0
def MockVm() -> mock.Mock: """Mocks test VM and returns sample results.""" vm = mock.Mock() vm.hostname = 'localhost' path = os.path.join( os.path.dirname(__file__), '..', 'data', 'gpu_pingpong_output.txt' ) with open(path) as reader: stderr = reader.read() vm.RemoteCommand.return_value = '', st...
Mocks test VM and returns sample results.
MockVm
python
GoogleCloudPlatform/PerfKitBenchmarker
tests/linux_benchmarks/gpu_pingpong_benchmark_test.py
https://github.com/GoogleCloudPlatform/PerfKitBenchmarker/blob/master/tests/linux_benchmarks/gpu_pingpong_benchmark_test.py
Apache-2.0
def testCmd(self) -> None: """Tests GPU PingPong test command on the remote VM.""" vm = MockVm() gpu_pingpong_benchmark.Run(mock.Mock(vms=[vm, MockVm()])) vm.RemoteCommand.assert_called_with( 'PATH=/opt/conda/bin:$PATH python gpu_pingpong_test.py localhost:2000' )
Tests GPU PingPong test command on the remote VM.
testCmd
python
GoogleCloudPlatform/PerfKitBenchmarker
tests/linux_benchmarks/gpu_pingpong_benchmark_test.py
https://github.com/GoogleCloudPlatform/PerfKitBenchmarker/blob/master/tests/linux_benchmarks/gpu_pingpong_benchmark_test.py
Apache-2.0
def testSample(self) -> None: """Tests GPU PingPong test parsing code.""" samples = gpu_pingpong_benchmark.Run(mock.Mock(vms=[MockVm(), MockVm()])) expected = sample.Sample( metric='latency', value=618.9995654384239, unit='microseconds', metadata={'ping': 305.00009531252977, ...
Tests GPU PingPong test parsing code.
testSample
python
GoogleCloudPlatform/PerfKitBenchmarker
tests/linux_benchmarks/gpu_pingpong_benchmark_test.py
https://github.com/GoogleCloudPlatform/PerfKitBenchmarker/blob/master/tests/linux_benchmarks/gpu_pingpong_benchmark_test.py
Apache-2.0
def testFilename(self): """Tests the objects written filename can be parsed for an age.""" FLAGS.object_storage_region = 'us-central1-a' FLAGS.object_storage_objects_written_file_prefix = 'prefix' write_time = datetime.datetime.now() - datetime.timedelta(hours=72) with mock.patch.object( obj...
Tests the objects written filename can be parsed for an age.
testFilename
python
GoogleCloudPlatform/PerfKitBenchmarker
tests/linux_benchmarks/object_storage_service_benchmark_test.py
https://github.com/GoogleCloudPlatform/PerfKitBenchmarker/blob/master/tests/linux_benchmarks/object_storage_service_benchmark_test.py
Apache-2.0
def create_mock_vm( index: int, operation_value: float, ) -> mock.Mock: """Create mock VMs which will be used by the unit tests. Args: index: an integer which specifies index of vm in the list of vms. operation_value: a float which indicates the resume or suspend duration Returns: A mock VM....
Create mock VMs which will be used by the unit tests. Args: index: an integer which specifies index of vm in the list of vms. operation_value: a float which indicates the resume or suspend duration Returns: A mock VM.
create_mock_vm
python
GoogleCloudPlatform/PerfKitBenchmarker
tests/linux_benchmarks/suspend_resume_benchmark_test.py
https://github.com/GoogleCloudPlatform/PerfKitBenchmarker/blob/master/tests/linux_benchmarks/suspend_resume_benchmark_test.py
Apache-2.0
def testMeasureOperation(self, operation: str): """Unit test for Suspend and Resume functions.""" num_vms = 3 # Create mock vms vms_to_test = [create_mock_vm(i, 50.0 + i) for i in range(num_vms)] # Call suspend function on mock vms - generates actual samples for the test. actual_samples = geta...
Unit test for Suspend and Resume functions.
testMeasureOperation
python
GoogleCloudPlatform/PerfKitBenchmarker
tests/linux_benchmarks/suspend_resume_benchmark_test.py
https://github.com/GoogleCloudPlatform/PerfKitBenchmarker/blob/master/tests/linux_benchmarks/suspend_resume_benchmark_test.py
Apache-2.0
def vm_mock(index: int, operation_return_value: int) -> mock.Mock: """Creates a mock vm and Adds the needed vm attributes to the mock vm. Args: index: an integer which specifies index of vm in the list of vms. operation_return_value: value to return when vm operation are called Returns: A mock vm. ...
Creates a mock vm and Adds the needed vm attributes to the mock vm. Args: index: an integer which specifies index of vm in the list of vms. operation_return_value: value to return when vm operation are called Returns: A mock vm.
vm_mock
python
GoogleCloudPlatform/PerfKitBenchmarker
tests/linux_benchmarks/vm_stop_start_benchmark_test.py
https://github.com/GoogleCloudPlatform/PerfKitBenchmarker/blob/master/tests/linux_benchmarks/vm_stop_start_benchmark_test.py
Apache-2.0
def testMeasureOperation(self, operation: str): """Unit test for Stop and Start functions.""" num_vms = 3 # create mock vms vms_to_test = [vm_mock(0, 5), vm_mock(1, 6), vm_mock(2, 7)] # call Stop on vms actual_samples = getattr(vm_stop_start_benchmark, f'_Measure{operation}')( vms_to_t...
Unit test for Stop and Start functions.
testMeasureOperation
python
GoogleCloudPlatform/PerfKitBenchmarker
tests/linux_benchmarks/vm_stop_start_benchmark_test.py
https://github.com/GoogleCloudPlatform/PerfKitBenchmarker/blob/master/tests/linux_benchmarks/vm_stop_start_benchmark_test.py
Apache-2.0
def assertCallArgsEqual(self, call_args_singles, mock_method): """Compare the list of single arguments to all mocked calls in mock_method. Mock calls can be tested like this: (('x',),) == call('x') As all the mocked method calls have one single argument (ie 'x') they need to be converted into the...
Compare the list of single arguments to all mocked calls in mock_method. Mock calls can be tested like this: (('x',),) == call('x') As all the mocked method calls have one single argument (ie 'x') they need to be converted into the tuple of positional arguments tuple that mock expects. Args:...
assertCallArgsEqual
python
GoogleCloudPlatform/PerfKitBenchmarker
tests/linux_packages/azure_cli_test.py
https://github.com/GoogleCloudPlatform/PerfKitBenchmarker/blob/master/tests/linux_packages/azure_cli_test.py
Apache-2.0
def _ExtractHistogramFromMetric(results, sample_name): """Search results for given metric and extract the embedded histogram.""" for r in results: if r.metric == sample_name: return json.loads(r.metadata['histogram']) return None
Search results for given metric and extract the embedded histogram.
_ExtractHistogramFromMetric
python
GoogleCloudPlatform/PerfKitBenchmarker
tests/linux_packages/fio_test.py
https://github.com/GoogleCloudPlatform/PerfKitBenchmarker/blob/master/tests/linux_packages/fio_test.py
Apache-2.0
def testParseTpcCTPMResultsFromFile(self): """Tests output from TPCC time profile.""" FLAGS['hammerdbcli_tpcc_time_profile'].parse(True) FLAGS['hammerdbcli_tpcc_rampup'].parse(0) output = ParseTpcCTPMResultsFromFile(TPM_PER_SECOND_4_3_LOG) self.assertSampleListsEqualUpToTimestamp( output, ...
Tests output from TPCC time profile.
testParseTpcCTPMResultsFromFile
python
GoogleCloudPlatform/PerfKitBenchmarker
tests/linux_packages/hammerdb_test.py
https://github.com/GoogleCloudPlatform/PerfKitBenchmarker/blob/master/tests/linux_packages/hammerdb_test.py
Apache-2.0
def testParseTPCCWithoutTimeProfile(self): """Tests parsing metadata from the ANSYS benchmark output.""" FLAGS['hammerdbcli_tpcc_time_profile'].parse(False) vm = mock.Mock() output = ParseTpcCResults(TPCC_LOG, vm) self.assertCountEqual( output, [ sample.Sample('TPM', 2477...
Tests parsing metadata from the ANSYS benchmark output.
testParseTPCCWithoutTimeProfile
python
GoogleCloudPlatform/PerfKitBenchmarker
tests/linux_packages/hammerdb_test.py
https://github.com/GoogleCloudPlatform/PerfKitBenchmarker/blob/master/tests/linux_packages/hammerdb_test.py
Apache-2.0
def _ValidateRunLimitBenchmarksToRun(self, expected_lines): """Validates that expected lines are found in the modified hpcc.c file. Args: expected_lines: An iterable of expected lines of code. """ expected_lines = set(expected_lines) with open(os.path.join(self._temp_dir, 'hpcc.c')) as f: ...
Validates that expected lines are found in the modified hpcc.c file. Args: expected_lines: An iterable of expected lines of code.
_ValidateRunLimitBenchmarksToRun
python
GoogleCloudPlatform/PerfKitBenchmarker
tests/linux_packages/hpcc_test.py
https://github.com/GoogleCloudPlatform/PerfKitBenchmarker/blob/master/tests/linux_packages/hpcc_test.py
Apache-2.0
def testParseUserTotalTimes(self): """Test kernel time, total time parsing.""" self.assertEqual( linux_boot.ParseUserTotalTimes( 'Startup finished in 2.2s (kernel) + 1min 12.5s (userspace) ' '= 1min 14.774s' ), (2.2, 74.7), ) self.assertEqual( linu...
Test kernel time, total time parsing.
testParseUserTotalTimes
python
GoogleCloudPlatform/PerfKitBenchmarker
tests/linux_packages/linux_boot_test.py
https://github.com/GoogleCloudPlatform/PerfKitBenchmarker/blob/master/tests/linux_packages/linux_boot_test.py
Apache-2.0
def testParseSystemDCriticalChain(self): """Test systemd critical-chain output parsing.""" with open(os.path.join(self.data_dir, 'systemd1.output')) as f: self.assertEqual( linux_boot.ParseSystemDCriticalChainOutput(f.read()), 2.741 ) with open(os.path.join(self.data_dir, 'systemd2.out...
Test systemd critical-chain output parsing.
testParseSystemDCriticalChain
python
GoogleCloudPlatform/PerfKitBenchmarker
tests/linux_packages/linux_boot_test.py
https://github.com/GoogleCloudPlatform/PerfKitBenchmarker/blob/master/tests/linux_packages/linux_boot_test.py
Apache-2.0
def testCollectVmToVmSamples(self): """Test vm to vm networking result parsing.""" # Load startup script data, which ingress timestamps. with open(os.path.join(self.data_dir, 'boot.output')) as f: boot_output = f.read() # Load tcpdump output, which contains egress timestamps. self.enter_contex...
Test vm to vm networking result parsing.
testCollectVmToVmSamples
python
GoogleCloudPlatform/PerfKitBenchmarker
tests/linux_packages/linux_boot_test.py
https://github.com/GoogleCloudPlatform/PerfKitBenchmarker/blob/master/tests/linux_packages/linux_boot_test.py
Apache-2.0
def assertCallArgsEqual(self, call_args_singles, mock_method): """Compare the list of single arguments to all mocked calls in mock_method. Mock calls can be tested like this: (('x',),) == call('x') As all the mocked method calls have one single argument (ie 'x') they need to be converted into the...
Compare the list of single arguments to all mocked calls in mock_method. Mock calls can be tested like this: (('x',),) == call('x') As all the mocked method calls have one single argument (ie 'x') they need to be converted into the tuple of positional arguments tuple that mock expects. Args: ...
assertCallArgsEqual
python
GoogleCloudPlatform/PerfKitBenchmarker
tests/linux_packages/maven_test.py
https://github.com/GoogleCloudPlatform/PerfKitBenchmarker/blob/master/tests/linux_packages/maven_test.py
Apache-2.0
def testReadableVersion(self): """Test normal cases work as they should.""" with self.subTest('6.x'): self.redis.version = '6.x' self.assertEqual(self.redis.GetReadableVersion(), '6.x') with self.subTest('4.0.10'): self.redis.version = '4.0.10' self.assertEqual(self.redis.GetReadable...
Test normal cases work as they should.
testReadableVersion
python
GoogleCloudPlatform/PerfKitBenchmarker
tests/providers/aws/aws_elasticache_redis_test.py
https://github.com/GoogleCloudPlatform/PerfKitBenchmarker/blob/master/tests/providers/aws/aws_elasticache_redis_test.py
Apache-2.0
def testReadableVersionExtraneous(self): """Test weird cases just return the version number as is.""" with self.subTest('redis.8'): self.redis.version = 'redis.8' self.assertEqual(self.redis.GetReadableVersion(), 'redis.8') with self.subTest('redis 9_7_5'): self.redis.version = 'redis 9_7_...
Test weird cases just return the version number as is.
testReadableVersionExtraneous
python
GoogleCloudPlatform/PerfKitBenchmarker
tests/providers/aws/aws_elasticache_redis_test.py
https://github.com/GoogleCloudPlatform/PerfKitBenchmarker/blob/master/tests/providers/aws/aws_elasticache_redis_test.py
Apache-2.0
def AsyncTest(test_method): """Run an async method synchronously for testing.""" @functools.wraps(test_method) def Wrapped(self, *args, **kwargs): return asyncio.run(test_method(self, *args, **kwargs)) return Wrapped
Run an async method synchronously for testing.
AsyncTest
python
GoogleCloudPlatform/PerfKitBenchmarker
tests/scripts/messaging_service_scripts_e2e_main_process_test.py
https://github.com/GoogleCloudPlatform/PerfKitBenchmarker/blob/master/tests/scripts/messaging_service_scripts_e2e_main_process_test.py
Apache-2.0
def connect(self): 'connect to all the events we need' self.cidpress = self.figure.canvas.mpl_connect( 'button_press_event', self.on_press ) self.cidrelease = self.figure.canvas.mpl_connect( 'button_release_event', self.on_release ) self.cidmotion = self.figure.canvas.mpl_connect...
connect to all the events we need
connect
python
GoogleCloudPlatform/PerfKitBenchmarker
tools/object_storage_timeline.py
https://github.com/GoogleCloudPlatform/PerfKitBenchmarker/blob/master/tools/object_storage_timeline.py
Apache-2.0
def on_press(self, event): 'on button press we will see if the mouse is over us and store some data' if event.button != 3: # Only continue for right mouse button return if self.span is not None: return self.start = event.xdata self.end = event.xdata self.span = plt.axvspan(sel...
on button press we will see if the mouse is over us and store some data
on_press
python
GoogleCloudPlatform/PerfKitBenchmarker
tools/object_storage_timeline.py
https://github.com/GoogleCloudPlatform/PerfKitBenchmarker/blob/master/tools/object_storage_timeline.py
Apache-2.0
def on_motion(self, event): 'on motion we will move the rect if the mouse is over us' if self.span is None: return self.span.remove() self.end = event.xdata self.span = plt.axvspan(self.start, self.end, color='blue', alpha=0.5) canvas = self.figure.canvas axes = self.span.axes #...
on motion we will move the rect if the mouse is over us
on_motion
python
GoogleCloudPlatform/PerfKitBenchmarker
tools/object_storage_timeline.py
https://github.com/GoogleCloudPlatform/PerfKitBenchmarker/blob/master/tools/object_storage_timeline.py
Apache-2.0
def on_release(self, event): 'on release we reset the press data' if event.button != 3: # Only continue for right mouse button return if self.span is None: return self.span.remove() self.start = None self.end = None self.span = None self.background = None # redra...
on release we reset the press data
on_release
python
GoogleCloudPlatform/PerfKitBenchmarker
tools/object_storage_timeline.py
https://github.com/GoogleCloudPlatform/PerfKitBenchmarker/blob/master/tools/object_storage_timeline.py
Apache-2.0
def disconnect(self): 'disconnect all the stored connection ids' self.figure.canvas.mpl_disconnect(self.cidpress) self.figure.canvas.mpl_disconnect(self.cidrelease) self.figure.canvas.mpl_disconnect(self.cidmotion)
disconnect all the stored connection ids
disconnect
python
GoogleCloudPlatform/PerfKitBenchmarker
tools/object_storage_timeline.py
https://github.com/GoogleCloudPlatform/PerfKitBenchmarker/blob/master/tools/object_storage_timeline.py
Apache-2.0
def TempDir(delete=True, **kwargs): """Directory equivalent of tempfile.NamedTemporaryFile. When used as a context manager, yields a temporary directory which by default is removed when the context manager goes our of scope. Example usage: >>> with TempDir(prefix='perfkit') as td: ... shutil.copy('...
Directory equivalent of tempfile.NamedTemporaryFile. When used as a context manager, yields a temporary directory which by default is removed when the context manager goes our of scope. Example usage: >>> with TempDir(prefix='perfkit') as td: ... shutil.copy('test.txt', td) Args: delete: Delet...
TempDir
python
GoogleCloudPlatform/PerfKitBenchmarker
tools/side-by-side/side_by_side.py
https://github.com/GoogleCloudPlatform/PerfKitBenchmarker/blob/master/tools/side-by-side/side_by_side.py
Apache-2.0
def _GitCommandPrefix(): """Prefix for all git commands. Returns: list of strings; 'git' with an appropriate '--git-dir' flag. """ git_dir = os.path.join(os.path.dirname(__file__), '..', '..', '.git') return ['git', '--git-dir', git_dir]
Prefix for all git commands. Returns: list of strings; 'git' with an appropriate '--git-dir' flag.
_GitCommandPrefix
python
GoogleCloudPlatform/PerfKitBenchmarker
tools/side-by-side/side_by_side.py
https://github.com/GoogleCloudPlatform/PerfKitBenchmarker/blob/master/tools/side-by-side/side_by_side.py
Apache-2.0
def _GitRevParse(revision): """Returns the output of 'git rev-parse' for 'revision'.""" output = subprocess.check_output( _GitCommandPrefix() + ['rev-parse', revision] ) return output.rstrip()
Returns the output of 'git rev-parse' for 'revision'.
_GitRevParse
python
GoogleCloudPlatform/PerfKitBenchmarker
tools/side-by-side/side_by_side.py
https://github.com/GoogleCloudPlatform/PerfKitBenchmarker/blob/master/tools/side-by-side/side_by_side.py
Apache-2.0
def _GitDescribe(revision): """Returns the output of 'git describe' for 'revision'.""" output = subprocess.check_output( _GitCommandPrefix() + ['describe', '--always', revision] ) return output.rstrip()
Returns the output of 'git describe' for 'revision'.
_GitDescribe
python
GoogleCloudPlatform/PerfKitBenchmarker
tools/side-by-side/side_by_side.py
https://github.com/GoogleCloudPlatform/PerfKitBenchmarker/blob/master/tools/side-by-side/side_by_side.py
Apache-2.0
def PerfKitBenchmarkerCheckout(revision): """Yields a directory with PerfKitBenchmarker checked out to 'revision'.""" archive_cmd = _GitCommandPrefix() + ['archive', revision] logging.info('Running: %s', archive_cmd) p_archive = subprocess.Popen(archive_cmd, stdout=subprocess.PIPE) with TempDir(prefix='pkb-te...
Yields a directory with PerfKitBenchmarker checked out to 'revision'.
PerfKitBenchmarkerCheckout
python
GoogleCloudPlatform/PerfKitBenchmarker
tools/side-by-side/side_by_side.py
https://github.com/GoogleCloudPlatform/PerfKitBenchmarker/blob/master/tools/side-by-side/side_by_side.py
Apache-2.0
def _SplitLabels(labels): """Parse the 'labels' key from a PerfKitBenchmarker record. Labels are recorded in '|key:value|,|key:value|' form. This function transforms them to a dict. Args: labels: string. labels to parse. Returns: dict. Parsed 'labels'. """ result = {} for item in labels.strip...
Parse the 'labels' key from a PerfKitBenchmarker record. Labels are recorded in '|key:value|,|key:value|' form. This function transforms them to a dict. Args: labels: string. labels to parse. Returns: dict. Parsed 'labels'.
_SplitLabels
python
GoogleCloudPlatform/PerfKitBenchmarker
tools/side-by-side/side_by_side.py
https://github.com/GoogleCloudPlatform/PerfKitBenchmarker/blob/master/tools/side-by-side/side_by_side.py
Apache-2.0
def _CompareSamples(a, b, context=True, numlines=1): """Generate an HTML table showing differences between 'a' and 'b'. Args: a: dict, as output by PerfKitBenchmarker. b: dict, as output by PerfKitBenchmarker. context: boolean. Show context in diff? If False, all lines are output, even those whic...
Generate an HTML table showing differences between 'a' and 'b'. Args: a: dict, as output by PerfKitBenchmarker. b: dict, as output by PerfKitBenchmarker. context: boolean. Show context in diff? If False, all lines are output, even those which are equal. numlines: int. Passed to difflib.Htmldiff...
_CompareSamples
python
GoogleCloudPlatform/PerfKitBenchmarker
tools/side-by-side/side_by_side.py
https://github.com/GoogleCloudPlatform/PerfKitBenchmarker/blob/master/tools/side-by-side/side_by_side.py
Apache-2.0
def _MatchSamples(base_samples, head_samples): """Match items from base_samples with items from head_samples. Rows are matched using 'test', 'metric', and 'unit' fields. Args: base_samples: List of dicts. head_samples: List of dicts. Returns: List of pairs, each item of the pair containing either...
Match items from base_samples with items from head_samples. Rows are matched using 'test', 'metric', and 'unit' fields. Args: base_samples: List of dicts. head_samples: List of dicts. Returns: List of pairs, each item of the pair containing either a dict or None.
_MatchSamples
python
GoogleCloudPlatform/PerfKitBenchmarker
tools/side-by-side/side_by_side.py
https://github.com/GoogleCloudPlatform/PerfKitBenchmarker/blob/master/tools/side-by-side/side_by_side.py
Apache-2.0
def RenderResults(base_result, head_result, template_name=TEMPLATE, **kwargs): """Render the results of a comparison as an HTML page. Args: base_result: PerfKitBenchmarkerResult. Result of running against base revision. head_result: PerfKitBenchmarkerResult. Result of running against head revis...
Render the results of a comparison as an HTML page. Args: base_result: PerfKitBenchmarkerResult. Result of running against base revision. head_result: PerfKitBenchmarkerResult. Result of running against head revision. template_name: string. The filename of the template. kwargs: Additional...
RenderResults
python
GoogleCloudPlatform/PerfKitBenchmarker
tools/side-by-side/side_by_side.py
https://github.com/GoogleCloudPlatform/PerfKitBenchmarker/blob/master/tools/side-by-side/side_by_side.py
Apache-2.0
def _ClassForPercentDifference(percent_diff): """Crude highlighting of differences between runs. Samples varying by >25% are colored red. Samples varying by 5-25% are colored orange. Other samples are colored green. Args: percent_diff: float. percent difference between values. """ if...
Crude highlighting of differences between runs. Samples varying by >25% are colored red. Samples varying by 5-25% are colored orange. Other samples are colored green. Args: percent_diff: float. percent difference between values.
_ClassForPercentDifference
python
GoogleCloudPlatform/PerfKitBenchmarker
tools/side-by-side/side_by_side.py
https://github.com/GoogleCloudPlatform/PerfKitBenchmarker/blob/master/tools/side-by-side/side_by_side.py
Apache-2.0
def main(): """ Main function to spawn the train and test process. """ cfg = Config(load=True) if hasattr(cfg, "TASK_TYPE") and cfg.TASK_TYPE == "MULTI_TASK": logging.info("TASK TYPE: %s " % cfg.TASK_TYPE) inference_multi(cfg.cfg_dict) elif hasattr(cfg, "TASK_TYPE") and cfg.TASK...
Main function to spawn the train and test process.
main
python
ali-vilab/videocomposer
run_net.py
https://github.com/ali-vilab/videocomposer/blob/master/run_net.py
MIT
def DOWNLOAD_TO_CACHE(oss_key, file_or_dirname=None, cache_dir=osp.join('/'.join(osp.abspath(__file__).split('/')[:-2]), 'model_weights')): r"""Download OSS [file or folder] to the cache folder. Only the 0th process on each node will run the downloading. B...
Download OSS [file or folder] to the cache folder. Only the 0th process on each node will run the downloading. Barrier all processes until the downloading is completed.
DOWNLOAD_TO_CACHE
python
ali-vilab/videocomposer
artist/__init__.py
https://github.com/ali-vilab/videocomposer/blob/master/artist/__init__.py
MIT
def forward(self, imgs, txt_tokens): r"""imgs: [B, C, H, W] of torch.float32. txt_tokens: [B, T] of torch.long. """ xi = self.visual(imgs) xt = self.textual(txt_tokens) # normalize features xi = F.normalize(xi, p=2, dim=1) xt = F.normalize(xt, p...
imgs: [B, C, H, W] of torch.float32. txt_tokens: [B, T] of torch.long.
forward
python
ali-vilab/videocomposer
artist/models/clip.py
https://github.com/ali-vilab/videocomposer/blob/master/artist/models/clip.py
MIT
def rgb2ycbcr(img, only_y=True): '''same as matlab rgb2ycbcr only_y: only return Y channel Input: uint8, [0, 255] float, [0, 1] ''' in_img_type = img.dtype img.astype(np.float32) if in_img_type != np.uint8: img *= 255. # convert if only_y: rlt = np.dot...
same as matlab rgb2ycbcr only_y: only return Y channel Input: uint8, [0, 255] float, [0, 1]
rgb2ycbcr
python
ali-vilab/videocomposer
artist/ops/degration.py
https://github.com/ali-vilab/videocomposer/blob/master/artist/ops/degration.py
MIT
def bgr2ycbcr(img, only_y=True): '''bgr version of rgb2ycbcr only_y: only return Y channel Input: uint8, [0, 255] float, [0, 1] ''' in_img_type = img.dtype img.astype(np.float32) if in_img_type != np.uint8: img *= 255. # convert if only_y: rlt = np.dot...
bgr version of rgb2ycbcr only_y: only return Y channel Input: uint8, [0, 255] float, [0, 1]
bgr2ycbcr
python
ali-vilab/videocomposer
artist/ops/degration.py
https://github.com/ali-vilab/videocomposer/blob/master/artist/ops/degration.py
MIT
def calculate_ssim(img1, img2, border=0): '''calculate SSIM the same outputs as MATLAB's img1, img2: [0, 255] ''' #img1 = img1.squeeze() #img2 = img2.squeeze() if not img1.shape == img2.shape: raise ValueError('Input images must have the same dimensions.') h, w = img1.shape[:2] ...
calculate SSIM the same outputs as MATLAB's img1, img2: [0, 255]
calculate_ssim
python
ali-vilab/videocomposer
artist/ops/degration.py
https://github.com/ali-vilab/videocomposer/blob/master/artist/ops/degration.py
MIT
def modcrop_np(img, sf): ''' Args: img: numpy image, WxH or WxHxC sf: scale factor Return: cropped image ''' w, h = img.shape[:2] im = np.copy(img) return im[:w - w % sf, :h - h % sf, ...]
Args: img: numpy image, WxH or WxHxC sf: scale factor Return: cropped image
modcrop_np
python
ali-vilab/videocomposer
artist/ops/degration.py
https://github.com/ali-vilab/videocomposer/blob/master/artist/ops/degration.py
MIT
def analytic_kernel(k): """Calculate the X4 kernel from the X2 kernel (for proof see appendix in paper)""" k_size = k.shape[0] # Calculate the big kernels size big_k = np.zeros((3 * k_size - 2, 3 * k_size - 2)) # Loop over the small kernel to fill the big one for r in range(k_size): for ...
Calculate the X4 kernel from the X2 kernel (for proof see appendix in paper)
analytic_kernel
python
ali-vilab/videocomposer
artist/ops/degration.py
https://github.com/ali-vilab/videocomposer/blob/master/artist/ops/degration.py
MIT
def anisotropic_Gaussian(ksize=15, theta=np.pi, l1=6, l2=6): """ generate an anisotropic Gaussian kernel Args: ksize : e.g., 15, kernel size theta : [0, pi], rotation angle range l1 : [0.1,50], scaling of eigenvalues l2 : [0.1,l1], scaling of eigenvalues If l1 = l2...
generate an anisotropic Gaussian kernel Args: ksize : e.g., 15, kernel size theta : [0, pi], rotation angle range l1 : [0.1,50], scaling of eigenvalues l2 : [0.1,l1], scaling of eigenvalues If l1 = l2, will get an isotropic Gaussian kernel. Returns: k ...
anisotropic_Gaussian
python
ali-vilab/videocomposer
artist/ops/degration.py
https://github.com/ali-vilab/videocomposer/blob/master/artist/ops/degration.py
MIT
def shift_pixel(x, sf, upper_left=True): """shift pixel for super-resolution with different scale factors Args: x: WxHxC or WxH sf: scale factor upper_left: shift direction """ h, w = x.shape[:2] shift = (sf - 1) * 0.5 xv, yv = np.arange(0, w, 1.0), np.arange(0, h, 1.0) ...
shift pixel for super-resolution with different scale factors Args: x: WxHxC or WxH sf: scale factor upper_left: shift direction
shift_pixel
python
ali-vilab/videocomposer
artist/ops/degration.py
https://github.com/ali-vilab/videocomposer/blob/master/artist/ops/degration.py
MIT
def gen_kernel(k_size=np.array([15, 15]), scale_factor=np.array([4, 4]), min_var=0.6, max_var=10., noise_level=0): """" # modified version of https://github.com/assafshocher/BlindSR_dataset_generator # Kai Zhang # min_var = 0.175 * sf # variance of the gaussian kernel will be sampled between min_var an...
" # modified version of https://github.com/assafshocher/BlindSR_dataset_generator # Kai Zhang # min_var = 0.175 * sf # variance of the gaussian kernel will be sampled between min_var and max_var # max_var = 2.5 * sf
gen_kernel
python
ali-vilab/videocomposer
artist/ops/degration.py
https://github.com/ali-vilab/videocomposer/blob/master/artist/ops/degration.py
MIT
def fspecial(filter_type, *args, **kwargs): ''' python code from: https://github.com/ronaldosena/imagens-medicas-2/blob/40171a6c259edec7827a6693a93955de2bd39e76/Aulas/aula_2_-_uniform_filter/matlab_fspecial.py ''' if filter_type == 'gaussian': return fspecial_gaussian(*args, **kwargs) if...
python code from: https://github.com/ronaldosena/imagens-medicas-2/blob/40171a6c259edec7827a6693a93955de2bd39e76/Aulas/aula_2_-_uniform_filter/matlab_fspecial.py
fspecial
python
ali-vilab/videocomposer
artist/ops/degration.py
https://github.com/ali-vilab/videocomposer/blob/master/artist/ops/degration.py
MIT
def srmd_degradation(x, k, sf=3): ''' blur + bicubic downsampling Args: x: HxWxC image, [0, 1] k: hxw, double sf: down-scale factor Return: downsampled LR image Reference: @inproceedings{zhang2018learning, title={Learning a single convolutional super-res...
blur + bicubic downsampling Args: x: HxWxC image, [0, 1] k: hxw, double sf: down-scale factor Return: downsampled LR image Reference: @inproceedings{zhang2018learning, title={Learning a single convolutional super-resolution network for multiple degradations...
srmd_degradation
python
ali-vilab/videocomposer
artist/ops/degration.py
https://github.com/ali-vilab/videocomposer/blob/master/artist/ops/degration.py
MIT
def dpsr_degradation(x, k, sf=3): ''' bicubic downsampling + blur Args: x: HxWxC image, [0, 1] k: hxw, double sf: down-scale factor Return: downsampled LR image Reference: @inproceedings{zhang2019deep, title={Deep Plug-and-Play Super-Resolution for Arbit...
bicubic downsampling + blur Args: x: HxWxC image, [0, 1] k: hxw, double sf: down-scale factor Return: downsampled LR image Reference: @inproceedings{zhang2019deep, title={Deep Plug-and-Play Super-Resolution for Arbitrary Blur Kernels}, author={Zha...
dpsr_degradation
python
ali-vilab/videocomposer
artist/ops/degration.py
https://github.com/ali-vilab/videocomposer/blob/master/artist/ops/degration.py
MIT
def classical_degradation(x, k, sf=3): ''' blur + downsampling Args: x: HxWxC image, [0, 1]/[0, 255] k: hxw, double sf: down-scale factor Return: downsampled LR image ''' x = ndimage.filters.convolve(x, np.expand_dims(k, axis=2), mode='wrap') # x = filters.correla...
blur + downsampling Args: x: HxWxC image, [0, 1]/[0, 255] k: hxw, double sf: down-scale factor Return: downsampled LR image
classical_degradation
python
ali-vilab/videocomposer
artist/ops/degration.py
https://github.com/ali-vilab/videocomposer/blob/master/artist/ops/degration.py
MIT
def add_sharpening(img, weight=0.5, radius=50, threshold=10): """USM sharpening. borrowed from real-ESRGAN Input image: I; Blurry image: B. 1. K = I + weight * (I - B) 2. Mask = 1 if abs(I - B) > threshold, else: 0 3. Blur mask: 4. Out = Mask * K + (1 - Mask) * I Args: img (Numpy arr...
USM sharpening. borrowed from real-ESRGAN Input image: I; Blurry image: B. 1. K = I + weight * (I - B) 2. Mask = 1 if abs(I - B) > threshold, else: 0 3. Blur mask: 4. Out = Mask * K + (1 - Mask) * I Args: img (Numpy array): Input image, HWC, BGR; float32, [0, 1]. weight (float): ...
add_sharpening
python
ali-vilab/videocomposer
artist/ops/degration.py
https://github.com/ali-vilab/videocomposer/blob/master/artist/ops/degration.py
MIT
def degradation_bsrgan_light(image, sf=4, isp_model=None): """ This is the variant of the degradation model of BSRGAN from the paper "Designing a Practical Degradation Model for Deep Blind Image Super-Resolution" ---------- sf: scale factor isp_model: camera ISP model Returns ------- ...
This is the variant of the degradation model of BSRGAN from the paper "Designing a Practical Degradation Model for Deep Blind Image Super-Resolution" ---------- sf: scale factor isp_model: camera ISP model Returns ------- img: low-quality patch, size: lq_patchsizeXlq_patchsizeXC, range:...
degradation_bsrgan_light
python
ali-vilab/videocomposer
artist/ops/degration.py
https://github.com/ali-vilab/videocomposer/blob/master/artist/ops/degration.py
MIT
def p_sample(self, xt, t, model, model_kwargs={}, clamp=None, percentile=None, condition_fn=None, guide_scale=None): r"""Sample from p(x_{t-1} | x_t). - condition_fn: for classifier-based guidance (guided-diffusion). - guide_scale: for classifier-free guidance (glide/dalle-2). ""...
Sample from p(x_{t-1} | x_t). - condition_fn: for classifier-based guidance (guided-diffusion). - guide_scale: for classifier-free guidance (glide/dalle-2).
p_sample
python
ali-vilab/videocomposer
artist/ops/diffusion.py
https://github.com/ali-vilab/videocomposer/blob/master/artist/ops/diffusion.py
MIT
def ddim_sample(self, xt, t, model, model_kwargs={}, clamp=None, percentile=None, condition_fn=None, guide_scale=None, ddim_timesteps=20, eta=0.0): r"""Sample from p(x_{t-1} | x_t) using DDIM. - condition_fn: for classifier-based guidance (guided-diffusion). - guide_scale: for classifier...
Sample from p(x_{t-1} | x_t) using DDIM. - condition_fn: for classifier-based guidance (guided-diffusion). - guide_scale: for classifier-free guidance (glide/dalle-2).
ddim_sample
python
ali-vilab/videocomposer
artist/ops/diffusion.py
https://github.com/ali-vilab/videocomposer/blob/master/artist/ops/diffusion.py
MIT
def ddim_reverse_sample(self, xt, t, model, model_kwargs={}, clamp=None, percentile=None, guide_scale=None, ddim_timesteps=20): r"""Sample from p(x_{t+1} | x_t) using DDIM reverse ODE (deterministic). """ stride = self.num_timesteps // ddim_timesteps # predict distribution of p(x_{t-1} ...
Sample from p(x_{t+1} | x_t) using DDIM reverse ODE (deterministic).
ddim_reverse_sample
python
ali-vilab/videocomposer
artist/ops/diffusion.py
https://github.com/ali-vilab/videocomposer/blob/master/artist/ops/diffusion.py
MIT
def plms_sample(self, xt, t, model, model_kwargs={}, clamp=None, percentile=None, condition_fn=None, guide_scale=None, plms_timesteps=20): r"""Sample from p(x_{t-1} | x_t) using PLMS. - condition_fn: for classifier-based guidance (guided-diffusion). - guide_scale: for classifier-free gui...
Sample from p(x_{t-1} | x_t) using PLMS. - condition_fn: for classifier-based guidance (guided-diffusion). - guide_scale: for classifier-free guidance (glide/dalle-2).
plms_sample
python
ali-vilab/videocomposer
artist/ops/diffusion.py
https://github.com/ali-vilab/videocomposer/blob/master/artist/ops/diffusion.py
MIT
def variational_lower_bound_loop(self, x0, model, model_kwargs={}, clamp=None, percentile=None): r"""Compute the entire variational lower bound, measured in bits-per-dim. """ # prepare input and output b = x0.size(0) metrics = {'vlb': [], 'mse': [], 'x0_mse': []} # loop ...
Compute the entire variational lower bound, measured in bits-per-dim.
variational_lower_bound_loop
python
ali-vilab/videocomposer
artist/ops/diffusion.py
https://github.com/ali-vilab/videocomposer/blob/master/artist/ops/diffusion.py
MIT
def dpm_solver_sample_loop(self, noise, model, model_kwargs={}, order=2, skip_type='logSNR', method='multistep', clamp=None, percentile=None, condition_fn=None, guide_scale=None, dpm_solver_timesteps=20, algorithm_type='dpmsolver++', t_start=None, t_end=None, lower_order_final=True, denoi...
Sample using DPM-Solver-based method. - condition_fn: for classifier-based guidance (guided-diffusion). - guide_scale: for classifier-free guidance (glide/dalle-2). Please check all the parameters in `dpm_solver.sample` before using.
dpm_solver_sample_loop
python
ali-vilab/videocomposer
artist/ops/diffusion.py
https://github.com/ali-vilab/videocomposer/blob/master/artist/ops/diffusion.py
MIT
def inpaint_mcg_p_sample(self, xt, t, y, mask, model, model_kwargs={}, clamp=None, percentile=None, guide_scale=None, mcg_scale=1.0): r"""DDPM sampling step for inpainting, with Manifold Constrained Gradient (MCG) correction. """ dtype = xt.dtype # predict distribution of p(x_{t-1} | x_...
DDPM sampling step for inpainting, with Manifold Constrained Gradient (MCG) correction.
inpaint_mcg_p_sample
python
ali-vilab/videocomposer
artist/ops/diffusion.py
https://github.com/ali-vilab/videocomposer/blob/master/artist/ops/diffusion.py
MIT
def inpaint_mcg_p_sample_loop(self, noise, y, mask, model, model_kwargs={}, clamp=None, percentile=None, guide_scale=None, mcg_scale=1.0): r"""DDPM sampling loop for inpainting, with Manifold Constrained Gradient (MCG) correction. """ # prepare input b = noise.size(0) xt = noise ...
DDPM sampling loop for inpainting, with Manifold Constrained Gradient (MCG) correction.
inpaint_mcg_p_sample_loop
python
ali-vilab/videocomposer
artist/ops/diffusion.py
https://github.com/ali-vilab/videocomposer/blob/master/artist/ops/diffusion.py
MIT
def scatter(data, scatter_list=None, src=0, group=None, **kwargs): r"""NOTE: only supports CPU tensor communication. """ if get_world_size(group) > 1: return dist.scatter(data, scatter_list, src, group, **kwargs)
NOTE: only supports CPU tensor communication.
scatter
python
ali-vilab/videocomposer
artist/ops/distributed.py
https://github.com/ali-vilab/videocomposer/blob/master/artist/ops/distributed.py
MIT
def _i(tensor, t, x): r"""Index tensor using t and format the output according to x. """ shape = (x.size(0), ) + (1, ) * (x.ndim - 1) device = x.device return tensor[t.to(device)].view(shape).to(device)
Index tensor using t and format the output according to x.
_i
python
ali-vilab/videocomposer
artist/ops/dpm_solver.py
https://github.com/ali-vilab/videocomposer/blob/master/artist/ops/dpm_solver.py
MIT
def __init__( self, schedule='discrete', betas=None, alphas_cumprod=None, continuous_beta_0=0.1, continuous_beta_1=20., dtype=torch.float32): r"""Create a wrapper class for the forward SDE (VP type). *** Update:...
Create a wrapper class for the forward SDE (VP type). *** Update: We support discrete-time diffusion models by implementing a picewise linear interpolation for log_alpha_t. We recommend to use schedule='discrete' for the discrete-time diffusion models, especially for high-resolution ima...
__init__
python
ali-vilab/videocomposer
artist/ops/dpm_solver.py
https://github.com/ali-vilab/videocomposer/blob/master/artist/ops/dpm_solver.py
MIT
def marginal_log_mean_coeff(self, t): """ Compute log(alpha_t) of a given continuous-time label t in [0, T]. """ if self.schedule == 'discrete': return interpolate_fn(t.reshape((-1, 1)), self.t_array.to(t.device), self.log_alpha_array.to(t.device)).reshape((-1)) elif ...
Compute log(alpha_t) of a given continuous-time label t in [0, T].
marginal_log_mean_coeff
python
ali-vilab/videocomposer
artist/ops/dpm_solver.py
https://github.com/ali-vilab/videocomposer/blob/master/artist/ops/dpm_solver.py
MIT
def marginal_lambda(self, t): """ Compute lambda_t = log(alpha_t) - log(sigma_t) of a given continuous-time label t in [0, T]. """ log_mean_coeff = self.marginal_log_mean_coeff(t) log_std = 0.5 * torch.log(1. - torch.exp(2. * log_mean_coeff)) return log_mean_coeff - log_s...
Compute lambda_t = log(alpha_t) - log(sigma_t) of a given continuous-time label t in [0, T].
marginal_lambda
python
ali-vilab/videocomposer
artist/ops/dpm_solver.py
https://github.com/ali-vilab/videocomposer/blob/master/artist/ops/dpm_solver.py
MIT
def inverse_lambda(self, lamb): """ Compute the continuous-time label t in [0, T] of a given half-logSNR lambda_t. """ if self.schedule == 'linear': tmp = 2. * (self.beta_1 - self.beta_0) * torch.logaddexp(-2. * lamb, torch.zeros((1,)).to(lamb)) Delta = self.beta_...
Compute the continuous-time label t in [0, T] of a given half-logSNR lambda_t.
inverse_lambda
python
ali-vilab/videocomposer
artist/ops/dpm_solver.py
https://github.com/ali-vilab/videocomposer/blob/master/artist/ops/dpm_solver.py
MIT
def model_wrapper( model, noise_schedule, model_type="noise", model_kwargs={}, guidance_type="uncond", condition=None, unconditional_condition=None, guidance_scale=1., classifier_fn=None, classifier_kwargs={}): r"""Create a wrapper function for the noise prediction model. ...
Create a wrapper function for the noise prediction model. DPM-Solver needs to solve the continuous-time diffusion ODEs. For DPMs trained on discrete-time labels, we need to firstly wrap the model function to a noise prediction model that accepts the continuous time as the input. We support four types of t...
model_wrapper
python
ali-vilab/videocomposer
artist/ops/dpm_solver.py
https://github.com/ali-vilab/videocomposer/blob/master/artist/ops/dpm_solver.py
MIT
def get_model_input_time(t_continuous): """ Convert the continuous-time `t_continuous` (in [epsilon, T]) to the model input time. For discrete-time DPMs, we convert `t_continuous` in [1 / N, 1] to `t_input` in [0, 1000 * (N - 1) / N]. For continuous-time DPMs, we just use `t_continuous`....
Convert the continuous-time `t_continuous` (in [epsilon, T]) to the model input time. For discrete-time DPMs, we convert `t_continuous` in [1 / N, 1] to `t_input` in [0, 1000 * (N - 1) / N]. For continuous-time DPMs, we just use `t_continuous`.
get_model_input_time
python
ali-vilab/videocomposer
artist/ops/dpm_solver.py
https://github.com/ali-vilab/videocomposer/blob/master/artist/ops/dpm_solver.py
MIT
def cond_grad_fn(x, t_input): """ Compute the gradient of the classifier, i.e. nabla_{x} log p_t(cond | x_t). """ with torch.enable_grad(): x_in = x.detach().requires_grad_(True) log_prob = classifier_fn(x_in, t_input, condition, **classifier_kwargs) r...
Compute the gradient of the classifier, i.e. nabla_{x} log p_t(cond | x_t).
cond_grad_fn
python
ali-vilab/videocomposer
artist/ops/dpm_solver.py
https://github.com/ali-vilab/videocomposer/blob/master/artist/ops/dpm_solver.py
MIT
def model_fn(x, t_continuous): """ The noise predicition model function that is used for DPM-Solver. """ if guidance_type == "uncond": return noise_pred_fn(x, t_continuous) elif guidance_type == "classifier": assert classifier_fn is not None t_...
The noise predicition model function that is used for DPM-Solver.
model_fn
python
ali-vilab/videocomposer
artist/ops/dpm_solver.py
https://github.com/ali-vilab/videocomposer/blob/master/artist/ops/dpm_solver.py
MIT
def model_wrapper_guided_diffusion( model, noise_schedule, var_type, mean_type, model_kwargs={}, rescale_timesteps=False, num_timesteps=1000, guide_scale=None, condition_fn=None): """Create a wrapper function for the noise prediction model guided diffusion. DPM-Solver needs ...
Create a wrapper function for the noise prediction model guided diffusion. DPM-Solver needs to solve the continuous-time diffusion ODEs. For DPMs trained on discrete-time labels, we need to firstly wrap the model function to a noise prediction model that accepts the continuous time as the input. We suppor...
model_wrapper_guided_diffusion
python
ali-vilab/videocomposer
artist/ops/dpm_solver.py
https://github.com/ali-vilab/videocomposer/blob/master/artist/ops/dpm_solver.py
MIT
def __init__( self, model_fn, noise_schedule, algorithm_type="dpmsolver++", percentile=None, thresholding_max_val=1., clamp=None): r"""Construct a DPM-Solver. We support both the noise prediction model ("predicting epsilon") and the data predi...
Construct a DPM-Solver. We support both the noise prediction model ("predicting epsilon") and the data prediction model ("predicting x0"). If `predict_x0` is False, we use the solver for the noise prediction model (DPM-Solver). If `predict_x0` is True, we use the solver for the data prediction...
__init__
python
ali-vilab/videocomposer
artist/ops/dpm_solver.py
https://github.com/ali-vilab/videocomposer/blob/master/artist/ops/dpm_solver.py
MIT