How to use test_passes method in autotest

Best Python code snippet using autotest_python

bom.py

Source:bom.py Github

copy

Full Screen

1#!/usr/bin/env python2# coding=utf-83"""4A highly optimized class for bill of materials consolidation and costing5"""6from __future__ import absolute_import7from pandas import DataFrame8from six import iteritems9import os10import sys11DOCKER = os.environ.get('DOCKER') in ('transform', 'ipython')12if DOCKER:13 sys.path.append('/var/vol/code')14__author__ = "Paul Morel"15__copyright__ = "© Copyright 2015, Tartan Solutions, Inc"16__credits__ = ["Paul Morel"]17__license__ = "Proprietary"18__maintainer__ = "Paul Morel"19__email__ = "paul.morel@tartansolutions.com"20class Node(object):21 """A BOM hierarchy node object"""22 def __init__(self, parent_obj, child_id, makeup_volume=1):23 """Initializes node object24 :param parent_obj: parent object25 :type parent_obj: object26 :param child_id: child node key27 :type child_id: str or unicode28 :param consolidation: consolidation type +, -, or ~29 :type consolidation: str or unicode30 :returns: None31 :rtype: None32 """33 self.id = child_id34 self.parents = []35 self.children = {}36 self.cost = None37 self.override_cost = None38 # Set the reference to an assembly39 if parent_obj is not None:40 parent_obj.add_child(self, makeup_volume)41 # Create a reference so each child know who uses it42 if parent_obj not in self.parents:43 self.parents.append(parent_obj)44 def __repr__(self):45 return "<(Node ID: {} ({})>".format(self.id, self.get_cost())46 def get_cost(self):47 if self.cost is None:48 # Need to calculate the cost49 self.calculate_cost()50 return self.cost51 def set_cost(self, value):52 self.cost = value53 def set_override_cost(self, value):54 self.override_cost = value55 def add_child(self, child_obj, makeup_volume):56 """Add a child to the node57 :param child_obj: node object to add58 :type child_obj: object59 :param h: hierarchy - main or name of alt hierarchy60 :type h: str or unicode61 :returns: None62 :rtype: None63 """64 # Add the child to this parent's list of children65 # Also handles a makeup volume change66 self.children[child_obj] = makeup_volume67 def remove_child(self, child_id):68 """Removes child from node69 :param child_id: child node key to remove70 :type child_id: str or unicode71 :returns: None72 :rtype: None73 """74 current_children = self.get_children()75 temp_children = {}76 for c in current_children:77 if c.id != child_id:78 temp_children[c] = current_children[c]79 # The new list should be missing the child.80 self.children = temp_children81 def get_parents(self):82 """Returns parent object of node83 :returns: Parent object84 :rtype: object85 """86 return self.parents87 def get_siblings(self, parent_id):88 """Finds siblings of the node89 :returns: list of siblings node objects including current node90 :rtype: list91 """92 for p in self.parents:93 if p.id == parent_id:94 return p.get_children()95 def get_children(self):96 """Returns list of children node objects97 :returns: list of child node objects98 :rtype: list99 """100 return self.children101 def is_child_of(self, parent_id):102 """Checks if the node is a child of the specified parent103 :param parent_id: parent node key104 :type parent_id: str or unicode105 :returns: True if node descends from the parent106 :rtype: bool107 """108 for p in self.parents:109 if p.id == parent_id:110 return True111 return False112 def is_parent_of(self, child_id):113 """Checks if the node is a parent of the specified child114 :param child_id: child node key115 :type child_id: str or unicode116 :returns: True if child descends from the node117 :rtype: bool118 """119 for c in self.get_children():120 if c.id == child_id:121 return True122 return False123 def calculate_cost(self):124 """Calculates the roll-up cost of this node based on125 the costs of sub-components126 :returns: None127 :rtype: None128 """129 if self.override_cost is None:130 # Ask all children for their costs and multiply by makeup volume131 # This will invoke a recursive request for costs down to the132 # lowest level component133 cost = 0134 for c in self.children:135 makeup_volume = self.children[c]136 if makeup_volume != 0:137 child_cost = c.get_cost()138 makeup_cost = child_cost * self.children[c]139 cost += makeup_cost140 self.cost = cost141 else:142 # An Override cost has been supplied143 # DO NOT calculate the cost, just use the override144 self.cost = self.override_cost145 def reset_cost(self):146 self.cost = None147class BOM(object):148 """BOM Hierarchy Class for fast BOM hierarchy operations"""149 def __init__(self, load_path=None):150 """Class init function sets up basic structure151 :param load_path: optional path to saved hierarchy load file to load initially152 :type load_path: str or unicode153 :returns: None154 :rtype: None155 """156 self.h_direct = {}157 self.h_children = {}158 self.clear()159 if load_path is not None:160 self.load(load_path)161 def add_node(self, parent_id, child_id, makeup_volume=1):162 """Adds a node to the main hierarchy163 :param parent_id: parent node key164 :type parent_id: str or unicode165 :param child_id: child node key166 :type child_id: str or unicode167 :param consolidation: consolidation type +, -, or ~168 :type consolidation: str or unicode169 :returns: None170 :rtype: None171 """172 try:173 parent_obj = self.get_node(parent_id)174 except:175 # Parent does not exist yet. Handle out of sequence data gracefully.176 root_parent = self.get_node('root')177 parent_obj = Node(root_parent, parent_id)178 self.h_direct[parent_id] = parent_obj179 if child_id in self.h_direct:180 # This already exists.181 node = self.h_direct[child_id]182 parent_obj.add_child(node, makeup_volume)183 else:184 # Doesn't exist. Simple add.185 node = Node(parent_obj, child_id, makeup_volume)186 self.h_direct[child_id] = node187 def delete_node(self, node_id):188 """Deletes the node and removes all aliases and properties189 :param node_id: node key190 :type node_id: str or unicode191 :returns: None192 :rtype: None193 """194 # Delete the node and index reference195 try:196 parents = self.get_parents(node_id)197 except:198 # Not present. No need to do anything199 pass200 else:201 # Remove from main hierarchy202 del self.h_direct[node_id]203 for p in parents:204 p.remove_child(node_id)205 def get_node(self, node_id):206 """Gets the node object207 :param node_id: node key208 :type node_id: str or unicode209 :returns: Node object210 :rtype: object211 """212 try:213 return self.h_direct[node_id]214 except:215 raise Exception('No node found with the name %s' % node_id)216 def reset_costs(self):217 """Resets all costs to uncalculated value218 :returns: None219 :rtype: None220 """221 for node_id in self.h_direct:222 self.h_direct[node_id].reset_cost()223 def set_cost(self, node_id, value):224 self.h_direct[node_id].set_cost(value)225 def set_override_cost(self, node_id, value):226 self.h_direct[node_id].set_override_cost(value)227 def get_all_costs(self):228 """Gets the cost of all nodes229 :returns: node cost230 :rtype: pandas.DataFrame231 """232 final = []233 for node_id in self.h_direct:234 temp = (node_id, self.h_direct[node_id].get_cost())235 final.append(temp)236 headers = ['node', 'cost']237 df = DataFrame(final, columns=headers)238 return df239 def get_parents(self, node_id):240 """Finds parent of node241 :param node_id: node key242 :type node_id: str or unicode243 :returns: node object of parent244 :rtype: object245 """246 return self.get_node(node_id).get_parents()247 def get_parent_ids(self, node_id):248 """Finds parent of node249 :param node_id: node key250 :type node_id: str or unicode251 :returns: node key of parent252 :rtype: str or unicode253 """254 try:255 parents = self.get_parents(node_id)256 return [p.id for p in parents]257 except:258 return None259 def get_siblings(self, node_id, parent_id):260 """Finds sibling nodes of specified node261 :param node_id: node key262 :type node_id: str or unicode263 :returns: node objects of all siblings including the current node264 :rtype: list265 """266 return self.get_node(node_id).get_siblings(parent_id)267 def get_sibling_ids(self, node_id, parent_id):268 """Finds sibling nodes of specified node269 :param node_id: node key270 :type node_id: str or unicode271 :returns: node keys of all siblings including the current node272 :rtype: list273 """274 objs = self.get_siblings(node_id, parent_id)275 return [o.id for o in objs]276 def get_children(self, node_id):277 """Finds children of node278 :param node_id: node key279 :type node_id: str or unicode280 :returns: list of children node objects281 :rtype: list282 """283 return self.get_node(node_id).get_children()284 def get_children_ids(self, node_id):285 """Finds children of node286 :param node_id: node key287 :type node_id: str or unicode288 :returns: list of children node keys289 :rtype: list290 """291 objs = self.get_children(node_id)292 return [o.id for o in objs]293 def is_child_of(self, node_id, parent_id):294 """Check if node is a child of the parent node295 :param node_id: child node key296 :type node_id: str or unicode297 :param parent_id: parent node key298 :type parent_id: str or unicode299 :returns: True if the child descends from the parent300 :rtype: bool301 """302 return self.get_node(node_id).is_child_of(parent_id)303 def is_parent_of(self, node_id, child_id):304 """Checks if node is a parent of the child node305 :param node_id: parent node key306 :type node_id: str or unicode307 :param child_id: child node key308 :type child_id: str or unicode309 :returns: True if the child descends from parent310 :rtype: bool311 """312 return self.get_node(node_id).is_parent_of(child_id)313 def _get_main_list_format(self, node_id):314 """Generates the parent child list recursively for saving315 :param node_id: current node to process316 :type node_id: str or unicode317 :returns: List of lists with parent child information318 :rtype: list319 """320 final = []321 children = self.get_children(node_id)322 for c in children:323 temp = [str(node_id), str(c.id), children[c]]324 final.append(temp)325 sub_children = self._get_main_list_format(c.id)326 if len(sub_children) > 0:327 final += sub_children328 return final329 def save(self, path):330 """Saves the hierarchy, alias, and property info in one file331 :param path: File path to save out put332 :type path: str or unicode333 :returns: None334 :rtype: None335 """336 self.save_hierarchy(path, 'root')337 def load(self, path):338 """Loads hierarchy, alias, and propeperty339 :param path: File path to load340 :type path: str or unicode341 :returns: None342 :rtype: None343 """344 self.load_hierarchy(path)345 def get_bom(self, top_node='root'):346 """Created dataframe of BOM makeup structure347 :param top_node:348 :type top_node: str or unicode349 :returns: Parent Child Dataframe350 :rtype: pandas.DataFrame351 """352 headers = ['parent', 'child', 'makeup_volume']353 pc_list = self._get_main_list_format(top_node)354 df = DataFrame(pc_list, columns=headers)355 return df356 def load_dataframe(self, df):357 """Loads a well formed dataframe into the hierarchy object358 Columns expected:359 - parent360 - child361 - makeup_volume362 :param df: The dataframe containing at least parent and child columns363 :type df: dataframe364 :returns: None365 :rtype: None366 """367 if df is not None:368 column_info = []369 for column_name, data_type in iteritems(df.dtypes):370 column_info.append(column_name)371 # Check to make sure all required columns are present372 if 'parent' not in column_info:373 raise Exception('Missing parent column. Found the following columns: {0}'.format(str(column_info)))374 if 'child' not in column_info:375 raise Exception('Missing child column. Found the following columns: {0}'.format(str(column_info)))376 if 'makeup_volume' not in column_info:377 raise Exception(378 'Missing makeup_volume column. Found the following columns: {0}'.format(str(column_info)))379 # order the df columns (hierarchy, parent, child, consolidation_type)380 # this enables using itertuples instead of iterrows381 df = df[['parent', 'child', 'makeup_volume']]382 # Iterate over the data and build the hierachy using the add method383 for r in df.itertuples():384 # Tuple is formed as (index, hierarchy, parent, child, consolidation type)385 self.add_node(r[1], r[2], r[3])386 def clear(self):387 self.clear_hierarchy()388 def clear_hierarchy(self):389 """Clears the main and alternate hierarchies390 :returns: None391 :rtype: None392 """393 self.h_direct = {}394 self.h_children = {}395 node = Node(None, 'root')396 self.h_direct['root'] = node397 def _get_preprocessed_main_format(self, node_id, left=0, volume_multiplier=1, indent=0):398 """Generates a highly optimized reporting format for export of main hierarchy399 :param node_id: current node key400 :type node_id: str or unicode401 :param left: current left counter402 :type left: int403 :param consolidation_list: list of consolidation multipliers as json string404 :type consolidation_list: str405 :returns: list of parent child records406 :rtype: list407 """408 final = []409 # If this recursed event doesn't have any records return the same value for left and right410 right = left411 children = self.get_children(node_id)412 for c in children:413 makeup_volume = children[c]414 effective_volume = makeup_volume * volume_multiplier415 # Get the child records recursively416 sub_right, sub_children = self._get_preprocessed_main_format(c.id, left + 1, effective_volume, indent + 1)417 # Now figure out the right side number based on how many elements are below418 right = sub_right + 1419 if len(sub_children) > 0:420 is_leaf = False421 else:422 is_leaf = True423 temp = [str(node_id), str(c.id), makeup_volume, effective_volume, is_leaf, left, right, indent]424 final.append(temp)425 if is_leaf is False:426 final += sub_children427 return (right, final)428 def get_frame(self, table, top_node='root'):429 """Generates a highly optimized reporting format for export430 :param path: Absolute path to export location431 :type path: str or unicode432 :param top_node: node key to start export at433 :type top_node: str or unicode434 :returns: None435 :rtype: None436 """437 headers = ['parent', 'child', 'makeup_volume', 'effective_makeup_volume', 'leaf', 'left', 'right', 'indent']438 right, pc_list = self._get_preprocessed_main_format(top_node)439 df = DataFrame(pc_list, columns=headers)440 return df441 def get_pretty_frame(self, table, top_node='root'):442 indent = ' '443 template = '{0}{1} x {2} ({3})'444 right, pc_list = self._get_preprocessed_main_format(top_node)445 final = []446 for p in pc_list:447 temp = []448 parent = p[0]449 child = p[1]450 makeup_volume = p[2]451 effective_makeup_volume = p[3]452 #leaf = p[4]453 #left = p[5]454 #right = p[6]455 indent_mult = p[7]456 indent_txt = indent * indent_mult457 txt = template.format(indent_txt, makeup_volume, child, effective_makeup_volume)458 temp.append(txt)459 temp.append(parent)460 temp.append(child)461 temp.append(makeup_volume)462 temp.append(effective_makeup_volume)463 final.append(temp)464 headers = ['friendly', 'parent', 'child', 'makeup_volume', 'effective_makeup_volume']465 df = DataFrame(final, columns=headers)466 return df467 def get_node_count(self):468 """Provides number of main hierarchy nodes469 :returns: Node count470 :rtype: int471 """472 return len(self.h_direct)473 def save_hierarchy(self, path, top_node):474 raise NotImplementedError()475 def load_hierarchy(self, path):476 raise NotImplementedError()477#478# if __name__ == '__main__':479# import timeit480#481# leaf_node_id = 'f1'482# parent_node_id = 'b1'483# test_passes = 1000484# fake_sets_to_generate = 10485#486# # This is declared globally for testing purposes. No reason for it otherwise.487# h = BOM()488#489# fake_data = [490# ['a', 'b', 3],491# ['a', 'c', 2],492# ['a', 'd', 1],493# ['b', 'e', 10],494# ['b', 'f', 2],495# ['c', 'f', 2],496# ['c', 'g', 2],497# ['a', 'f', 1]498# ]499#500# leaves = ('d', 'e', 'f', 'g')501#502# print "Generating {0} fake assemblies".format(fake_sets_to_generate)503# result = []504# part_cost = {}505#506# for fsg in xrange(fake_sets_to_generate):507# for fd in fake_data:508# parent = '{}{}'.format(fd[0], fsg)509# child = '{}{}'.format(fd[1], fsg)510# muv = fd[2]511#512# if fd[1] in leaves:513# part_cost[child] = 0.1 * fsg * fd[2]514#515# result.append((parent, child, muv))516#517# print "Generation Complete. Loading BOM Object..."518#519# # Create starting nodes for the CO dimensions520# #h.add_node('root', 51, '~')521# #h.add_node('root', 52, '~')522# #h.add_node('root', 53, '~')523#524# record_count = 0525# for r in result:526# h.add_node(r[0], r[1], r[2])527# record_count += 1528#529# print "Loading the BOM Object Complete. {0} Records Loaded.".format(record_count)530#531# print "Loading Leaf level costs..."532#533# # Create starting nodes for the CO dimensions534# #h.add_node('root', 51, '~')535# #h.add_node('root', 52, '~')536# #h.add_node('root', 53, '~')537#538# record_count = 0539# for pc in part_cost:540# h.set_cost(pc, part_cost[pc])541# record_count += 1542#543# print "Loading leaf level part cost complete. {0} base costs set.".format(record_count)544#545# print546# print547# print "Beginning Tests..."548#549# print "Leaf Node Used for Tests is {0}".format(leaf_node_id)550# print "Parent Node Used for Tests is {0}".format(parent_node_id)551# print "{0} Test passes used for timing.".format(test_passes)552#553# print "STARTING NODE COUNT is {0}".format(h.get_node_count())554#555# print "-----------"556# s = "h.get_node(leaf_node_id)"557#558# print s559# t = timeit.Timer(s, "from __main__ import h, leaf_node_id")560# print "%.2f usec/pass" % (test_passes * t.timeit(number=test_passes) / test_passes)561#562# print "-----------"563# s = "h.get_parents(leaf_node_id)"564#565# print s566# t = timeit.Timer(s, "from __main__ import h, leaf_node_id")567# print "%.2f usec/pass" % (test_passes * t.timeit(number=test_passes) / test_passes)568#569# print "-----------"570# s = "h.get_parent_ids(leaf_node_id)"571#572# print s573# t = timeit.Timer(s, "from __main__ import h, leaf_node_id")574# print "%.2f usec/pass" % (test_passes * t.timeit(number=test_passes) / test_passes)575#576# print "-----------"577# s = "h.get_siblings(leaf_node_id, parent_node_id)"578#579# print s580# t = timeit.Timer(s, "from __main__ import h, leaf_node_id, parent_node_id")581# print "%.2f usec/pass" % (test_passes * t.timeit(number=test_passes) / test_passes)582#583# print "-----------"584# s = "h.get_sibling_ids(leaf_node_id, parent_node_id)"585#586# print s587# t = timeit.Timer(s, "from __main__ import h, leaf_node_id, parent_node_id")588# print "%.2f usec/pass" % (test_passes * t.timeit(number=test_passes) / test_passes)589#590# print "-----------"591# s = "h.is_child_of(leaf_node_id, parent_node_id)"592#593# print s594# t = timeit.Timer(s, "from __main__ import h, leaf_node_id, parent_node_id")595# print "%.2f usec/pass" % (test_passes * t.timeit(number=test_passes) / test_passes)596#597# print "-----------"598# s = "h.is_parent_of(parent_node_id, leaf_node_id)"599#600# print s601# t = timeit.Timer(s, "from __main__ import h, leaf_node_id, parent_node_id")602# print "%.2f usec/pass" % (test_passes * t.timeit(number=test_passes) / test_passes)603#604# print "-----------"605# s = "h.get_children(parent_node_id)"606#607# print s608# t = timeit.Timer(s, "from __main__ import h, parent_node_id")609# print "%.2f usec/pass" % (test_passes * t.timeit(number=test_passes) / test_passes)610#611# print "-----------"612# s = "h.get_children_ids(parent_node_id)"613#614# print s615# t = timeit.Timer(s, "from __main__ import h, parent_node_id")616# print "%.2f usec/pass" % (test_passes * t.timeit(number=test_passes) / test_passes)617#618# print "-----------"619# print "MAXIMUM STRESS TEST - Get all Costs"620# s = "h.get_all_costs()"621#622# print s623# t = timeit.Timer(s, "from __main__ import h")624# print "%.2f usec/pass" % (test_passes * t.timeit(number=test_passes) / test_passes)625#626# print "-----------"627# print "MAXIMUM STRESS TEST - Get the complete BOM"628# s = "h.get_bom('root')"629#630# print s631# t = timeit.Timer(s, "from __main__ import h")...

