Best Python code snippet using hypothesis
naive_gen_mix.py
Source:naive_gen_mix.py  
...48    ''' Write the add function for a set of coefficients.  This is a custom add49    function used for a single multiply in a single fast algorithm.50    coeffs is the set of coefficients used for the add51    '''52    nonzero_coeffs = [coeff for coeff in coeffs if is_nonzero(coeff)]53    nnz = len( nonzero_coeffs )54    add = 'void %s_Add%d( int m, int n, ' % (mat_name, index)55    add += ', '.join(['double* %s%d' % ( mat_name, i ) for i in range(nnz)])56    add += ', int ld%s, double* R, int ldR, int bl_ic_nt ' % (mat_name)57    # Handle the C := alpha A * B + beta C58    is_output = (mat_name == 'M')59    #is_output = False 60    #if is_output:61    #    add += ', double beta'62    add += ') {'63    write_line(myfile, 0, add)64    # Handle the C := alpha A * B + beta C65    if is_output:66        #write_line( myfile, 1, 'int i, j;' )67        #write_line( myfile, 1, 'for ( j = 0; j < n; ++j ) {')68        #write_line( myfile, 2, 'for ( i = 0; i < m; ++i ) {')69        #add = data_access('R') + ' ='70        #for j, coeff in enumerate(nonzero_coeffs):71        #    ind = j72        #    add += arith_expression(coeff, mat_name, ind )73        #add += ' + %s;' % (data_access('R'))74        #write_line(myfile, 3, add)75        #write_line(myfile, 2, '}')76        #write_line(myfile, 1, '}')77        write_line( myfile, 1, 'int i, j;' )78        #write_line( myfile, 1, '#pragma omp parallel for schedule( dynamic )' )79        write_line( myfile, 0, '#ifdef _PARALLEL_')80        write_line( myfile, 1, '#pragma omp parallel for num_threads( bl_ic_nt )' )81        write_line( myfile, 0, '#endif')82        write_line( myfile, 1, 'for ( j = 0; j < n; ++j ) {')83        write_line( myfile, 2, 'for ( i = 0; i < m; ++i ) {')84        for j, coeff in enumerate(nonzero_coeffs):85            ind = j86            add = data_access( mat_name, str(ind) )  + ' += '87            add += arith_expression(coeff, 'R', '' )88            add += ';'89            write_line(myfile, 3, add)90        write_line(myfile, 2, '}')91        write_line(myfile, 1, '}')92        #write_line( myfile, 1, 'int i, j;' )93        #for j, coeff in enumerate(nonzero_coeffs):94        #    write_line( myfile, 1, 'for ( j = 0; j < n; ++j ) {')95        #    write_line( myfile, 2, 'for ( i = 0; i < m; ++i ) {')96        #    ind = j97        #    add = data_access( mat_name, str(ind) )  + ' += '98        #    add += arith_expression(coeff, 'R', '' )99        #    add += ';'100        #    write_line(myfile, 3, add)101        #    write_line(myfile, 2, '}')102        #    write_line(myfile, 1, '}')103    else:104        write_line( myfile, 1, 'int i, j;' )105        write_line( myfile, 0, '#ifdef _PARALLEL_')106        write_line( myfile, 1, '#pragma omp parallel for num_threads( bl_ic_nt )' )107        write_line( myfile, 0, '#endif')108        write_line( myfile, 1, 'for ( j = 0; j < n; ++j ) {' )109        write_line( myfile, 2, 'for ( i = 0; i < m; ++i ) {' )110        add = data_access('R') + ' ='111        for j, coeff in enumerate(nonzero_coeffs):112            ind = j113            add += arith_expression(coeff, mat_name, ind )114    115        add += ';'116        write_line(myfile, 3, add)117        write_line(myfile, 2, '}')118        write_line(myfile, 1, '}')119    write_line(myfile, 0, '}')  # end of function120def arith_expression(coeff, mat_name, ind):121    ''' Return the arithmetic expression needed for multiplying coeff by value122    in a string of expressions.123    '''124    value = data_access( mat_name, str( ind ) )125    if is_one(coeff):126         expr = ' %s' % value127    elif is_negone(coeff):128        expr = ' - %s' % value129    else:130        #print "coeff is not +-1!"131        expr = ' (double)(%s) * %s' % (coeff, value)132    if ind != 0 and not is_negone(coeff):133        return ' +' + expr134    return expr135def write_output_add( myfile, index, coeffs, dims, rank ):136    add = 'M_Add%d( ' % (index)137    add += 'ms, ns, '138    for i, coeff in enumerate(coeffs):139        if is_nonzero(coeff):140            suffix = i141            #if suffix > rank:142            #    suffix = '_X%d' % (suffix - rank)143            add += 'M%s, ' % suffix144    add += 'ldM, '145    #output_mat = getBlockName( 2, index, dims, level )146    output_mat = getBlockName( 2, index, dims )147    add += '%s, ldc, bl_ic_nt );' % output_mat148    write_line(myfile, 1, add)149def create_output( myfile, coeffs, dims  ):150    num_multiplies = len(coeffs[0][0])151    for i, row in enumerate(coeffs[2]):152        write_output_add(myfile, i, row, dims,153                         num_multiplies  )154def create_straprim_caller( myfile, coeffs, dims_mix, num_multiplies ):155    ''' Generate all of the function callers.156    myfile is the file to which we are writing157    coeffs is the set of all coefficients158    dims is a 3-tuple (m, k, n) of the dimensions of the problem159    '''160    for i in xrange(len(coeffs[0][0])):161        a_coeffs = [c[i] for c in coeffs[0]]162        b_coeffs = [c[i] for c in coeffs[1]]163        c_coeffs = [c[i] for c in coeffs[2]]164        write_multiply_caller(myfile, i, a_coeffs, b_coeffs, c_coeffs, dims_mix, num_multiplies )165def create_straprim_naive_functions( myfile, coeffs, dims_mix, num_multiplies ):166    ''' Generate all of the Naive fmm primitive functions.167    myfile is the file to which we are writing168    coeffs is the set of all coefficients169    dims is a 3-tuple (m, k, n) of the dimensions of the problem170    '''171    for i in xrange(len(coeffs[0][0])):172        a_coeffs = [c[i] for c in coeffs[0]]173        b_coeffs = [c[i] for c in coeffs[1]]174        c_coeffs = [c[i] for c in coeffs[2]]175        write_straprim_naive_function( myfile, i, a_coeffs, b_coeffs, c_coeffs, dims_mix, num_multiplies )176def is_nonone(x):177    return not is_one(x)178def num_nonone(arr):179    ''' Returns number of non-one entries in the array arr. '''180    return len(filter(is_nonone, arr))181def need_tmp_mat(coeffs):182    return num_nonone(coeffs) > 1183def instantiate_tmp(myfile, tmp_name, mult_index):184    inst = 'double* %s%d = bl_malloc_aligned( ld%s, n%s, sizeof(double) );' % (tmp_name, mult_index, tmp_name, tmp_name)185    write_line(myfile, 1, inst)186def write_multiply_caller(myfile, index, a_coeffs, b_coeffs, c_coeffs, dims_mix, num_multiplies ):187    comment = '// M%d = (' % (index)188    comment += ' + '.join([str(c) + ' * %s' % getBlockName( 0, i, dims_mix ) \189                               for i, c in enumerate(a_coeffs) if is_nonzero(c)])190    comment += ') * ('191    comment += ' + '.join([str(c) + ' * %s' % getBlockName( 1, i, dims_mix  ) \192                               for i, c in enumerate(b_coeffs) if is_nonzero(c)])193    comment += '); '194    comment += '; '.join([' %s += %s * M%d' % ( getBlockName( 2, i, dims_mix ), c, index ) for i, c in enumerate(c_coeffs) if is_nonzero(c)])195    comment += ';'196    write_line(myfile, 1, comment)197    add = 'bl_dgemm_straprim_naive%d( ms, ns, ks, ' % index198    add += ', '.join(['%s' % getBlockName( 0, i, dims_mix ) \199                      for i, c in enumerate(a_coeffs) if is_nonzero(c)])200    add += ', lda, '201    add += ', '.join(['%s' % getBlockName( 1, i, dims_mix ) \202                      for i, c in enumerate(b_coeffs) if is_nonzero(c)])203    add += ', ldb, '204    add += ', '.join(['%s' % getBlockName( 2, i, dims_mix ) \205                      for i, c in enumerate(c_coeffs) if is_nonzero(c)])206    add += ', ldc, bl_ic_nt );'207    write_line( myfile, 1, add )208def write_straprim_naive_function(myfile, index, a_coeffs, b_coeffs, c_coeffs, dims_mix, num_multiplies ):209    comment = '// M%d = (' % (index)210    comment += ' + '.join([str(c) + ' * %s' % getBlockName( 0, i, dims_mix ) \211                               for i, c in enumerate(a_coeffs) if is_nonzero(c)])212    comment += ') * ('213    comment += ' + '.join([str(c) + ' * %s' % getBlockName( 1, i, dims_mix ) \214                               for i, c in enumerate(b_coeffs) if is_nonzero(c)])215    comment += '); '216    comment += '; '.join([' %s += %s * M%d' % ( getBlockName( 2, i, dims_mix ), c, index ) for i, c in enumerate(c_coeffs) if is_nonzero(c)])217    comment += ';'218    write_line(myfile, 0, comment)219    add = 'void bl_dgemm_straprim_naive%d( int ms, int ns, int ks, ' % index220    add += ', '.join(['double* %s' % getBlockName( 0, i, dims_mix ) \221                      for i, c in enumerate(a_coeffs) if is_nonzero(c)])222    add += ', int lda, '223    add += ', '.join(['double* %s' % getBlockName( 1, i, dims_mix ) \224                      for i, c in enumerate(b_coeffs) if is_nonzero(c)])225    add += ', int ldb, '226    add += ', '.join(['double* %s' % getBlockName( 2, i, dims_mix ) \227                      for i, c in enumerate(c_coeffs) if is_nonzero(c)])228    add += ', int ldc, int bl_ic_nt ) {'229    #add += ', '.join(['double* %s%d' % ( 'a', i ) for i in range( num_nonzero(a_coeffs) )])230    #add += ', lda, '231    #add += ', '.join(['double* %s%d' % ( 'b', i ) for i in range( num_nonzero(b_coeffs) )])232    #add += ', ldb, '233    #add += ', '.join(['double* %s%d' % ( 'c', i ) for i in range( num_nonzero(c_coeffs) )])234    #add += ', ldc ) {'235    write_line( myfile, 0, add )236    write_line( myfile, 1, 'int ldS = ms, nS = ks, ldT = ks, nT = ns, ldM = ms, nM = ns;' )237    def para_ld( coeff_index  ):238        if( coeff_index == 0 ):239            mm = 'ms'240            nn = 'ks'241        elif( coeff_index == 1 ):242            mm = 'ks'243            nn = 'ns' 244        elif( coeff_index == 2 ):245            mm = 'ms' 246            nn = 'ns'247        else:248            print "Wrong coeff_index\n"249        return str(mm) + ', ' + str(nn) + ', '250    def addition_str(coeffs, coeff_index, mat_name, tmp_name, dims_mix ):251        tmp_mat = '%s%d' % (tmp_name, index)252        add = '%s_Add%d( %s' % ( tmp_name, index, para_ld( coeff_index ) )253        for i, coeff in enumerate(coeffs):254            if is_nonzero(coeff):255                add += getBlockName( coeff_index, i, dims_mix ) + ', '256        add += 'ld%s, ' % ( mat_name )257        add += tmp_mat + ', ld%s, bl_ic_nt );' % tmp_name258        return add259    # Write the adds to temps if necessary260    if need_tmp_mat(a_coeffs):261        instantiate_tmp(myfile, 'S', index)262        write_line(myfile, 1, addition_str(a_coeffs, 0, 'a', 'S', dims_mix ))263    if need_tmp_mat(b_coeffs):264        instantiate_tmp(myfile, 'T', index)265        write_line(myfile, 1, addition_str(b_coeffs, 1, 'b', 'T', dims_mix ))266    inst = 'double* M%d = bl_malloc_aligned( ldM, nM, sizeof(double) );' % ( index )267    write_line( myfile, 1, inst )268    write_line( myfile, 1, 'memset( M%d, 0, sizeof(double) * ldM * nM );' % ( index ) )269    res_mat = 'M%d' % (index)270    ## Handle the case where there is one non-zero coefficient and it is271    ## not equal to one.  We need to propagate the multiplier information.272    #a_nonzero_coeffs = filter(is_nonzero, a_coeffs)273    #b_nonzero_coeffs = filter(is_nonzero, b_coeffs)274    #if len(a_nonzero_coeffs) == 1 and a_nonzero_coeffs[0] != 1:275    #    write_line(myfile, 1, '%s.UpdateMultiplier(Scalar(%s));' % (res_mat,276    #                                                                a_nonzero_coeffs[0]))277    #if len(b_nonzero_coeffs) == 1 and b_nonzero_coeffs[0] != 1:278    #    write_line(myfile, 1, '%s.UpdateMultiplier(Scalar(%s));' % (res_mat,279    #                                                                b_nonzero_coeffs[0]))280    def subblock_name( coeffs, coeff_index, mat_name, tmp_name, dims_mix ):281        if need_tmp_mat(coeffs):282            return '%s%d' % (tmp_name, index)283        else:284            loc = [i for i, c in enumerate(coeffs) if is_nonzero(c)]285            return getBlockName( coeff_index, loc[0], dims_mix )286    def subblock_ld( coeffs, mat_name, tmp_name ):287        if need_tmp_mat(coeffs):288            return '%s' % (tmp_name)289        else:290            return mat_name291    # Finally, write the actual call to matrix multiply.292    write_line(myfile, 1,293               'bl_dgemm( ms, ns, ks, %s, ld%s, %s, ld%s, %s, ldM );' % (294            subblock_name(a_coeffs, 0, 'a', 'S', dims_mix ),295            subblock_ld(a_coeffs, 'a', 'S' ),296            subblock_name(b_coeffs, 1, 'b', 'T', dims_mix ),297            subblock_ld(b_coeffs, 'b', 'T' ),298            res_mat...torch_type_ops_test.py
Source:torch_type_ops_test.py  
...168    @api_link(169        target="torch.is_nonzero",170        ref="https://pytorch.org/docs/stable/generated/torch.is_nonzero.html",171    )172    def test_is_nonzero(self) -> None:173        """torch.is_nonzero(input: Tensor)174        Also: `<tensor>.is_nonzero()`175        Returns true if the input is a single element tensor176        which is not equal to zero after type conversions.177        .. _Online Doc:178            https://pytorch.org/docs/stable/generated/torch.is_nonzero.html179        """180        # True:181        # =====182        for s in [1, [1], [1.0], [[1]], [[1.0]]]:183            t = torch.tensor(s)184            eggs.assert_match(t.numel(), 1)185            eggs.assert_true(186                torch.is_nonzero(t),187            )188            eggs.assert_true(189                t.is_nonzero(),190            )191        # False:192        # =====193        for s in [0, [0], [0.0], [[0]], [[0.0]]]:194            t = torch.tensor(s)195            eggs.assert_match(t.numel(), 1)196            eggs.assert_false(197                torch.is_nonzero(t),198            )199            eggs.assert_false(200                t.is_nonzero(),201            )202        # Errors:203        # =======204        # Throws RuntimeError if t.numel() != 1205        for s in [[], [1, 1]]:206            t = torch.tensor(s)207            hamcrest.assert_that(t.numel(), hamcrest.is_not(1))208            eggs.assert_raises(209                lambda: torch.is_nonzero(t),210                RuntimeError,211            )212            eggs.assert_raises(213                lambda: t.is_nonzero(),214                RuntimeError,215            )216        # Throws TypeError if input isn't a Tensor217        eggs.assert_raises(218            lambda: torch.is_nonzero("abc"),  # type: ignore219            TypeError,...basicFunc.py
Source:basicFunc.py  
1import torch2### is_nonzero æ¯ä¸æ¯éé¶,åªè½æ£æµå个åé3torch.is_nonzero(torch.tensor([0.]))4torch.is_nonzero(torch.tensor([1.5]))5# torch.is_nonzero(torch.tensor([1, 3, 5])) # wrong6### count_nonzero 计æ°éé¶é¡¹7x = torch.zeros(3,3)8x[torch.randn(3,3) > 0.5] = 19print(x)10print(torch.count_nonzero(x))11### åæ¢ç±»å12'''131.CPU tensor转GPU tensorï¼14cpu_imgs.cuda()152. GPU tensor 转CPU tensorï¼16gpu_imgs.cpu()173. numpy转为CPU tensorï¼18torch.from_numpy(imgs)194.CPU tensor转为numpyæ°æ®ï¼...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!!
