code stringlengths 17 6.64M |
|---|
class SympySGD(SympyPredictingOptimizer):
collect_order = ['v', 'theta']
def __init__(self):
self.theta = Symbol('theta')
self.grad = Symbol('g')
self.weight_decay = 0
self.momentum = Symbol('\\gamma')
self.buff = Symbol('v')
self.lr = Symbol('\\eta')
s... |
class WDSympySGD(SympySGD):
def __init__(self):
super().__init__()
self.weight_decay = Symbol('\\lambda')
|
class WDSympySGDMsnag(WDSympySGD):
collect_order = ['v', 'theta', '\\phi']
def __init__(self):
super().__init__()
self.first_grad = Symbol('\\phi')
def prediction(self, nsteps):
buff_hat = self.buff
theta_hat = self.theta
for i in range(1, (nsteps + 1)):
... |
class SympyAdam(SympyPredictingOptimizer):
collect_order = ['v', 'm', 'theta']
def __init__(self):
self.theta = Symbol('theta')
self.grad = Symbol('g')
self.weight_decay = 0
(self.exp_avg, self.exp_avg_sq) = (Symbol('m'), Symbol('v'))
(self.beta1, self.beta2) = (Symbol... |
class NormalSympyAdam(SympyAdam):
def __init__(self):
super().__init__()
def prediction(self, nsteps):
d_p = 0
timestep = self.timestep
beta1 = self.beta1
beta2 = self.beta1
exp_avg = self.exp_avg
exp_avg_sq = self.exp_avg_sq
eps = self.eps
... |
def run_sim(nsteps, optimizer_cls: SympyPredictingOptimizer=SympySGD, simplify=True):
s1 = optimizer_cls()
s2 = optimizer_cls()
theta_preds = []
theta_true = []
for staleness in range(1, (nsteps + 1)):
s1.step()
theta_true.append(s1.theta)
(theta_hat, _) = s2.prediction(sta... |
def display_sim_resuts(theta_true, theta_preds, gaps, displayer=pprint):
print('True thetas:')
list(map(displayer, theta_true))
print('Theta Predictions:')
list(map(displayer, theta_preds))
print('Gaps')
list(map(displayer, gaps))
|
def run_and_display_sim(nsteps, optimizer_cls=SympySGD, displayer=pprint, simplify=True):
(theta_true, theta_preds, gaps) = run_sim(nsteps, optimizer_cls=optimizer_cls, simplify=simplify)
display_sim_resuts(theta_true, theta_preds, gaps, displayer=displayer)
return (theta_true, theta_preds, gaps)
|
class WeightStashingCachePolicy(Enum):
EVERY_BATCH = auto()
STEP_EVERY = auto()
|
class WeightStasher():
' Helper calss to handle weight stashing\n API:\n Stash during FWD pass:\n stash_current(idx)\n\n Pre backward pass:\n pop_and_load_stashed_params(idx)\n\n Post backward pass:\n # back to true weights\n\n # TODO: look to pipedream ... |
def _get_num_unique_gpus(args):
if (not hasattr(args, 'stage_to_device_map')):
raise ValueError('Need stage_to_device_map to infer number of GPUs')
else:
n_unique_gpus = len(set(args.stage_to_device_map))
return n_unique_gpus
|
def _get_supremum_staleness(args):
supremum_staleness = getattr(args, 'supremum_staleness', None)
if (supremum_staleness == 'auto'):
supremum_staleness = _get_num_unique_gpus(args)
print(f'-I- auto inferred supremum_staleness of {supremum_staleness}')
elif (supremum_staleness is not None):... |
def get_work_scheduler(args, pipe_config: Optional[PipelineConfig]=None) -> WorkScheduler:
sched_name = args.work_scheduler.lower()
kw = {}
if (sched_name == 'virtual_stages_1f1b'):
kw['num_gpus'] = _get_num_unique_gpus(args)
kw['supremum_staleness'] = _get_supremum_staleness(args)
... |
def get_fwd_bwd_string_for_stage(stage, scheduler: WorkScheduler, num_stages, num_batches) -> str:
f = 0
b = 0
s = ''
stage_depth = ((num_stages - stage) - 1)
if hasattr(scheduler, 'get_virtual_stage_depth'):
original_stage = stage
virtual_stage_depth = scheduler.get_virtual_stage_... |
def get_fwds_between_1st_and_2nd_step_from_str(s: str, step_every) -> List[int]:
all_B_idexes = [m.start() for m in re.finditer('B', s)]
first = all_B_idexes[(step_every - 1)]
second = all_B_idexes[((2 * step_every) - 1)]
c1 = Counter(s[:first])['F']
c2 = Counter(s[:second])['F']
idexes = list... |
def get_fwds_between_first_and_seconds_step_for_stage(scheduler: WorkScheduler, stage, num_stages, num_batches) -> Tuple[(List[int], bool)]:
s = get_fwd_bwd_string_for_stage(stage, scheduler, num_stages, num_batches)
step_every = scheduler.step_every
if (step_every == 1):
print('-W- with step_ever... |
def should_do_step(batch_idx, se) -> bool:
do_step = ((batch_idx % se) == (se - 1))
return do_step
|
def expected_staleness(done_fwds, done_bwds, se) -> int:
return sum([should_do_step(x, se) for x in range(done_bwds, done_fwds)])
|
def my_version(done_bwds, se) -> int:
' steps so far '
return sum([should_do_step(i, se) for i in range(done_bwds)])
|
def expected_version(done_fwds, done_bwds, se) -> Tuple[(int, int)]:
return (my_version(done_bwds, se), expected_staleness(done_fwds, done_bwds, se))
|
def backward_version(done_fwds, done_bwds, se) -> int:
return (my_version(done_bwds, se) + expected_staleness(done_fwds, done_bwds, se))
|
def get_staleness_for_stage(stage, scheduler: WorkScheduler, num_stages, num_batches, se) -> Dict[(int, Dict[(int, Any)])]:
s = get_fwd_bwd_string_for_stage(stage, scheduler, num_stages, num_batches)
d = {}
done_fwds = 0
done_bwds = 0
for c in s:
if (c == 'F'):
es = expected_st... |
def print_string_for_all_stages(num_stages, scheduler: WorkScheduler, num_batches):
stage_strings = dict()
for stage in range(num_stages):
print(f'Stage {stage}')
s = get_fwd_bwd_string_for_stage(stage, scheduler, num_stages, num_batches)
print(s)
stage_strings[stage] = s
... |
class WorkScheduler(abc.ABC):
def __init__(self, step_every, *args, **kw):
self.step_every = step_every
@abc.abstractmethod
def __call__(self, stage_depth, pipeline_depth, num_batches, done_fwds, done_bwds) -> bool:
raise NotImplementedError()
def reset(self):
pass
|
class FBScheduler(WorkScheduler):
' Note: this is not like the scheduler in pipedream.\n In pipedream all partitions except last do D forwards in "warmup state",\n here every partitions does a different number of forwards in "warmup state" \n '
def __init__(self, *args, **kw):
super(... |
class VirtualStagesFBScheduler(FBScheduler):
def __init__(self, *args, **kw):
super().__init__(*args, **kw)
self.supremum_staleness = kw['supremum_staleness']
self.num_gpus = kw['num_gpus']
self.pipeline_depth = kw['pipeline_depth']
def __call__(self, stage_depth, pipeline_de... |
class PipeDream1F1BScheduler(WorkScheduler):
def __init__(self, *args, **kw):
super().__init__(*args, **kw)
self.warmup = True
def set_warmup(self, warmup=True):
self.warmup = warmup
def __call__(self, stage_depth, pipeline_depth, num_batches, done_fwds, done_bwds):
asse... |
class SeqScheduler(WorkScheduler):
def __init__(self, *args, **kw):
super().__init__(*args, **kw)
def __call__(self, stage_depth, pipeline_depth, num_batches, done_fwds, done_bwds):
if (stage_depth == 0):
return True
if (done_fwds == num_batches):
return False... |
class Synchronous1F1BScheduler(WorkScheduler):
' "1f1b-gpipe.\n First scheduler I implemented in simulation 1.5 years ago...\n '
def __init__(self, *args, **kw):
super().__init__(*args, **kw)
assert hasattr(self, 'step_every')
def __call__(self, stage_depth, pipeline_depth, num... |
class GpipeScheduler(WorkScheduler):
'\n GPipe scheduler with num_micro_batches = step_every.\n Supports shorter "last batch".\n\n NOTE:\n User responsibility to check that\n (1) last_batch_size % (normal_batch_size // step_every) == 0\n (2) normal_batch_size ... |
class SmallerLastBatchPolicy(Enum):
ProportionalStep = auto()
DropReminder = auto()
|
def is_huggingface_transformer(args):
if getattr(args, 'is_huggingface_transformer', False):
return True
return (args.model in pipe.models.transformers_cfg.MODEL_TOKENIZER_AND_CONFIG_FUNCTIONS.keys())
|
def create_comm_handler(args, comm_init_args, device) -> CommunicationHandlerBase:
handler_cls = get_auto_comm_handler_cls(args.distributed_backend, args.cpu)
comm_handler = handler_cls(args.rank, args.local_rank, args.distributed_backend, args.world_size, args.num_stages, args.stage, *comm_init_args, args.cp... |
def create_comm_handler_v2(args, comm_init_args, device, v2_args) -> CommunicationHandlerBase:
handler_cls = MultiprocessingCommunicationHandler
comm_handler = handler_cls(*v2_args, args.rank, args.local_rank, args.distributed_backend, args.world_size, args.num_stages, args.stage, *comm_init_args, args.cpu, a... |
def get_lr_scheduler(args, optimizer):
if hasattr(args, 'lr_scheduler'):
attr = getattr(args, 'lr_scheduler')
preproc_lr_scheduler_args(args)
scheduler_cls = get_lr_scheduler_class(args)
scheduler = scheduler_cls(optimizer, **attr['args'])
return scheduler
|
def preproc_lr_scheduler_args(args):
attr = getattr(args, 'lr_scheduler')
preproc_args = attr.get('preproc_args', None)
if preproc_args:
for (arg_name, preproc_command) in preproc_args.items():
if (preproc_command == 'epochs_to_steps'):
if (args.steps > 0):
... |
def get_lr_scheduler_class(args):
attr = getattr(args, 'lr_scheduler')
if (attr['type'] in pipe.optimizers.lr_scheduler.ADDITIONAL_AVAILABLE_LR_SCHEDULERS):
scheduler_cls = pipe.optimizers.lr_scheduler.ADDITIONAL_AVAILABLE_LR_SCHEDULERS[attr['type']]
else:
scheduler_cls = getattr(torch.opt... |
def get_sched_aware_stuff(args):
attr = getattr(args, 'lr_scheduler')
scheduler_cls = get_lr_scheduler_class(args)
sched_aware_stuff = (scheduler_cls, attr['args'])
return sched_aware_stuff
|
def get_gap_aware(args, optimizer):
if (not hasattr(args, 'gap_aware')):
return None
gap_aware_args = getattr(args, 'gap_aware')['args']
optimizer_type = getattr(args, 'optimizer')['type']
if ((not (optimizer_type == 'sgd1')) and (not getattr(args, 'weight_stashing', False))):
raise No... |
def try_replace_prediction_with_nesterov(args):
optimizer_type = getattr(args, 'optimizer')['type']
if (('sgd' in optimizer_type) and getattr(args, 'nesterov_set_for_last_partition', False)):
tmp = args.optimizer['args']
if (not tmp.get('nesterov', False)):
pred = getattr(args, 'we... |
def get_weight_predictor(args, optimizer, scheduler=None, true_weights_storage=None):
'\n Returns:\n weight_predictor,\n nag_with_predictor: bool\n '
assert (true_weights_storage is not None)
if (not hasattr(args, 'weight_prediction')):
return (None, None)
optim... |
def get_sched_aware_predictor(args, optimizer, scheduler):
optimizer_type = getattr(args, 'optimizer')['type']
pred = getattr(args, 'weight_prediction')
sched_predictor = None
if pred['args'].get('sched_aware', False):
print('-I- using sched aware weight prediction')
assert (scheduler ... |
def get_ngpus_per_node(args):
nnodes = args.nnodes
if (not hasattr(args, 'ngpus_per_node')):
if ((args.world_size % nnodes) != 0):
raise NotImplementedError()
ngpus_per_node = ([(args.world_size // nnodes)] * nnodes)
else:
ngpus_per_node = args.ngpus_per_node
assert... |
def get_device_for_rank(args, rank, local_rank):
nnodes = args.nnodes
ngpus_per_node = get_ngpus_per_node(args)
if hasattr(args, 'stage_to_device_map'):
stage_to_device_map = args.stage_to_device_map
cuda_device_id = stage_to_device_map[rank]
if (nnodes > 1):
for (node_... |
def get_rank_to_device_map(args):
if (args.nnodes == 1):
local_ranks = list(range(args.world_size))
else:
ngpus_per_node = get_ngpus_per_node(args)
local_ranks = list()
for n in ngpus_per_node:
local_ranks.extend(range(n))
return {rank: get_device_for_rank(args,... |
def test_rank_to_device_map(world_size=8, nnodes=1, cpu=False):
from types import SimpleNamespace
args = SimpleNamespace(cpu=cpu, world_size=world_size, nnodes=nnodes)
print(get_rank_to_device_map(args))
|
def hack_trainer_type_to_gap_aware(args, stage_depth=None):
" replaces TRAINER with TRAINER_gap_aware,\n according to parsed policy\n SUPPORTED_POLICIES = {\n 'almost_last_partition', \n 'all_except_last',\n 'all_except_last_two'\n }\n # TODO: polic... |
def get_optimizer_cls(args, has_gap_aware):
optimizer_type = args.optimizer['type']
if (has_gap_aware and (optimizer_type in {'adam', 'adamw'})):
optimizer_type += '_record_step'
optimizer_cls = AVAILBALE_OPTIMIZERS.get(optimizer_type)
assert (optimizer_cls is not None), f'{optimizer_type} not... |
def tuplify(listything):
if isinstance(listything, list):
return tuple(map(tuplify, listything))
if isinstance(listything, dict):
return {k: tuplify(v) for (k, v) in listything.items()}
return listything
|
def get_optimizer(args, optimizer_cls, parameters):
assert isinstance(parameters, list)
if (len(parameters) == 0):
if (not getattr(args, 'allow_stateless', False)):
raise ValueError(f'Got stateless partition {args.stage}, if this is wanter, set "allow_stateless": true')
else:
... |
def preproc_data(args, cache=None, save_cache=True):
print(f'Loading partitioned model and dataset...')
if (cache is None):
handler = pipe.models.AVAILABLE_MODELS.get(args.model)
if save_cache:
cache = handler
else:
handler = cache
parsed_config = parse_config.Parti... |
def prepare_pipeline(args, shared_ctx=None, comm_version=1):
is_gpipe = ('gpipe' == args.work_scheduler.lower())
if args.is_multiprocessing_worker:
comm_version = 2
local_rank_to_device_map = get_rank_to_device_map(args)
device = local_rank_to_device_map[args.local_rank]
if (not args.cpu):... |
def synchronize_dataloaders_length(args, is_first_partition: bool, logger, eval_dl: DataLoader, train_dl: DataLoader):
if (args.rank == 0):
assert is_first_partition
(train_dl_len, eval_dl_len) = (len(train_dl), len(eval_dl))
(train_dataset_len, eval_dataset_len) = (len(train_dl.dataset), ... |
def get_optimizer_parameter_groups(args, partition):
if is_huggingface_transformer(args):
model = partition.partition
opt_args = args.optimizer['args']
no_decay = {'bias', 'LayerNorm.weight', 'T5LayerNorm.weight'}
optimizer_grouped_parameters = [{'params': [p for (n, p) in model.na... |
def run_function(func, cfg, q):
gpu = q.get()
os.environ['CUDA_VISIBLE_DEVICES'] = str(gpu)
print(f'# GPU:{gpu}')
func(**cfg)
q.put(gpu)
|
def run_function_on_several_gpus(required_gpus, func, cfg, q):
gpus = [str(q.get()) for _ in range(required_gpus)]
os.environ['CUDA_VISIBLE_DEVICES'] = ','.join(gpus)
print(f'# GPUs:{gpus}')
func(**cfg)
for gpu in gpus:
q.put(gpu)
|
def prepare_gpu_queue(manager, NUM_AVAIALBLE_GPUS, CUDA_VISIBLE_DEVICES=None):
q = manager.Queue()
if CUDA_VISIBLE_DEVICES:
for i in CUDA_VISIBLE_DEVICES:
q.put(i)
else:
for i in range(NUM_AVAIALBLE_GPUS):
q.put(i)
return q
|
def map_to_several_limited_gpus(func, configs, gpus_per_config, NUM_AVAIALBLE_GPUS, CUDA_VISIBLE_DEVICES=None):
with Manager() as manager:
q = prepare_gpu_queue(manager, NUM_AVAIALBLE_GPUS, CUDA_VISIBLE_DEVICES)
if (not isinstance(gpus_per_config, list)):
gpus_per_config = [gpus_per_co... |
def pop_from_cfg(cfg, name):
attr = cfg.pop(name)
return (cfg, attr)
|
def pop_FUNC_from_cfg(cfg):
return pop_from_cfg(cfg, name='FUNC')
|
def pop_REQUIRED_GPUS_from_cfg(cfg):
return pop_from_cfg(cfg, name='REQUIRED_GPUS')
|
def flexible_map_to_several_limited_gpus(configs, NUM_AVAIALBLE_GPUS, CUDA_VISIBLE_DEVICES=None):
with Manager() as manager:
q = prepare_gpu_queue(manager, NUM_AVAIALBLE_GPUS, CUDA_VISIBLE_DEVICES)
gpus_per_config = []
funcs = []
cfgs = []
for cfg in configs:
(c... |
def map_to_limited_gpus(func, configs, NUM_AVAIALBLE_GPUS, CUDA_VISIBLE_DEVICES=None):
with Manager() as manager:
q = manager.Queue()
if CUDA_VISIBLE_DEVICES:
for i in CUDA_VISIBLE_DEVICES:
q.put(i)
else:
for i in range(NUM_AVAIALBLE_GPUS):
... |
class RunGridHelper():
'\n Example: running on 4 GPUs:\n\n helper = RunGridHelper(gpu_list=[0,1,2,3])\n helper.add_runs("python main.py", dict(seed=[42, 12]), num_gpus=1)\n helper.run()\n '
def __init__(self, verbose=True, test=False, gpu_list=None):
self.grids = []
self.gpu_li... |
def call_function(COMMAND, *args, _verbose=True, _test=False, **kw):
'\n Example:\n The following:\n base_command = "python main.py"\n call_function(base_command, **dict(seed=42))\n\n calls:\n python main.py --seed 42\n\n '
sargs = ('--' + ' --'.join([f'{i}... |
def subprocess_func(COMMAND, *args, **kw):
sargs = ('--' + ' --'.join([f'{i} {v}' for (i, v) in kw.items()]))
command_line = f'{COMMAND} {sargs}'
args = shlex.split(command_line)
print(f'-I- Runnning: {command_line}')
p = subprocess.Popen(args)
p.wait()
|
def run_grid_on(COMMAND, param_grid, gpu_list, skip_first=0):
configs = ParameterGrid(param_grid)
if (skip_first > 0):
print(f'-I- Skipping first {skip_first} configs')
print(f'-I- Skipping: {list(configs)[:skip_first]}')
configs = list(configs)[skip_first:]
func = partial(subproce... |
def run_grid_on_multi_gpu_per_run(COMMAND, param_grid, gpu_list, gpus_per_config=1):
configs = ParameterGrid(param_grid)
func = partial(call_function, COMMAND)
map_to_several_limited_gpus(func, configs, gpus_per_config, len(gpu_list), CUDA_VISIBLE_DEVICES=gpu_list)
|
def infer_number_of_gpus(COMMAND):
raise NotImplementedError()
|
def training_loop(args, logger, train_dl, test_dl, is_last_partition, partition: SinglePartitionManager, statistics: Stats, train_dl_len, test_dl_len, samplers):
last_batch_smaller_n_micro_batches_policy = getattr(args, 'last_batch_smaller_n_micro_batches_policy', DEFAULT_STEP_EVERY_SMALLER_LAST_BATCH_POLICY)
... |
def get_micro_batches_until_flush(args, train_batches_limit, steps, step_every_smaller_last_batch_policy, logger, partition):
if (args.steps > 0):
steps_left = (args.steps - steps)
batches_left = (steps_left * args.step_every)
train_batches_limit_to_use = min(train_batches_limit, batches_l... |
def approximate_checkpoint_every_x_epochs(args, train_dl_len):
save_checkpoint_every_x_epochs = getattr(args, 'save_checkpoint_every_x_steps', None)
approx_step_per_epoch = (train_dl_len // args.step_every)
if (save_checkpoint_every_x_epochs is not None):
save_checkpoint_every_x_epochs = (save_che... |
def should_stop_early(args, valid_loss, logger):
if (valid_loss is None):
return False
if (args.patience <= 0):
return False
def is_better(a, b):
return ((a > b) if getattr(args, 'maximize_best_checkpoint_metric', False) else (a < b))
prev_best = getattr(should_stop_early, 'be... |
class CheckpointsSaver():
def __init__(self, args):
self.args = args
self.num_saved_checkpoints = 0
if getattr(args, 'save_checkpoints', False):
assert hasattr(args, 'checkpoints_save_dir')
os.makedirs(args.checkpoints_save_dir, exist_ok=True)
else:
... |
class MyTestCase(unittest.TestCase):
def test_our_loader_vs_timm_ViT_B_16(self):
url1 = 'https://storage.googleapis.com/vit_models/imagenet21k/ViT-B_16.npz'
state_dict1 = load_state_dict_from_url(url1)
model = vit_base_patch16_384_in21k(pretrained=False)
_fix_pos_embed(model, stat... |
def skip_property_member(app, what, name, obj, skip, options):
if isinstance(obj, property):
return True
|
def setup(app):
app.connect('autodoc-skip-member', skip_property_member)
|
def multiply_with_arccos(x, y):
return (x * np.arccos(y))
|
def fetch_logged_data(run_id):
client = mlflow.MlflowClient()
data = client.get_run(run_id).data
artifacts = [f.path for f in client.list_artifacts(run_id, 'model')]
return (data.params, data.metrics, artifacts)
|
def func(x):
return ((np.sin((3 * x)) * x) * x)
|
def func(x):
return ((np.sin((3 * x)) * x) * x)
|
def generate_y(x):
u = (x * np.pi)
return (np.sin(u) / u)
|
def func(x):
return ((np.sin((3 * x)) * x) * x)
|
class ChebyshevRx(EncodingCircuitBase):
'\n Simple Chebyshev encoding circuit build from Rx gates\n\n **Example for 4 qubits, a 2 dimensional feature vector and 2 layers:**\n\n .. plot::\n\n from squlearn.encoding_circuit import ChebyshevRx\n pqc = ChebyshevRx(4, 2, 2)\n pqc.draw(ou... |
class ChebyshevTower(EncodingCircuitBase):
'\n A feature-map that is based on the Chebyshev Tower encoding.\n\n **Example for 4 qubits, a 2 dimensional feature vector, 2 Chebyshev terms per feature,\n and 2 layers:**\n\n .. plot::\n\n from squlearn.encoding_circuit import ChebyshevTower\n ... |
class HighDimEncodingCircuit(EncodingCircuitBase):
'\n The high-dimensional encoding circuit from reference [1].\n\n A encoding circuit that can be used for the classification of high-dimensional data.\n\n **Example for 5 qubits, a 23 dimensional feature vector and 2 layers:**\n\n .. plot::\n\n ... |
class HubregtsenEncodingCircuit(EncodingCircuitBase):
'\n Creates the data reuploading encoding circuit as presented in reference [1].\n\n **Example for 4 qubits, a 2 dimensional feature vector, 2 layers:**\n\n .. plot::\n\n from squlearn.encoding_circuit import HubregtsenEncodingCircuit\n ... |
class MultiControlEncodingCircuit(EncodingCircuitBase):
'\n Encoding circuit with HZ encoding followed by controlled Rx, Ry Rz rotations.\n\n **Example for 4 qubits, a 2 dimensional feature vector and 1 layer:**\n\n .. plot::\n\n from squlearn.encoding_circuit import MultiControlEncodingCircuit\n ... |
class ParamZFeatureMap(EncodingCircuitBase):
'\n Parameterized Z feature map with optional CNOT gates between the default layers.\n\n This encoding circuit is based on Qiskit\'s :class:`qiskit.circuit.library.ZFeatureMap`.\n\n **Example for 4 qubits, a 2 dimensional feature vector and 2 layers with enta... |
class QiskitEncodingCircuit(EncodingCircuitBase):
'\n Wrapper to create sQUlearn encoding circuits from the `Qiskit circuit library\n <https://qiskit.org/documentation/apidoc/circuit_library.html>`_.\n\n **Example: create a encoding circuit from Qiskit TwoLocal map**\n\n .. jupyter-execute::\n\n ... |
class YZ_CX_EncodingCircuit(EncodingCircuitBase):
'\n Creates the YZ-CX Encoding Circuit from reference [1].\n\n **Example for 4 qubits, a 4 dimensional feature vector, 2 layers and c = 2.0:**\n\n .. plot::\n\n from squlearn.encoding_circuit import YZ_CX_EncodingCircuit\n pqc = YZ_CX_Encodi... |
class EncodingCircuitDerivatives():
'\n Class for automatic differentiation of encoding circuits.\n\n This class allows to compute derivatives of a encoding circuit with respect to its parameters\n by utilizing the parameter-shift rule.\n The derivatives can be obtained by the method :meth:`get_deriva... |
class VariableGroup():
'\n class for one variable group e.g. x1, x2, p1,..., which saves the dimension of one variable\n '
def __init__(self, variable_name: str, size=None):
'\n Args:\n variable_name [String]: the name of the variable type, which one can see, if he draws the c... |
class _operation():
'\n parent class for a quantum operation. Each gate layer stands for one operation.\n '
def __init__(self, num_qubits: int, variablegroup_tuple: tuple, map=None):
'\n Attributes:\n -----------\n\n Attributes:\n num_qubits: The number of all qu... |
class _H_operation(_operation):
'class for a H operation'
def get_circuit(self, var_param_assignment=None):
QC = QuantumCircuit(self.num_qubits)
QC.h(range(self.num_qubits))
return QC
|
class _X_operation(_operation):
'class for a X operation'
def get_circuit(self, var_param_assignment=None):
QC = QuantumCircuit(self.num_qubits)
QC.x(range(self.num_qubits))
return QC
|
class _Y_operation(_operation):
'class for a Y operation'
def get_circuit(self, var_param_assignment=None):
QC = QuantumCircuit(self.num_qubits)
QC.y(range(self.num_qubits))
return QC
|
class _Z_operation(_operation):
'class for a Z operation'
def get_circuit(self, var_param_assignment=None):
QC = QuantumCircuit(self.num_qubits)
QC.z(range(self.num_qubits))
return QC
|
class _Id_operation(_operation):
'class for an identity operation'
def get_circuit(self, var_param_assignment=None):
QC = QuantumCircuit(self.num_qubits)
QC.id(range(self.num_qubits))
return QC
|
class _S_operation(_operation):
'class for a S operation'
def get_circuit(self, var_param_assignment=None):
QC = QuantumCircuit(self.num_qubits)
QC.s(range(self.num_qubits))
return QC
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.