Full Screen

Full Screen

test_passes.py

Source:test_passes.py Github

copy

Full Screen

1# Copyright 2021 The BladeDISC Authors. All rights reserved.2# Licensed under the Apache License, Version 2.0 (the "License");3# you may not use this file except in compliance with the License.4# You may obtain a copy of the License at5# http://www.apache.org/licenses/LICENSE-2.06# Unless required by applicable law or agreed to in writing, software7# distributed under the License is distributed on an "AS IS" BASIS,8# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.9# See the License for the specific language governing permissions and10# limitations under the License.11import unittest12import torch13from torch.testing import FileCheck14from torch_blade import exporter15from torch_blade import pass_manager16from torch_blade import utils17from torch_blade.config import Config18from torch_blade.testing.common_utils import TestCase19class TestPasses(TestCase):20 def test_pass_freeze_rank(self):21 class Model(torch.nn.Module):22 def forward(self, inp):23 if inp.dim() == 0:24 return 025 elif inp.dim() == 1:26 return 127 elif inp.dim() == 2:28 return 229 elif inp.dim() == 3:30 return 331 else:32 return 433 dummy_input = torch.ones([64, 64])34 model = Model()35 graph = exporter.export(Model(), False, dummy_input).graph36 pass_manager._jit_pass_freeze_rank(graph)37 expect_gstr = """38 graph(%x.1 : Tensor):39 # CHECK-COUNT-EXACTLY-1: prim::Constant[value=2]40 %3 : int = prim::Constant[value=2]()41 return (%3)"""42 FileCheck().run(expect_gstr, graph)43 def test_reorder_raise_exception(self):44 @torch.jit.script45 def has_raise_exception(x):46 x_sum = x.sum()47 if x_sum < 0:48 raise Exception("sum < 0")49 x_numel = x.numel()50 if x_sum < 0:51 raise Exception("x_numel < 0")52 x_mean = x_sum / x.numel()53 if x_mean < 0:54 raise Exception("x_mean < 0")55 return x_mean56 graph = has_raise_exception.graph57 pass_manager._jit_pass_reorder_raise_exception(graph)58 last_3nodes = graph.node_list()[-3:]59 self.assertEqual(len(last_3nodes), 3)60 for node in last_3nodes:61 blks = [blk for blk in node.blocks()]62 self.assertGreater(len(blks), 0)63 blk0_nodes = blks[0].node_list()64 self.assertGreater(len(blk0_nodes), 0)65 n0_kind = blk0_nodes[0].kind()66 self.assertEqual(n0_kind, "prim::RaiseException")67 @unittest.skipIf(utils.torch_version_number() >= utils.parse_version("1.8.1"), 'failed')68 def test_pass_licm(self):69 class Model(torch.nn.Module):70 def __init__(self, hidden_size):71 super().__init__()72 self.hidden_size = hidden_size73 self.hidden = torch.nn.Linear(self.hidden_size, self.hidden_size)74 def forward(self, x):75 y = x76 for i in range(x.size(0)):77 y = self.hidden(x)78 return y79 hidden_size = 25680 model = Model(hidden_size)81 x = torch.randn(1, 10, hidden_size)82 module = exporter.export(model, False, x)83 pass_manager._jit_pass_freeze_rank(module.graph)84 expected_y = module.forward(x)85 pass_manager._jit_pass_licm(module.graph)86 y = module.forward(x)87 self.assertEqual(y, expected_y)88 # Check matmul op is before Loop after licm pass89 expect_gstr = """90graph(%self : __torch__.___torch_mangle_0.Model,91 %x.1 : Float(1:2560, 10:256, 256:1)):92 %8 : bool = prim::Constant[value=1]() # tests/test_passes.py:107:1693 %4 : int = prim::Constant[value=0]() # tests/test_passes.py:107:3894 %5 : int = aten::size(%x.1, %4) # tests/test_passes.py:107:3195 %62 : __torch__.torch.nn.modules.linear.Linear = prim::GetAttr[name="hidden"](%self)96 %63 : int = prim::Constant[value=1]()97 %64 : Float(256:256, 256:1) = prim::GetAttr[name="weight"](%62)98 %65 : Float(256:1) = prim::GetAttr[name="bias"](%62)99 %66 : Float(256:1, 256:256) = aten::t(%64)100 # CHECK: aten::matmul101 %output.1 : Float(1:2560, 10:256, 256:1) = aten::matmul(%x.1, %66)102 %output.3 : Float(1:2560, 10:256, 256:1) = aten::add(%output.1, %65, %63)103 # CHECK: prim::Loop104 %y : Float(1:2560, 10:256, 256:1) = prim::Loop(%5, %8, %x.1) # tests/test_passes.py:107:16105 block0(%i : int, %y.4 : Tensor):106 -> (%8, %output.3)107 return (%y)"""108 FileCheck().run(expect_gstr, str(module._c.forward.graph))109 def test_pass_licm_fail(self):110 class Model(torch.nn.Module):111 def forward(self, x):112 y = [0]113 for i in range(x.size(0)):114 z = y[0]115 y.append(z)116 return y117 model = Model()118 module = torch.jit.script(model).eval()119 x = torch.randn(10)120 expected_y = module.forward(x)121 pass_manager._jit_pass_licm(module.graph)122 y = module.forward(x)123 self.assertEqual(y, expected_y)124 # Check getitem op is will not be moved before Loop by licm pass125 expect_gstr = """126graph(%self : __torch__.___torch_mangle_4.Model,127 %x.1 : Tensor):128 %8 : bool = prim::Constant[value=1]() # tests/test_passes.py:101:16129 %2 : int = prim::Constant[value=0]() # tests/test_passes.py:100:21130 %y.1 : int[] = prim::ListConstruct(%2)131 %5 : int = aten::size(%x.1, %2) # tests/test_passes.py:101:31132 # CHECK: prim::Loop133 = prim::Loop(%5, %8) # tests/test_passes.py:101:16134 block0(%i : int):135 # CHECK: aten::__getitem__136 %z.1 : int = aten::__getitem__(%y.1, %2) # tests/test_passes.py:102:24137 %14 : int[] = aten::append(%y.1, %z.1) # tests/test_passes.py:103:20138 -> (%8)139 return (%y.1)"""140 FileCheck().run(expect_gstr, str(module._c.forward.graph))141 def test_hack_cpu_device(self):142 cfg = Config.get_current_context_or_new()143 cfg.enable_force_to_cuda = True144 @torch.jit.script145 def move_to_cpu(x):146 return x.to('cpu')147 with cfg:148 pass_manager._jit_pass_hack_cpu_device(move_to_cpu.graph)149 expect_gstr = """150graph(%x.1 : Tensor):151 %6 : bool = prim::Constant[value=0]()152 %5 : None = prim::Constant()153 # CHECK: prim::Constant[value="cuda"]()154 %18 : Device = prim::Constant[value="cuda"]()155 %8 : Tensor = aten::to(%x.1, %18, %5, %6, %6)156 return (%8)"""157 FileCheck().run(expect_gstr, move_to_cpu.graph)158 @torch.jit.script159 def zeros_cpu():160 return torch.zeros([1, 2], device=torch.device('cpu'))161 with cfg:162 pass_manager._jit_pass_hack_cpu_device(zeros_cpu.graph)163 expect_gstr = """164graph():165 %5 : None = prim::Constant()166 %0 : int = prim::Constant[value=1]()167 %1 : int = prim::Constant[value=2]()168 %2 : int[] = prim::ListConstruct(%0, %1)169 # CHECK: prim::Constant[value="cuda"]()170 %18 : Device = prim::Constant[value="cuda"]()171 %8 : Tensor = aten::zeros(%2, %5, %5, %18, %5)172 return (%8)"""173 FileCheck().run(expect_gstr, zeros_cpu.graph)174if __name__ == "__main__":...

