Best Python code snippet using autotest_python
TransformCxCascade.py
Source:TransformCxCascade.py  
1import logging2from qiskit.dagcircuit import DAGCircuit3from qiskit.extensions import CXGate, U2Gate4from qiskit.transpiler import TransformationPass, TranspilerError5from qiskit.transpiler.passes import Unroller, Optimize1qGates, CXCancellation6from qiskit.qasm import pi7logger = logging.getLogger(__name__)8class TransformCxCascade(TransformationPass):9    """10    Finds CNOT cascades int the dag and transform them into nearest-neighbor CNOT sequences,11    which are more easily mapped over a real device coupling map::12        ---x--x--x--x---           --------x--------13           |  |  |  |                      |14        ---o--|--|--|---           ------x-o-x------15              |  |  |                    |   |16        ------o--|--|---    --->   ----x-o---o-x----17                 |  |                  |       |18        ---------o--|---           --x-o-------o-x--19                    |                |           |20        ------------o---           --o-----------o--21        ---o--o--o--o---           -H-------x-------H-22           |  |  |  |                       |23        ---x--|--|--|---           -H-----x-o-x-----H-24              |  |  |                     |   |25        ------x--|--|---    --->   -H---x-o---o-x---H-26                 |  |                   |       |27        ---------x--|---           -H-x-o-------o-x-H-28                    |                 |           |29        ------------x---           -H-o-----------o-H-30    """31    def __init__(self):32        """TransformCxCascade initializer.33        Raises:34            TranspilerError: if run after the layout has been set.35        """36        super().__init__()37        if self.property_set['layout']:38            raise TranspilerError('TransformCxCascade pass must be run before any layout has been set.')39        self.requires.append(Unroller(['u1', 'u2', 'u3', 'cx', 'id']))40        self._num_qubits = None41        self._wires_to_id = {}42        self._id_to_wires = {}43        self._layers = None44        self._extra_layers = None45        self._skip = []46    def run(self, dag):47        """48        Run the CNOTCascadesTransform pass over a dag circuit.49        After the transformation, proceeds to check for possible one-qubit gates optimizations and50        CNOT cancellations, as subsequent CNOT nearest-neighbor sequences could create51        the opportunity for useful circuit simplifications.52        Args:53            dag (DAGCircuit): the dag circuit to be searched for CNOT cascades.54        Returns:55            new_dag (DAGCircuit): a new dag where all CNOT cascades have been transformed.56        """57        # prepare new dag58        new_dag = DAGCircuit()59        new_dag.name = dag.name60        self._num_qubits = dag.num_qubits()61        for q_reg in dag.qregs.values():62            new_dag.add_qreg(q_reg)63        for c_reg in dag.cregs.values():64            new_dag.add_creg(c_reg)65        i = 066        for q_reg in dag.qregs.values():67            for q in q_reg:68                self._wires_to_id[q] = i69                self._id_to_wires[i] = q70                i += 171        depth = new_dag.depth()72        while True:73            new_dag = Optimize1qGates().run(new_dag)74            new_dag = CXCancellation().run(new_dag)75            new_depth = new_dag.depth()76            if new_depth < depth:77                depth = new_depth78            else:79                break80        # get dag layers81        self._layers = [layer['graph'] for layer in dag.layers()]82        # this is the list of new layers for the nearest-neighbor CNOT sequences83        self._extra_layers = {l: [] for l in range(len(self._layers))}84        # loop through all layers85        for i, layer in enumerate(self._layers):86            if i != 0:87                # add nearest-neighbor CNOT sequences in the right layer88                for gate in self._extra_layers[i - 1]:89                    new_dag.apply_operation_back(*gate)90            # check all gates in the layer91            for gate in layer.op_nodes():92                temp = None93                # do not add gates that have been used in the transformation process94                if gate in self._skip:95                    continue96                # every cnot could be the starting point for a CNOT cascade97                elif gate.name == 'cx':98                    logger.debug('Check Cascade %s with qargs: %s\n' % (gate.name, gate.qargs))99                    # check for a CNOT cascade100                    temp = self.check_cascade(gate, i)101                    if temp is not None:102                        logger.info('Cascade Starts at %s with qargs: %s\n' % (gate.name, gate.qargs))103                        self._skip.extend(temp)104                    else:105                        logger.debug(106                            'Check Inverse Cascade at %s with qargs: %s\n' % (gate.name, gate.qargs))107                        # check for an inverted CNOT cascade108                        temp = self.check_inverse_cascade(gate, i)109                        if temp is not None:110                            logger.info(111                                'Inverse Cascade Starts at %s with qargs: %s\n' % (gate.name, gate.qargs))112                            self._skip.extend(temp)113                        else:114                            # apply the CNOT if no cascade was found115                            self._skip.append(gate)116                            logger.debug(117                                'Found Nothing at %s with qargs: %s\n' % (gate.name, gate.qargs))118                            new_dag.apply_operation_back(gate.op, gate.qargs, gate.cargs, gate.condition)119                else:120                    self._skip.append(gate)121                    new_dag.apply_operation_back(gate.op, gate.qargs, gate.cargs, gate.condition)122        logger.debug('Cascades found: %s' % str(self._extra_layers))123        # optimize dag after transformation124        depth = new_dag.depth()125        while True:126            new_dag = Optimize1qGates().run(new_dag)127            new_dag = CXCancellation().run(new_dag)128            new_depth = new_dag.depth()129            if new_depth < depth:130                depth = new_depth131            else:132                break133        return new_dag134    def check_cascade(self, gate, layer_id):135        """Searches for a CNOT cascade, a sequence of CNOT gates where the target qubit136        is the same for every CNOT while the control changes, and transforms it137        into a nearest-neighbor CNOT sequence ::138            ---x--x--x--x---           --------x--------139               |  |  |  |                      |140            ---o--|--|--|---           ------x-o-x------141                  |  |  |                    |   |142            ------o--|--|---    --->   ----x-o---o-x----143                     |  |                  |       |144            ---------o--|---           --x-o-------o-x--145                        |                |           |146            ------------o---           --o-----------o--147        Args:148            gate (DAGNode): first CNOT of a possible CNOT cascade.149            layer_id (int): layer index of the CNOT.150        Returns:151            skip (list): list of gates to be skipped as part of the CNOT cascade,152            may include one-qubit gates that appears before or after the cascade.153        """154        target = self._wires_to_id[gate.qargs[1]]155        control = self._wires_to_id[gate.qargs[0]]156        controls = [control]157        skip = [gate]158        # qubits already added to the CNOT sequence159        used = set()160        used.add(target)161        used.add(control)162        # qubits that cannot be used anymore163        off_limits = set()164        before = {}165        after = []166        # flag to identify the direction of the cascade167        descending = False168        if control > target:169            descending = True170        count = 0171        last_layer = layer_id172        double_break = False173        # loop through layers until a max limit is reached174        while count < min([2 * (self._num_qubits - 1), len(self._layers) - layer_id]):175            for gate in self._layers[layer_id + count].op_nodes():176                logger.debug('Last layer: %d' % last_layer)177                logger.debug('Layer: %d' % (layer_id + count))178                logger.debug('Off limits: %s' % off_limits)179                logger.debug('Gate Name: %s\tType: %s\tQargs: %s\tCargs: %s\tCond: %s' % (180                    gate.name, gate.type, gate.qargs, gate.cargs, gate.condition))181                if gate in self._skip:182                    for qarg in gate.qargs:183                        if self._wires_to_id[qarg] == target:184                            double_break = True185                            break186                elif gate not in skip:187                    if gate.name == 'cx' and gate not in self._skip:188                        g_control = self._wires_to_id[gate.qargs[0]]189                        g_target = self._wires_to_id[gate.qargs[1]]190                        logger.debug('Check CNOT Name: %s\tType: %s\tQargs: %s\tCargs: %s\tCond: %s' % (191                            gate.name, gate.type, [g_control, g_target], gate.cargs, gate.condition))192                        if g_control == target:193                            double_break = True194                            break195                        if g_control in off_limits or g_target in off_limits:196                            off_limits.add(g_control)197                            off_limits.add(g_target)198                            if g_control not in used:199                                used.add(g_control)200                            if g_target not in used:201                                used.add(g_target)202                            logger.debug('CNOT Off limits')203                            continue204                        logger.debug('Used: %s' % str(used))205                        logger.debug('Controls: %s' % str(controls))206                        logger.debug('Control-G_control: %d-%d' % (control, g_control))207                        logger.debug('Target-G_target: %d-%d' % (target, g_target))208                        # chek that the CNOT is part of the cascade209                        a = (g_target == target and g_control not in controls and g_control not in used)210                        b = (descending is True and g_control > target) or (descending is False and g_control < target)211                        logger.debug('A: %s B: %s Descending: %s\n' % (a, b, descending))212                        if a and b:213                            controls.append(g_control)214                            used.add(g_control)215                            skip.append(gate)216                        # check if the CNOT interrupts the cascade217                        elif g_target != target and g_control != target:218                            # remember to put the CNOT after the transformation219                            if g_target not in used and g_control not in used:220                                if last_layer < layer_id + count:221                                    last_layer = layer_id + count222                            # updates used and off limits qubits when necessary223                            else:224                                off_limits.add(g_control)225                                off_limits.add(g_target)226                                if last_layer > layer_id + count - 1:227                                    last_layer = layer_id + count - 1228                                if g_control not in used:229                                    used.add(g_control)230                                if g_target not in used:231                                    used.add(g_target)232                        else:233                            # break the loop if the CNOT interrupts the cascade234                            double_break = True235                            break236                    else:237                        # ignore gates acting on off limits qubits238                        double_continue = False239                        for qarg in gate.qargs:240                            if self._wires_to_id[qarg] in off_limits:241                                double_continue = True242                                continue243                        if double_continue is True:244                            continue245                        # for special multi-qubits gates, update used and off limits qubits properly,246                        # break the loop if necessary247                        if gate.name in ["barrier", "snapshot", "save", "load", "noise"]:248                            qargs = [self._wires_to_id[qarg] for qarg in gate.qargs]249                            if target in qargs:250                                if last_layer > layer_id + count - 1:251                                    last_layer = layer_id + count - 1252                                double_break = True253                                break254                            u = []255                            not_u = []256                            for qarg in qargs:257                                if qarg in used:258                                    off_limits.add(qarg)259                                    u.append(qarg)260                                else:261                                    not_u.append(qarg)262                            if len(u) == len(qargs):263                                # the transformation must be applied before this gate264                                if last_layer > layer_id + count - 1:265                                    last_layer = layer_id + count - 1266                            elif len(u) == 0:267                                # the transformation must be applied after this gate268                                if last_layer < layer_id + count:269                                    last_layer = layer_id + count270                            else:271                                # the transformation must be applied before this gate272                                if last_layer > layer_id + count - 1:273                                    last_layer = layer_id + count - 1274                                for qarg in not_u + u:275                                    used.add(qarg)276                                    off_limits.add(qarg)277                        else:278                            # check if one-qubits gates either interrupt the cascade, can be applied after or before279                            qarg = self._wires_to_id[gate.qargs[0]]280                            logger.debug(gate.op.__class__)281                            logger.debug('Gate Name: %s\tType: %s\tQarg: %s\tCarg: %s\tCond: %s' % (282                                gate.name, gate.type, qarg, gate.cargs, gate.condition))283                            if qarg == target:284                                logger.debug('After')285                                after.append(gate)286                                skip.append(gate)287                                double_break = True288                                break289                            if qarg not in used:290                                logger.debug('Before')291                                if qarg not in before:292                                    before[qarg] = []293                                before[qarg].append(gate)294                                skip.append(gate)295                            else:296                                logger.debug('After')297                                after.append(gate)298                                skip.append(gate)299            count += 1300            if double_break is True:301                break302        # if a cascade was found303        if len(controls) > 1:304            logger.debug('Found Cascade from layer %d to %d\n' % (layer_id, last_layer))305            if descending is True:306                controls = sorted(controls)307            else:308                controls = sorted(controls, reverse=True)309            # apply all gates that were encountered before the cascade310            for u in before:311                for gate in before[u]:312                    self._extra_layers[last_layer].append(313                        (gate.op.__class__(*gate.op.params), gate.qargs, gate.cargs, gate.condition))314            # apply the transformation315            for i in range(len(controls) - 1, 0, -1):316                self._extra_layers[last_layer].append((CXGate(),317                                                       [self._id_to_wires[controls[i]],318                                                        self._id_to_wires[controls[i - 1]]], []))319            self._extra_layers[last_layer].append(320                (CXGate(), [self._id_to_wires[controls[0]], self._id_to_wires[target]], []))321            for i in range(len(controls) - 1):322                self._extra_layers[last_layer].append((CXGate(),323                                                       [self._id_to_wires[controls[i + 1]],324                                                        self._id_to_wires[controls[i]]], []))325            # apply all gates that were encountered after the cascade326            for gate in after:327                self._extra_layers[last_layer].append(328                    (gate.op.__class__(*gate.op.params), gate.qargs, gate.cargs, gate.condition))329        else:330            skip = None331        return skip332    def check_inverse_cascade(self, gate, layer_id):333            """Searches for an inverted CNOT cascade, a sequence of CNOT gates where the control qubit is the same for every CNOT334            while the target changes, and transforms it into a nearest-neighbor CNOT sequence.335             It is very similar to a CNOT cascade by using H gates to invert every CNOT.336             For every H gate it adds another H gate to maintain the circuit identity::337                ---o--o--o--o---           -H-------x-------H-338                   |  |  |  |                       |339                ---x--|--|--|---           -H-----x-o-x-----H-340                      |  |  |                     |   |341                ------x--|--|---    --->   -H---x-o---o-x---H-342                         |  |                   |       |343                ---------x--|---           -H-x-o-------o-x-H-344                            |                 |           |345                ------------x---           -H-o-----------o-H-346            Args:347                gate (DAGNode): first CNOT of a possible inverted CNOT cascade.348                layer_id (int): layer index of the CNOT.349            Returns:350                skip (list): list of gates to be skipped as part of the inverted CNOT cascade,351                may include one-qubit gates that appears before or after the cascade.352            """353            target = self._wires_to_id[gate.qargs[1]]354            control = self._wires_to_id[gate.qargs[0]]355            targets = [target]356            skip = [gate]357            # qubits already added to the CNOT sequence358            used = set()359            used.add(target)360            used.add(control)361            # qubits that cannot be used anymore362            off_limits = set()363            before = {}364            after = []365            # flag to identify the direction of the cascade366            descending = False367            if target > control:368                descending = True369            count = 0370            last_layer = layer_id371            double_break = False372            # loop through layers until a max limit is reached373            while count < min([2 * (self._num_qubits - 1), len(self._layers) - layer_id]):374                for gate in self._layers[layer_id + count].op_nodes():375                    logger.debug('Last layer: %d' % last_layer)376                    logger.debug('Layer: %d' % (layer_id + count))377                    logger.debug('Off limits: %s' % off_limits)378                    logger.debug('Gate Name: %s\tType: %s\tQargs: %s\tCargs: %s\tCond: %s' % (379                        gate.name, gate.type, gate.qargs, gate.cargs, gate.condition))380                    if gate in self._skip:381                        for qarg in gate.qargs:382                            if self._wires_to_id[qarg] == control:383                                double_break = True384                                break385                    elif gate not in skip:386                        if gate.name == 'cx' and gate not in self._skip:387                            g_control = self._wires_to_id[gate.qargs[0]]388                            g_target = self._wires_to_id[gate.qargs[1]]389                            logger.debug('Check CNOT Name: %s\tType: %s\tQargs: %s\tCargs: %s\tCond: %s' % (390                                gate.name, gate.type, [g_control, g_target], gate.cargs, gate.condition))391                            if g_target == control:392                                double_break = True393                                break394                            if g_control in off_limits or g_target in off_limits:395                                if last_layer > layer_id + count - 1:396                                    last_layer = layer_id + count - 1397                                off_limits.add(g_control)398                                off_limits.add(g_target)399                                if g_control not in used:400                                    used.add(g_control)401                                if g_target not in used:402                                    used.add(g_target)403                                logger.debug('CNOT off limits')404                                continue405                            logger.debug('Used: %s' % str(used))406                            logger.debug('Targets: %s' % str(targets))407                            logger.debug('Control-G_control: %d-%d' % (control, g_control))408                            logger.debug('Target-G_target: %d-%d' % (target, g_target))409                            # chek that the CNOT is part of the cascade410                            a = (g_control == control and g_target not in targets and g_target not in used)411                            b = (descending is True and g_target > control) or (descending is False and g_target < control)412                            logger.debug('A: %s B: %s Descending: %s\n' % (a, b, descending))413                            if a and b:414                                targets.append(g_target)415                                used.add(g_target)416                                skip.append(gate)417                            # check if the CNOT interrupts the cascade418                            elif g_control != control and g_target != control:419                                # remember to put the CNOT after the transformation420                                if g_control not in used and g_target not in used:421                                    if last_layer < layer_id + count:422                                        last_layer = layer_id + count423                                # updates used and off limits qubits when necessary424                                else:425                                    off_limits.add(g_control)426                                    off_limits.add(g_target)427                                    if last_layer > layer_id + count - 1:428                                        last_layer = layer_id + count - 1429                                    if g_control not in used:430                                        used.add(g_control)431                                    if g_target not in used:432                                        used.add(g_target)433                            else:434                                # break the loop if the CNOT interrupts the cascade435                                double_break = True436                                break437                        else:438                            # ignore gates acting on off limits qubits439                            double_continue = False440                            for qarg in gate.qargs:441                                if self._wires_to_id[qarg] in off_limits:442                                    double_continue = True443                                    continue444                            if double_continue is True:445                                continue446                            # for special multi-qubits gates, update used and off limits qubits properly,447                            # break the loop if necessary448                            if gate.name in ["barrier", "snapshot", "save", "load", "noise"]:449                                qargs = [self._wires_to_id[qarg] for qarg in gate.qargs]450                                if control in qargs:451                                    if last_layer > layer_id + count - 1:452                                        last_layer = layer_id + count - 1453                                    double_break = True454                                    break455                                u = []456                                not_u = []457                                for qarg in qargs:458                                    if qarg in used:459                                        off_limits.add(qarg)460                                        u.append(qarg)461                                    else:462                                        not_u.append(qarg)463                                if len(u) == len(qargs):464                                    # the transformation must be applied before this gate465                                    if last_layer > layer_id + count - 1:466                                        last_layer = layer_id + count - 1467                                elif len(u) == 0:468                                    # the transformation must be applied after this gate469                                    if last_layer < layer_id + count:470                                        last_layer = layer_id + count471                                else:472                                    # the transformation must be applied before this gate473                                    if last_layer > layer_id + count - 1:474                                        last_layer = layer_id + count - 1475                                    for qarg in not_u + u:476                                        used.add(qarg)477                                        off_limits.add(qarg)478                            else:479                                # check if one-qubits gates either interrupt the cascade, can be applied after or before480                                qarg = self._wires_to_id[gate.qargs[0]]481                                logger.debug(gate.op.__class__)482                                logger.debug('Gate Name: %s\tType: %s\tQarg: %s\tCarg: %s\tCond: %s' % (483                                    gate.name, gate.type, qarg, gate.cargs, gate.condition))484                                if qarg == control:485                                    logger.debug('After')486                                    after.append(gate)487                                    skip.append(gate)488                                    double_break = True489                                    break490                                if qarg not in used:491                                    logger.debug('Before')492                                    if qarg not in before:493                                        before[qarg] = []494                                    before[qarg].append(gate)495                                    skip.append(gate)496                                else:497                                    logger.debug('After')498                                    after.append(gate)499                                    skip.append(gate)500                count += 1501                if double_break is True:502                    break503            # if an inverse cascade was found504            if len(targets) > 1:505                logger.debug('Found Inverse Cascade from layer %d to %d\n' % (layer_id, last_layer))506                if descending is True:507                    targets = sorted(targets)508                else:509                    targets = sorted(targets, reverse=True)510                # apply all gates that were encountered before the cascade511                for u in before:512                    for gate in before[u]:513                        self._extra_layers[last_layer].append(514                            (gate.op.__class__(*gate.op.params), gate.qargs, gate.cargs, gate.condition))515                # apply the transformation516                self._extra_layers[last_layer].append((U2Gate(0, pi), [self._id_to_wires[control]], []))517                for t in targets:518                    self._extra_layers[last_layer].append((U2Gate(0, pi), [self._id_to_wires[t]], []))519                for i in range(len(targets) - 1, 0, -1):520                    self._extra_layers[last_layer].append((CXGate(),521                                                           [self._id_to_wires[targets[i]],522                                                            self._id_to_wires[targets[i - 1]]], []))523                self._extra_layers[last_layer].append(524                    (CXGate(), [self._id_to_wires[targets[0]], self._id_to_wires[control]], []))525                for i in range(len(targets) - 1):526                    self._extra_layers[last_layer].append((CXGate(),527                                                           [self._id_to_wires[targets[i + 1]],528                                                            self._id_to_wires[targets[i]]], []))529                self._extra_layers[last_layer].append((U2Gate(0, pi), [self._id_to_wires[control]], []))530                for t in targets:531                    self._extra_layers[last_layer].append((U2Gate(0, pi), [self._id_to_wires[t]], []))532                # apply all gates that were encountered after the cascade533                for gate in after:534                    self._extra_layers[last_layer].append(535                        (gate.op.__class__(*gate.op.params), gate.qargs, gate.cargs, gate.condition))536            else:537                skip = None...finetune.py
Source:finetune.py  
...32	gen_i, gen_j = args.gen_sample.get(args.image_size, (10, 5))33	images = []34	with torch.no_grad():35		for i in range(gen_i):36			images.append(G_running_target(fixed_noise[i].cuda(), step=step, alpha=alpha).cpu())37	sample_path = f'sample/{args.name}/{str(iteration).zfill(6)}.png'38	utils.save_image(torch.cat(images, dim=0), sample_path, nrow=gen_i, normalize=True, range=(-1, 1))39	# compute evaluation metrics40	sample_num = args.sample_num41	fake_images, fake_acts = get_fake_images_and_acts(inception, G_running_target, code_size, step, alpha, sample_num, batch_size)42	fid = compute_fid(real_acts, fake_acts)43	metrics = {'fid': fid}44	return metrics45def l2_reg(net_src, net_tgt):46	params_src = list(net_src.parameters())47	params_tgt = list(net_tgt.parameters())48	loss = 049	for p_src, p_tgt in zip(params_src, params_tgt):50		loss += F.mse_loss(p_tgt, p_src)...generate.py
Source:generate.py  
...31                z = z2*alpha + (1-alpha)*z132                sample_s, _ = g_source([z], randomize_noise=False)33                w = [g_target.module.style(z)]34                w = [Proj_module.modulate(item) for item in w]35                sample_t, _= g_target(w, input_is_latent=True, randomize_noise=False)36                utils.save_image(37                    sample_s,38                    f'%s/sample%d.png' % (args.save_source, (t*n_steps) + i) ,39                    normalize=True,40                    range=(-1, 1),41                )42                utils.save_image(43                    sample_t,44                    f'%s/sample%d.png' % (args.save_target, (t*n_steps) + i),45                    normalize=True,46                    range=(-1, 1),47                )48def generate_imgs(args, g_source, g_target, Proj_module):49    with torch.no_grad():50        51        if args.load_noise:52            sample_z = torch.load(args.load_noise)53        else:54            sample_z = torch.randn(args.n_sample, args.latent).cuda()55        sample_s, _ = g_source([sample_z], input_is_latent=False, randomize_noise=False)56        w = [g_target.module.style(sample_z)]57        w = [Proj_module.modulate(item) for item in w]58        sample_t, _= g_target(w, input_is_latent=True, randomize_noise=False)59        utils.save_image(60            sample_s,61            f'%s/sample_s.png' % args.save_source,62            nrow=5,63            normalize=True,64            range=(-1, 1),65        )66        utils.save_image(67            sample_t,68            f'%s/sample_t.png' % args.save_target,69            nrow=5,70            normalize=True,71            range=(-1, 1),72        )73def generate_img_pairs(args, g_source, g_target, Proj_module):74    75    with torch.no_grad():76        sample_z = torch.randn(args.SCS_samples, args.latent).cuda()77        for i in range(10):78            print(i)79            w = [g_target.module.style(sample_z[i* int(args.SCS_samples / 10): (i+1)*int(args.SCS_samples / 10)])]80            w = [Proj_module.modulate(item) for item in w]81            sample_t, _= g_target(w, input_is_latent=True, randomize_noise=False)82            sample_s, _ = g_source([sample_z[i* int(args.SCS_samples / 10): (i+1)*int(args.SCS_samples / 10)]], input_is_latent=False, randomize_noise=False)83            84            for (num, (img_s, img_t)) in enumerate(zip(sample_s, sample_t)):85                utils.save_image(86                    img_s,87                    f'%s/img%d.png' % (args.save_source, (i* int(args.SCS_samples / 10)) + num) ,88                    normalize=True,89                    range=(-1, 1),90                )91                utils.save_image(92                    img_t,93                    f'%s/img%d.png' % (args.save_target, (i * int(args.SCS_samples / 10)) + num) ,94                    normalize=True,95                    range=(-1, 1),96                )97def generate_imgs_4IS(args, g_target, Proj_module):98    99    with torch.no_grad():100        101        sample_z = torch.randn(args.IS_sample, args.latent).cuda()102        step = int(args.IS_sample / 50)103        batch = 50104        for i in range(int(args.IS_sample / 50)):105            print(i)106            w = [g_target.module.style(sample_z[i*batch: (i+1)*batch])]107            w = [Proj_module.modulate(item) for item in w]108            sample_t, _= g_target(w, input_is_latent=True, randomize_noise=False)109            for (num, img) in enumerate(sample_t):110                utils.save_image(111                    img,112                    f'%s/img%d.png' % (args.save_target, (i * batch) + num) ,113                    normalize=True,114                    range=(-1, 1),115                )116if __name__ == '__main__':117    device = 'cuda'118    parser = argparse.ArgumentParser()119    parser.add_argument('--size', type=int, default=256)120    parser.add_argument('--SCS_samples', type=int, default=500, help='number of image pairs to eval SCS')121    parser.add_argument('--n_sample', type=int, default=25, help='number of fake images to be sampled')122    parser.add_argument('--IS_sample', type=int, default=10000, help='number of fake images to be sampled for IS')...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
