text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def transform_padding(pad_width): """Helper function to convert padding format for pad operator. """
num_pad_values = len(pad_width) onnx_pad_width = [0]*num_pad_values start_index = 0 # num_pad_values will always be multiple of 2 end_index = int(num_pad_values/2) for idx in range(0, num_pad_values): if idx % 2 == 0: onnx_pad_width[start_index] = pad_width[idx] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_string_to_list(string_val): """Helper function to convert string to list. Used to convert shape attribute string to list format. """
result_list = [] list_string = string_val.split(',') for val in list_string: val = str(val.strip()) val = val.replace("(", "") val = val.replace(")", "") val = val.replace("L", "") val = val.replace("[", "") val = val.replace("]", "") if val not in (...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_inputs(node, kwargs): """Helper function to get inputs"""
name = node["name"] proc_nodes = kwargs["proc_nodes"] index_lookup = kwargs["index_lookup"] inputs = node["inputs"] attrs = node.get("attrs", {}) input_nodes = [] for ip in inputs: input_node_id = index_lookup[ip[0]] input_nodes.append(proc_nodes[input_node_id].name) r...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_basic_op_node(op_name, node, kwargs): """Helper function to create a basic operator node that doesn't contain op specific attrs"""
name, input_nodes, _ = get_inputs(node, kwargs) node = onnx.helper.make_node( op_name, input_nodes, [name], name=name ) return [node]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_weights_and_inputs(node, **kwargs): """Helper function to convert weights and inputs. """
name, _, _ = get_inputs(node, kwargs) if kwargs["is_input"] is False: weights = kwargs["weights"] initializer = kwargs["initializer"] np_arr = weights[name] data_type = onnx.mapping.NP_TYPE_TO_TENSOR_TYPE[np_arr.dtype] dims = np.shape(np_arr) tensor_node = onnx...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_convolution(node, **kwargs): """Map MXNet's convolution operator attributes to onnx's Conv operator and return the created node. """
name, input_nodes, attrs = get_inputs(node, kwargs) kernel_dims = list(parse_helper(attrs, "kernel")) stride_dims = list(parse_helper(attrs, "stride", [1, 1])) pad_dims = list(parse_helper(attrs, "pad", [0, 0])) num_group = int(attrs.get("num_group", 1)) dilations = list(parse_helper(attrs, "d...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_deconvolution(node, **kwargs): """Map MXNet's deconvolution operator attributes to onnx's ConvTranspose operator and return the created node. """
name, inputs, attrs = get_inputs(node, kwargs) kernel_dims = list(parse_helper(attrs, "kernel")) stride_dims = list(parse_helper(attrs, "stride", [1, 1])) pad_dims = list(parse_helper(attrs, "pad", [0, 0])) num_group = int(attrs.get("num_group", 1)) dilations = list(parse_helper(attrs, "dilate...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_crop(node, **kwargs): """Map MXNet's crop operator attributes to onnx's Crop operator and return the created node. """
name, inputs, attrs = get_inputs(node, kwargs) num_inputs = len(inputs) y, x = list(parse_helper(attrs, "offset", [0, 0])) h, w = list(parse_helper(attrs, "h_w", [0, 0])) if num_inputs > 1: h, w = kwargs["out_shape"][-2:] border = [x, y, x + w, y + h] crop_node = onnx.helper.make_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_fully_connected(node, **kwargs): """Map MXNet's FullyConnected operator attributes to onnx's Gemm operator and return the created node. """
name, input_nodes, attrs = get_inputs(node, kwargs) initializer = kwargs["initializer"] no_bias = get_boolean_attribute_value(attrs, "no_bias") fcnode = [] op_name = "flatten_" + str(kwargs["idx"]) flatten_node = onnx.helper.make_node( 'Flatten', inputs=[input_nodes[0]], ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_batchnorm(node, **kwargs): """Map MXNet's BatchNorm operator attributes to onnx's BatchNormalization operator and return the created node. """
name, input_nodes, attrs = get_inputs(node, kwargs) momentum = float(attrs.get("momentum", 0.9)) eps = float(attrs.get("eps", 0.001)) bn_node = onnx.helper.make_node( "BatchNormalization", input_nodes, [name], name=name, epsilon=eps, momentum=momentum, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_pad(node, **kwargs): """Map MXNet's pad operator attributes to onnx's Pad operator and return the created node. """
name, input_nodes, attrs = get_inputs(node, kwargs) mxnet_pad_width = convert_string_to_list(attrs.get("pad_width")) onnx_pad_width = transform_padding(mxnet_pad_width) pad_mode = attrs.get("mode") if pad_mode == "constant": pad_value = float(attrs.get("constant_value")) \ if...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_helper_trans_node(op_name, input_node, node_name): """create extra transpose node for dot operator"""
node_name = op_name + "_" + node_name trans_node = onnx.helper.make_node( 'Transpose', inputs=[input_node], outputs=[node_name], name=node_name ) return trans_node
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_dot(node, **kwargs): """Map MXNet's dot operator attributes to onnx's MatMul and Transpose operators based on the values set for transpose_a, transpo...
name, input_nodes, attrs = get_inputs(node, kwargs) input_node_a = input_nodes[0] input_node_b = input_nodes[1] trans_a_node = None trans_b_node = None trans_a = get_boolean_attribute_value(attrs, "transpose_a") trans_b = get_boolean_attribute_value(attrs, "transpose_b") op_name = "t...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_linalg_gemm2(node, **kwargs): """Map MXNet's _linalg_gemm2 operator attributes to onnx's MatMul and Transpose operators based on the values set for t...
name, input_nodes, attrs = get_inputs(node, kwargs) # Getting the attributes and assigning default values. alpha = float(attrs.get("alpha", 1.0)) trans_a = get_boolean_attribute_value(attrs, "transpose_a") trans_b = get_boolean_attribute_value(attrs, "transpose_b") op_name = "transpose" + str...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_instancenorm(node, **kwargs): """Map MXNet's InstanceNorm operator attributes to onnx's InstanceNormalization operator based on the input node's attr...
name, input_nodes, attrs = get_inputs(node, kwargs) eps = float(attrs.get("eps", 0.001)) node = onnx.helper.make_node( 'InstanceNormalization', inputs=input_nodes, outputs=[name], name=name, epsilon=eps) return [node]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_softmax(node, **kwargs): """Map MXNet's softmax operator attributes to onnx's Softmax operator and return the created node. """
name, input_nodes, attrs = get_inputs(node, kwargs) axis = int(attrs.get("axis", -1)) softmax_node = onnx.helper.make_node( "Softmax", input_nodes, [name], axis=axis, name=name ) return [softmax_node]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_concat(node, **kwargs): """Map MXNet's Concat operator attributes to onnx's Concat operator and return the created node. """
name, input_nodes, attrs = get_inputs(node, kwargs) axis = int(attrs.get("dim", 1)) concat_node = onnx.helper.make_node( "Concat", input_nodes, [name], axis=axis, name=name ) return [concat_node]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_transpose(node, **kwargs): """Map MXNet's transpose operator attributes to onnx's Transpose operator and return the created node. """
name, input_nodes, attrs = get_inputs(node, kwargs) axes = attrs.get("axes", ()) if axes: axes = tuple(map(int, re.findall(r'\d+', axes))) transpose_node = onnx.helper.make_node( "Transpose", input_nodes, [name], perm=axes, name=...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_lrn(node, **kwargs): """Map MXNet's LRN operator attributes to onnx's LRN operator and return the created node. """
name, input_nodes, attrs = get_inputs(node, kwargs) alpha = float(attrs.get("alpha", 0.0001)) beta = float(attrs.get("beta", 0.75)) bias = float(attrs.get("knorm", 1.0)) size = int(attrs.get("nsize")) lrn_node = onnx.helper.make_node( "LRN", inputs=input_nodes, outputs...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_l2normalization(node, **kwargs): """Map MXNet's L2Normalization operator attributes to onnx's LpNormalization operator and return the created node. "...
name, input_nodes, attrs = get_inputs(node, kwargs) mode = attrs.get("mode", "instance") if mode != "channel": raise AttributeError("L2Normalization: ONNX currently supports channel mode only") l2norm_node = onnx.helper.make_node( "LpNormalization", input_nodes, [name...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_dropout(node, **kwargs): """Map MXNet's Dropout operator attributes to onnx's Dropout operator and return the created node. """
name, input_nodes, attrs = get_inputs(node, kwargs) probability = float(attrs.get("p", 0.5)) dropout_node = onnx.helper.make_node( "Dropout", input_nodes, [name], ratio=probability, name=name ) return [dropout_node]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_clip(node, **kwargs): """Map MXNet's Clip operator attributes to onnx's Clip operator and return the created node. """
name, input_nodes, attrs = get_inputs(node, kwargs) a_min = np.float(attrs.get('a_min', -np.inf)) a_max = np.float(attrs.get('a_max', np.inf)) clip_node = onnx.helper.make_node( "Clip", input_nodes, [name], name=name, min=a_min, max=a_max ) retu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def scalar_op_helper(node, op_name, **kwargs): """Helper function for scalar arithmetic operations"""
name, input_nodes, attrs = get_inputs(node, kwargs) from onnx import numpy_helper input_type = kwargs["in_type"] scalar_value = np.array([attrs.get("scalar", 1)], dtype=onnx.mapping.TENSOR_TYPE_TO_NP_TYPE[input_type]) initializer = kwargs["initializer"] flag = True ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_argmax(node, **kwargs): """Map MXNet's argmax operator attributes to onnx's ArgMax operator and return the created node. """
name, input_nodes, attrs = get_inputs(node, kwargs) axis = int(attrs.get("axis")) keepdims = get_boolean_attribute_value(attrs, "keepdims") node = onnx.helper.make_node( 'ArgMax', inputs=input_nodes, axis=axis, keepdims=keepdims, outputs=[name], name=na...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_reshape(node, **kwargs): """Map MXNet's Reshape operator attributes to onnx's Reshape operator. Converts output shape attribute to output shape tenso...
name, input_nodes, attrs = get_inputs(node, kwargs) output_shape_list = convert_string_to_list(attrs["shape"]) initializer = kwargs["initializer"] output_shape_np = np.array(output_shape_list, dtype='int64') data_type = onnx.mapping.NP_TYPE_TO_TENSOR_TYPE[output_shape_np.dtype] dims = np.shap...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_cast(node, **kwargs): """Map MXNet's Cast operator attributes to onnx's Cast operator and return the created node. """
name, input_nodes, attrs = get_inputs(node, kwargs) dtype = attrs["dtype"] # dtype can be mapped only with types from TensorProto # float32 is mapped to float and float64 to double in onnx # following tensorproto mapping https://github.com/onnx/onnx/blob/master/onnx/mapping.py if dtype == 'fl...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_slice_axis(node, **kwargs): """Map MXNet's slice_axis operator attributes to onnx's Slice operator and return the created node. """
name, input_nodes, attrs = get_inputs(node, kwargs) axes = int(attrs.get("axis")) starts = int(attrs.get("begin")) ends = int(attrs.get("end", None)) if not ends: raise ValueError("Slice: ONNX doesnt't support 'None' in 'end' attribute") node = onnx.helper.make_node( "Slice", ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_slice_channel(node, **kwargs): """Map MXNet's SliceChannel operator attributes to onnx's Squeeze or Split operator based on squeeze_axis attribute an...
name, input_nodes, attrs = get_inputs(node, kwargs) num_outputs = int(attrs.get("num_outputs")) axis = int(attrs.get("axis", 1)) squeeze_axis = int(attrs.get("squeeze_axis", 0)) if squeeze_axis == 1 and num_outputs == 1: node = onnx.helper.make_node( "Squeeze", inp...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_expand_dims(node, **kwargs): """Map MXNet's expand_dims operator attributes to onnx's Unsqueeze operator and return the created node. """
name, input_nodes, attrs = get_inputs(node, kwargs) axis = int(attrs.get("axis")) node = onnx.helper.make_node( "Unsqueeze", input_nodes, [name], axes=[axis], name=name, ) return [node]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_squeeze(node, **kwargs): """Map MXNet's squeeze operator attributes to onnx's squeeze operator and return the created node. """
name, input_nodes, attrs = get_inputs(node, kwargs) axis = attrs.get("axis", None) if not axis: raise AttributeError("Squeeze: Missing axis attribute: ONNX currently requires axis to " "be specified for squeeze operator") axis = convert_string_to_list(axis) no...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_depthtospace(node, **kwargs): """Map MXNet's depth_to_space operator attributes to onnx's DepthToSpace operator and return the created node. """
name, input_nodes, attrs = get_inputs(node, kwargs) blksize = int(attrs.get("block_size", 0)) node = onnx.helper.make_node( "DepthToSpace", input_nodes, [name], blocksize=blksize, name=name, ) return [node]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_square(node, **kwargs): """Map MXNet's square operator attributes to onnx's Pow operator and return the created node. """
name, input_nodes, _ = get_inputs(node, kwargs) initializer = kwargs["initializer"] data_type = onnx.mapping.NP_TYPE_TO_TENSOR_TYPE[np.dtype('int64')] power2_name = "square_tensor" + str(kwargs["idx"]) tensor_node = onnx.helper.make_tensor_value_info(power2_name, data_type, (1,)) initializer....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_sum(node, **kwargs): """Map MXNet's sum operator attributes to onnx's ReduceSum operator and return the created node. """
name, input_nodes, attrs = get_inputs(node, kwargs) mx_axis = attrs.get("axis", None) axes = convert_string_to_list(str(mx_axis)) if mx_axis is not None else None keepdims = get_boolean_attribute_value(attrs, "keepdims") if axes: node = onnx.helper.make_node( 'ReduceSum', ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_hardsigmoid(node, **kwargs): """Map MXNet's hard_sigmoid operator attributes to onnx's HardSigmoid operator and return the created node. """
name, input_nodes, attrs = get_inputs(node, kwargs) # Converting to float32 alpha = float(attrs.get("alpha", 0.2)) beta = float(attrs.get("beta", 0.5)) node = onnx.helper.make_node( 'HardSigmoid', input_nodes, [name], alpha=alpha, beta=beta, name=na...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_logsoftmax(node, **kwargs): """Map MXNet's log_softmax operator attributes to onnx's LogSoftMax operator and return the created node. """
name, input_nodes, attrs = get_inputs(node, kwargs) # Converting to int axis = int(attrs.get("axis", -1)) temp = attrs.get("temperature", 'None') if temp != 'None': raise AttributeError("LogSoftMax: ONNX supports only temperature=None") node = onnx.helper.make_node( 'LogSoftma...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_norm(node, **kwargs): """Map MXNet's norm operator attributes to onnx's ReduceL1 and ReduceL2 operators and return the created node. """
name, input_nodes, attrs = get_inputs(node, kwargs) mx_axis = attrs.get("axis", None) axes = convert_string_to_list(str(mx_axis)) if mx_axis else None keepdims = get_boolean_attribute_value(attrs, "keepdims") ord = int(attrs.get("ord", 2)) onnx_op_name = "ReduceL1" if ord == 1 else "ReduceL2...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_multinomial(node, **kwargs): """Map MXNet's multinomial operator attributes to onnx's Multinomial operator and return the created node. """
name, input_nodes, attrs = get_inputs(node, kwargs) dtype = onnx.mapping.NP_TYPE_TO_TENSOR_TYPE[np.dtype(attrs.get("dtype", 'int32'))] sample_size = convert_string_to_list(attrs.get("shape", '1')) if len(sample_size) < 2: sample_size = sample_size[-1] else: raise AttributeError("ONN...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_random_uniform(node, **kwargs): """Map MXNet's random_uniform operator attributes to onnx's RandomUniform operator and return the created node. """
name, input_nodes, attrs = get_inputs(node, kwargs) # Converting to float32 low = float(attrs.get("low", 0)) high = float(attrs.get("high", 1.0)) shape = convert_string_to_list(attrs.get('shape', '[]')) dtype = onnx.mapping.NP_TYPE_TO_TENSOR_TYPE[np.dtype(attrs.get('dtype', 'float32'))] n...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_random_normal(node, **kwargs): """Map MXNet's random_normal operator attributes to onnx's RandomNormal operator and return the created node. """
name, input_nodes, attrs = get_inputs(node, kwargs) # Converting to float32 mean = float(attrs.get("loc", 0)) scale = float(attrs.get("scale", 1.0)) shape = convert_string_to_list(attrs.get('shape', '[]')) dtype = onnx.mapping.NP_TYPE_TO_TENSOR_TYPE[np.dtype(attrs.get('dtype', 'float32'))] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_roipooling(node, **kwargs): """Map MXNet's ROIPooling operator attributes to onnx's MaxRoiPool operator and return the created node. """
name, input_nodes, attrs = get_inputs(node, kwargs) pooled_shape = convert_string_to_list(attrs.get('pooled_size')) scale = float(attrs.get("spatial_scale")) node = onnx.helper.make_node( 'MaxRoiPool', input_nodes, [name], pooled_shape=pooled_shape, spatial_sca...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_tile(node, **kwargs): """Map MXNet's Tile operator attributes to onnx's Tile operator and return the created node. """
name, input_nodes, attrs = get_inputs(node, kwargs) reps_list = convert_string_to_list(attrs["reps"]) initializer = kwargs["initializer"] reps_shape_np = np.array(reps_list, dtype='int64') data_type = onnx.mapping.NP_TYPE_TO_TENSOR_TYPE[reps_shape_np.dtype] dims = np.shape(reps_shape_np) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_broadcast_to(node, **kwargs): """Map MXNet's broadcast_to operator attributes to onnx's Expand operator and return the created node. """
name, input_nodes, attrs = get_inputs(node, kwargs) shape_list = convert_string_to_list(attrs["shape"]) initializer = kwargs["initializer"] output_shape_np = np.array(shape_list, dtype='int64') data_type = onnx.mapping.NP_TYPE_TO_TENSOR_TYPE[output_shape_np.dtype] dims = np.shape(output_shape...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def exe(self): """Get the current executor Returns ------- exe : mxnet.executor.Executor """
return self._buckets[self.curr_bucket_key]['exe'][tuple(self.data_shapes.items())]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compute_internal(self, sym_name, bucket_kwargs=None, **arg_dict): """ View the internal symbols using the forward function. :param sym_name: :param bucket_kw...
data_shapes = {k: v.shape for k, v in arg_dict.items()} self.switch_bucket(bucket_kwargs=bucket_kwargs, data_shapes=data_shapes) internal_sym = self.sym.get_internals()[sym_name] data_inputs = {k: mx.nd.empty(v, ctx=self.ctx) for k, v in...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def init_from_fcnxs(ctx, fcnxs_symbol, fcnxs_args_from, fcnxs_auxs_from): """ use zero initialization for better convergence, because it tends to oputut 0, and t...
fcnxs_args = fcnxs_args_from.copy() fcnxs_auxs = fcnxs_auxs_from.copy() for k,v in fcnxs_args.items(): if(v.context != ctx): fcnxs_args[k] = mx.nd.zeros(v.shape, ctx) v.copyto(fcnxs_args[k]) for k,v in fcnxs_auxs.items(): if(v.context != ctx): fcnxs_a...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def var(name, attr=None, shape=None, lr_mult=None, wd_mult=None, dtype=None, init=None, stype=None, **kwargs): """Creates a symbolic variable with specified name...
if not isinstance(name, string_types): raise TypeError('Expect a string for variable `name`') handle = SymbolHandle() check_call(_LIB.MXSymbolCreateVariable(c_str(name), ctypes.byref(handle))) ret = Symbol(handle) if not hasattr(AttrScope._current, "value"): AttrScope._current.value...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def Group(symbols): """Creates a symbol that contains a collection of other symbols, grouped together. Example ------- <Symbol Grouped> Parameters symbols : list...
if not symbols or any(not isinstance(sym, Symbol) for sym in symbols): raise TypeError('Expected a list of symbols as input') handle = SymbolHandle() check_call(_LIB.MXSymbolCreateGroup( mx_uint(len(symbols)), c_handle_array(symbols), ctypes.byref(handle))) return Symbol(handle)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load(fname): """Loads symbol from a JSON file. You can also use pickle to do the job if you only work on python. The advantage of load/save is the file is la...
if not isinstance(fname, string_types): raise TypeError('fname need to be string') handle = SymbolHandle() check_call(_LIB.MXSymbolCreateFromFile(c_str(fname), ctypes.byref(handle))) return Symbol(handle)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_json(json_str): """Loads symbol from json string. Parameters json_str : str A JSON string. Returns ------- sym : Symbol The loaded symbol. See Also ----...
if not isinstance(json_str, string_types): raise TypeError('fname required to be string') handle = SymbolHandle() check_call(_LIB.MXSymbolCreateFromJSON(c_str(json_str), ctypes.byref(handle))) return Symbol(handle)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def maximum(left, right): """Returns element-wise maximum of the input elements. Both inputs can be Symbol or scalar number. Broadcasting is not supported. Param...
if isinstance(left, Symbol) and isinstance(right, Symbol): return _internal._Maximum(left, right) if isinstance(left, Symbol) and isinstance(right, Number): return _internal._MaximumScalar(left, scalar=right) if isinstance(left, Number) and isinstance(right, Symbol): return _interna...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def minimum(left, right): """Returns element-wise minimum of the input elements. Both inputs can be Symbol or scalar number. Broadcasting is not supported. Param...
if isinstance(left, Symbol) and isinstance(right, Symbol): return _internal._Minimum(left, right) if isinstance(left, Symbol) and isinstance(right, Number): return _internal._MinimumScalar(left, scalar=right) if isinstance(left, Number) and isinstance(right, Symbol): return _interna...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def hypot(left, right): """Given the "legs" of a right triangle, returns its hypotenuse. Equivalent to :math:`\\sqrt(left^2 + right^2)`, element-wise. Both input...
if isinstance(left, Symbol) and isinstance(right, Symbol): return _internal._Hypot(left, right) if isinstance(left, Symbol) and isinstance(right, Number): return _internal._HypotScalar(left, scalar=right) if isinstance(left, Number) and isinstance(right, Symbol): return _internal._H...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def eye(N, M=0, k=0, dtype=None, **kwargs): """Returns a new symbol of 2-D shpae, filled with ones on the diagonal and zeros elsewhere. Parameters N: int Number ...
if dtype is None: dtype = _numpy.float32 return _internal._eye(N, M, k, dtype=dtype, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def zeros(shape, dtype=None, **kwargs): """Returns a new symbol of given shape and type, filled with zeros. Parameters shape : int or sequence of ints Shape of t...
if dtype is None: dtype = _numpy.float32 return _internal._zeros(shape=shape, dtype=dtype, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ones(shape, dtype=None, **kwargs): """Returns a new symbol of given shape and type, filled with ones. Parameters shape : int or sequence of ints Shape of the...
if dtype is None: dtype = _numpy.float32 return _internal._ones(shape=shape, dtype=dtype, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def name(self): """Gets name string from the symbol, this function only works for non-grouped symbol. Returns ------- value : str The name of this symbol, return...
ret = ctypes.c_char_p() success = ctypes.c_int() check_call(_LIB.MXSymbolGetName( self.handle, ctypes.byref(ret), ctypes.byref(success))) if success.value != 0: return py_str(ret.value) else: return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def attr(self, key): """Returns the attribute string for corresponding input key from the symbol. This function only works for non-grouped symbols. Example -----...
ret = ctypes.c_char_p() success = ctypes.c_int() check_call(_LIB.MXSymbolGetAttr( self.handle, c_str(key), ctypes.byref(ret), ctypes.byref(success))) if success.value != 0: return py_str(ret.value) else: return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_attr(self, recursive=False): """Gets all attributes from the symbol. Example ------- {'mood': 'angry'} Returns ------- ret : Dict of str to str A dictio...
if recursive: raise DeprecationWarning("Symbol.list_attr with recursive=True has been deprecated. " "Please use attr_dict instead.") size = mx_uint() pairs = ctypes.POINTER(ctypes.c_char_p)() f_handle = _LIB.MXSymbolListAttrShallow ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def attr_dict(self): """Recursively gets all attributes from the symbol and its children. Example ------- {'a': {'a1': 'a2'}, 'b': {'b1': 'b2'}} Returns ------- ...
size = mx_uint() pairs = ctypes.POINTER(ctypes.c_char_p)() f_handle = _LIB.MXSymbolListAttr check_call(f_handle(self.handle, ctypes.byref(size), ctypes.byref(pairs))) ret = {} for i in range(size.value): name, key = py_str(pairs[i * 2]).split('$') ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _set_attr(self, **kwargs): """Sets an attribute of the symbol. For example. A._set_attr(foo="bar") adds the mapping ``"{foo: bar}"`` to the symbol's attribut...
for key, value in kwargs.items(): if not isinstance(value, string_types): raise ValueError("Set Attr only accepts string values") check_call(_LIB.MXSymbolSetAttr( self.handle, c_str(key), c_str(str(value))))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_internals(self): """Gets a new grouped symbol `sgroup`. The output of `sgroup` is a list of outputs of all of the internal nodes. Consider the following ...
handle = SymbolHandle() check_call(_LIB.MXSymbolGetInternals( self.handle, ctypes.byref(handle))) return Symbol(handle=handle)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_children(self): """Gets a new grouped symbol whose output contains inputs to output nodes of the original symbol. Example ------- <Symbol Grouped> ['x', ...
handle = SymbolHandle() check_call(_LIB.MXSymbolGetChildren( self.handle, ctypes.byref(handle))) ret = Symbol(handle=handle) if len(ret.list_outputs()) == 0: return None return ret
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_arguments(self): """Lists all the arguments in the symbol. Example ------- ['a', 'b'] Returns ------- args : list of string List containing the names of...
size = ctypes.c_uint() sarr = ctypes.POINTER(ctypes.c_char_p)() check_call(_LIB.MXSymbolListArguments( self.handle, ctypes.byref(size), ctypes.byref(sarr))) return [py_str(sarr[i]) for i in range(size.value)]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_outputs(self): """Lists all the outputs in the symbol. Example ------- ['_plus12_output'] Returns ------- list of str List of all the outputs. For most ...
size = ctypes.c_uint() sarr = ctypes.POINTER(ctypes.c_char_p)() check_call(_LIB.MXSymbolListOutputs( self.handle, ctypes.byref(size), ctypes.byref(sarr))) return [py_str(sarr[i]) for i in range(size.value)]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_auxiliary_states(self): """Lists all the auxiliary states in the symbol. Example ------- [] Example of auxiliary states in `BatchNorm`. ['batchnorm0_mov...
size = ctypes.c_uint() sarr = ctypes.POINTER(ctypes.c_char_p)() check_call(_LIB.MXSymbolListAuxiliaryStates( self.handle, ctypes.byref(size), ctypes.byref(sarr))) return [py_str(sarr[i]) for i in range(size.value)]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_inputs(self): """Lists all arguments and auxiliary states of this Symbol. Returns ------- inputs : list of str List of all inputs. Examples -------- ['b...
size = ctypes.c_uint() sarr = ctypes.POINTER(ctypes.c_char_p)() check_call(_LIB.NNSymbolListInputNames( self.handle, 0, ctypes.byref(size), ctypes.byref(sarr))) return [py_str(sarr[i]) for i in range(size.value)]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def infer_type(self, *args, **kwargs): """Infers the type of all arguments and all outputs, given the known types for some arguments. This function takes the kno...
try: res = self._infer_type_impl(False, *args, **kwargs) if res[1] is None: arg_shapes, _, _ = self._infer_type_impl(True, *args, **kwargs) arg_names = self.list_arguments() unknowns = [] for name, dtype in zip(arg_names, a...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _infer_type_impl(self, partial, *args, **kwargs): """The actual implementation for calling type inference API."""
# pylint: disable=too-many-locals if len(args) != 0 and len(kwargs) != 0: raise ValueError('Can only specify known argument \ types either by positional or kwargs way.') sdata = [] if len(args) != 0: keys = c_array(ctypes.c_char_p, []) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def infer_shape(self, *args, **kwargs): """Infers the shapes of all arguments and all outputs given the known shapes of some arguments. This function takes the k...
try: res = self._infer_shape_impl(False, *args, **kwargs) if res[1] is None: arg_shapes, _, _ = self._infer_shape_impl(True, *args, **kwargs) arg_names = self.list_arguments() unknowns = [] for name, shape in zip(arg_names,...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save(self, fname): """Saves symbol to a file. You can also use pickle to do the job if you only work on python. The advantage of `load`/`save` functions is t...
if not isinstance(fname, string_types): raise TypeError('fname need to be string') check_call(_LIB.MXSymbolSaveToFile(self.handle, c_str(fname)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tojson(self): """Saves symbol to a JSON string. See Also -------- symbol.load_json : Used to load symbol from JSON string. """
json_str = ctypes.c_char_p() check_call(_LIB.MXSymbolSaveToJSON(self.handle, ctypes.byref(json_str))) return py_str(json_str.value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_ndarray_inputs(arg_key, args, arg_names, allow_missing): """Helper function to get NDArray lists handles from various inputs. Parameters arg_key : str T...
# setup args arg_handles = [] arg_arrays = [] if isinstance(args, list): if len(args) != len(arg_names): raise ValueError('Length of %s does not match the number of arguments' % arg_key) for narr in args: if narr is None and allow_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bind(self, ctx, args, args_grad=None, grad_req='write', aux_states=None, group2ctx=None, shared_exec=None): """Binds the current symbol to an executor and re...
# pylint: disable=too-many-locals, too-many-branches if not isinstance(ctx, Context): raise TypeError("Context type error") listed_arguments = self.list_arguments() args_handle, args = self._get_ndarray_inputs('args', args, listed_arguments, False) # setup args grad...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def gradient(self, wrt): """Gets the autodiff of current symbol. This function can only be used if current symbol is a loss function. .. note:: This function is ...
handle = SymbolHandle() c_wrt = c_str_array(wrt) check_call(_LIB.MXSymbolGrad(self.handle, mx_uint(len(wrt)), c_wrt, ctypes.byref(handle))) return Symbol(handle)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def eval(self, ctx=None, **kwargs): """Evaluates a symbol given arguments. The `eval` method combines a call to `bind` (which returns an executor) with a call to...
if ctx is None: ctx = current_context() return self.bind(ctx, kwargs).forward()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_backend_symbol(self, backend): """Return symbol for target backend. Parameters backend : str The backend names. Returns ------- out : Symbol The created ...
out = SymbolHandle() check_call(_LIB.MXGenBackendSubgraph(self.handle, c_str(backend), ctypes.byref(out))) return Symbol(out)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_model(model_name, epoch_num, data_shapes, label_shapes, label_names, gpus=''): """Returns a module loaded with the provided model. Parameters model_name...
sym, arg_params, aux_params = mx.model.load_checkpoint(model_name, epoch_num) mod = create_module(sym, data_shapes, label_shapes, label_names, gpus) mod.set_params( arg_params=arg_params, aux_params=aux_params, allow_missing=True ) return mod
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_module(sym, data_shapes, label_shapes, label_names, gpus=''): """Creates a new MXNet module. Parameters sym : Symbol An MXNet symbol. input_shape: tup...
if gpus == '': devices = mx.cpu() else: devices = [mx.gpu(int(i)) for i in gpus.split(',')] data_names = [data_shape[0] for data_shape in data_shapes] mod = mx.mod.Module( symbol=sym, data_names=data_names, context=devices, label_names=label_names )...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def evaluate_net(net, path_imgrec, num_classes, num_batch, mean_pixels, data_shape, model_prefix, epoch, ctx=mx.cpu(), batch_size=32, path_imglist="", nms_thresh=...
# set up logger logging.basicConfig() logger = logging.getLogger() logger.setLevel(logging.INFO) # args if isinstance(data_shape, int): data_shape = (3, data_shape, data_shape) assert len(data_shape) == 3 and data_shape[0] == 3 model_prefix += '_' + str(data_shape[1]) # it...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def init_params(self, initializer=Uniform(0.01), arg_params=None, aux_params=None, allow_missing=False, force_init=False, allow_extra=False): """Initializes the ...
pass
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_metric(self, eval_metric, labels, pre_sliced=False): """Evaluates and accumulates evaluation metric on outputs of the last forward computation. Subcla...
if self._label_shapes is None: # since we do not need labels, we are probably not a module with a loss # function or predictions, so just ignore this call return if pre_sliced: raise RuntimeError("PythonModule does not support presliced labels") ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def forward(self, data_batch, is_train=None): """Forward computation. Here we do nothing but to keep a reference to the scores and the labels so that we can do b...
self._scores = data_batch.data[0] if is_train is None: is_train = self.for_training if is_train: self._labels = data_batch.label[0]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _backward_impl(self): """Actual implementation of the backward computation. The computation should take ``self._scores`` and ``self._labels`` and then comput...
if self._grad_func is not None: grad = self._grad_func(self._scores, self._labels) if not isinstance(grad, nd.NDArray): grad = nd.array(grad) self._scores_grad = grad else: raise NotImplementedError()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get(self, name, **kwargs): """Get the variable given a name if one exists or create a new one if missing. Parameters name : str name of the variable **kwargs...
name = self._prefix + name if name not in self._params: self._params[name] = symbol.Variable(name, **kwargs) return self._params[name]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unpack_weights(self, args): """Unpack fused weight matrices into separate weight matrices. For example, say you use a module object `mod` to run a network th...
args = args.copy() if not self._gate_names: return args h = self._num_hidden for group_name in ['i2h', 'h2h']: weight = args.pop('%s%s_weight'%(self._prefix, group_name)) bias = args.pop('%s%s_bias' % (self._prefix, group_name)) for j, gat...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pack_weights(self, args): """Pack separate weight matrices into a single packed weight. Parameters args : dict of str -> NDArray Dictionary containing unpack...
args = args.copy() if not self._gate_names: return args for group_name in ['i2h', 'h2h']: weight = [] bias = [] for gate in self._gate_names: wname = '%s%s%s_weight'%(self._prefix, group_name, gate) weight.append(ar...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unroll(self, length, inputs, begin_state=None, layout='NTC', merge_outputs=None): """Unroll an RNN cell across time steps. Parameters length : int Number of ...
self.reset() inputs, _ = _normalize_sequence(length, inputs, layout, False) if begin_state is None: begin_state = self.begin_state() states = begin_state outputs = [] for i in range(length): output, states = self(inputs[i], states) o...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _slice_weights(self, arr, li, lh): """slice fused rnn weights"""
args = {} gate_names = self._gate_names directions = self._directions b = len(directions) p = 0 for layer in range(self._num_layers): for direction in directions: for gate in gate_names: name = '%s%s%d_i2h%s_weight'%(self....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unfuse(self): """Unfuse the fused RNN in to a stack of rnn cells. Returns ------- cell : mxnet.rnn.SequentialRNNCell unfused cell that can be used for steppi...
stack = SequentialRNNCell() get_cell = {'rnn_relu': lambda cell_prefix: RNNCell(self._num_hidden, activation='relu', prefix=cell_prefix), 'rnn_tanh': lambda cell_p...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add(self, cell): """Append a cell into the stack. Parameters cell : BaseRNNCell The cell to be appended. During unroll, previous cell's output (or raw inputs...
self._cells.append(cell) if self._override_cell_params: assert cell._own_params, \ "Either specify params for SequentialRNNCell " \ "or child cells, not both." cell.params._params.update(self.params._params) self.params._params.update(cell...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def main(): """Entrypoint for compare_layers"""
parser = argparse.ArgumentParser( description='Tool for testing caffe to mxnet conversion layer by layer') parser.add_argument('--image_url', type=str, default='https://github.com/dmlc/web-data/raw/master/mxnet/doc/'\ 'tutorials/python/predict_im...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def copy_param(exe, new_param=None): """Create copy of parameters"""
if new_param is None: new_param = {k: nd.empty(v.shape, ctx=mx.cpu()) for k, v in exe.arg_dict.items()} for k, v in new_param.items(): exe.arg_dict[k].copyto(v) return new_param
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_mnist_sym(output_op=None, num_hidden=400): """Get symbol of mnist"""
net = mx.symbol.Variable('data') net = mx.symbol.FullyConnected(data=net, name='mnist_fc1', num_hidden=num_hidden) net = mx.symbol.Activation(data=net, name='mnist_relu1', act_type="relu") net = mx.symbol.FullyConnected(data=net, name='mnist_fc2', num_hidden=num_hidden) net = mx.symbol.Activation(d...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def synthetic_grad(X, theta, sigma1, sigma2, sigmax, rescale_grad=1.0, grad=None): """Get synthetic gradient value"""
if grad is None: grad = nd.empty(theta.shape, theta.context) theta1 = theta.asnumpy()[0] theta2 = theta.asnumpy()[1] v1 = sigma1 ** 2 v2 = sigma2 ** 2 vx = sigmax ** 2 denominator = numpy.exp(-(X - theta1) ** 2 / (2 * vx)) + numpy.exp( -(X - theta1 - theta2) ** 2 / (2 * vx))...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_toy_sym(teacher=True, teacher_noise_precision=None): """Get toy symbol"""
if teacher: net = mx.symbol.Variable('data') net = mx.symbol.FullyConnected(data=net, name='teacher_fc1', num_hidden=100) net = mx.symbol.Activation(data=net, name='teacher_relu1', act_type="relu") net = mx.symbol.FullyConnected(data=net, name='teacher_fc2', num_hidden=1) ne...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run_mnist_DistilledSGLD(num_training=50000, gpu_id=None): """Run DistilledSGLD on mnist dataset"""
X, Y, X_test, Y_test = load_mnist(num_training) minibatch_size = 100 if num_training >= 10000: num_hidden = 800 total_iter_num = 1000000 teacher_learning_rate = 1E-6 student_learning_rate = 0.0001 teacher_prior = 1 student_prior = 0.1 perturb_deviatio...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run_toy_SGLD(gpu_id=None): """Run SGLD on toy dataset"""
X, Y, X_test, Y_test = load_toy() minibatch_size = 1 teacher_noise_precision = 1.0 / 9.0 net = get_toy_sym(True, teacher_noise_precision) data_shape = (minibatch_size,) + X.shape[1::] data_inputs = {'data': nd.zeros(data_shape, ctx=dev(gpu_id)), 'teacher_output_label': nd.zer...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run_toy_DistilledSGLD(gpu_id): """Run DistilledSGLD on toy dataset"""
X, Y, X_test, Y_test = load_toy() minibatch_size = 1 teacher_noise_precision = 1.0 teacher_net = get_toy_sym(True, teacher_noise_precision) student_net = get_toy_sym(False) data_shape = (minibatch_size,) + X.shape[1::] teacher_data_inputs = {'data': nd.zeros(data_shape, ctx=dev(gpu_id)), ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run_toy_HMC(gpu_id=None): """Run HMC on toy dataset"""
X, Y, X_test, Y_test = load_toy() minibatch_size = Y.shape[0] noise_precision = 1 / 9.0 net = get_toy_sym(True, noise_precision) data_shape = (minibatch_size,) + X.shape[1::] data_inputs = {'data': nd.zeros(data_shape, ctx=dev(gpu_id)), 'teacher_output_label': nd.zeros((minib...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run_synthetic_SGLD(): """Run synthetic SGLD"""
theta1 = 0 theta2 = 1 sigma1 = numpy.sqrt(10) sigma2 = 1 sigmax = numpy.sqrt(2) X = load_synthetic(theta1=theta1, theta2=theta2, sigmax=sigmax, num=100) minibatch_size = 1 total_iter_num = 1000000 lr_scheduler = SGLDScheduler(begin_rate=0.01, end_rate=0.0001, total_iter_num=total_it...