Full Screen

Full Screen

test_package.py

Source:test_package.py Github

copy

Full Screen

1# -*- coding: utf-8 -*-2"""3Created on Mon Jun 20 14:13:36 20224@author: seford5"""6#call_id_api_test7import os8import sys9import keyring10# getting the name of the director where the this file is present.11current = os.path.realpath(os.getcwd())12# Getting the parent directory name where the current directory is present.13parent = os.path.dirname(current)14# adding the parent directory to the sys.path.15if parent not in sys.path:16 sys.path.append(parent)17from src.viyapy.viya_utils import call_id_api, unpack_viya_outputs18username='seford'19#authentication token (get from Paige)20token=keyring.get_password('buds35_token',username)21host='eeclxvm067.exnet.sas.com'22password=keyring.get_password('buds35_pwd',username)23protocol='http'24#base URL for Viya25baseUrl = protocol + '://' + host + '/'26moduleID = 'api_tester1_0'27features = {'input_string': "this is a test"}28 29test_passes = True30test_details = []31try:32 response = call_id_api(baseUrl, token, features, moduleID)33except:34 test_passes = False35 test_details.append('call_id_api failed')36if test_passes:37 try:38 output_dict = unpack_viya_outputs(response['outputs'])39 except:40 test_passes = False41 test_details.append('unpack_viya_outputs failed')42if test_passes:43 if 'input_string' not in output_dict.keys():44 test_passes = False45 test_details.append('input string is not in the Viya return call')46 else:47 if output_dict['input_string'] != features['input_string']:48 test_passes = False49 test_details.append('input string is incorrect')50 51if test_passes:52 if 'output_string' not in output_dict.keys():53 test_passes = False54 test_details.append('output string is not in the Viya return call')55 else:56 if output_dict['output_string'] != "successfully ran decision flow":57 test_passes = False58 test_details.append('output_string is incorrect')59 60if test_passes:61 print('tests PASSED')62else:63 print('test FAILED')...

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run autotest automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful