Creates a fp32 copy of model parameters and sets optimizer parameters
495100
def copy_model_to_fp32(m, optim):
    
    fp32_params = [m_param.clone().type(torch.cuda.FloatTensor).detach() for m_param in trainable_params_(m)]
    optim_groups = [group['params'] for group in optim.param_groups]
    iter_fp32_params = iter(fp32_params)
    for group_params in optim_groups:
        for i in range(len(group_params)):
            if not group_params[i].requires_grad: continue # only update trainable_params_
            fp32_param = next(iter_fp32_params)
            assert(fp32_param.shape == group_params[i].shape)
            fp32_param.requires_grad = group_params[i].requires_grad
            group_params[i] = fp32_param
    return fp32_params
601573
def _set_parameter(encoder, parameter, parameter_name, val):
    
    rc = lib.BrotliEncoderSetParameter(encoder, parameter, val)

    if parameter == lib.BROTLI_PARAM_MODE:
        _validate_mode(val)
    elif parameter == lib.BROTLI_PARAM_QUALITY:
        _validate_quality(val)
    elif parameter == lib.BROTLI_PARAM_LGWIN:
        _validate_lgwin(val)
    elif parameter == lib.BROTLI_PARAM_LGBLOCK:
        _validate_lgblock(val)
    else:  # pragma: no cover
        raise RuntimeError("Unexpected parameter!")

    # This block is defensive: I see no way to hit it, but as long as the
    # function returns a value we can live in hope that the brotli folks will
    # enforce their own constraints.
    if rc != lib.BROTLI_TRUE:  # pragma: no cover
        raise Error(
            "Error setting parameter %s: %d" % (parameter_name, val)
        )
1369997
def optimize(self, f=None, df=None, f_df=None, duplicate_manager=None):
        
        self.f = f
        self.df = df
        self.f_df = f_df

        ## --- Update the optimizer, in case context has beee passed.
        self.optimizer = choose_optimizer(self.optimizer_name, self.context_manager.noncontext_bounds)

        ## --- Selecting the anchor points and removing duplicates
        if self.type_anchor_points_logic == max_objective_anchor_points_logic:
            anchor_points_generator = ObjectiveAnchorPointsGenerator(self.space, random_design_type, f)
        elif self.type_anchor_points_logic == thompson_sampling_anchor_points_logic:
            anchor_points_generator = ThompsonSamplingAnchorPointsGenerator(self.space, sobol_design_type, self.model)

        ## -- Select the anchor points (with context)
        anchor_points = anchor_points_generator.get(duplicate_manager=duplicate_manager, context_manager=self.context_manager)

        ## --- Applying local optimizers at the anchor points and update bounds of the optimizer (according to the context)
        optimized_points = [apply_optimizer(self.optimizer, a, f=f, df=None, f_df=f_df, duplicate_manager=duplicate_manager, context_manager=self.context_manager, space = self.space) for a in anchor_points]
        x_min, fx_min = min(optimized_points, key=lambda t:t[1])

        #x_min, fx_min = min([apply_optimizer(self.optimizer, a, f=f, df=None, f_df=f_df, duplicate_manager=duplicate_manager, context_manager=self.context_manager, space = self.space) for a in anchor_points], key=lambda t:t[1])

        return x_min, fx_min
891558
function _from_file (fname_tmpl, opts, cfg_so_far, cb) {
  var vals = {
    env: process.env.NODE_ENV || 'development'
  };

  _.merge (vals, cfg_so_far);
  
  var fname = interpolator.parse (fname_tmpl, vals);

  // check existence
  fs.access (fname, function (err) {
    if (err) {
      if (opts.ignore_missing) {
        return cb (null, {});
      }
      else {
        return cb (err);
      }
    }

    var obj = {};
  
    try {
      obj = importFresh (fname);
    } 
    catch (e) {
      return cb (e);
    }

    // expand variables in loaded object
    _expand (obj, vals, cb);
  });
}
1090624
def clone(cls, model, use_json=True, use_lp=False):
        
        model.update()
        interface = sys.modules[cls.__module__]

        if use_lp:
            warnings.warn("Cloning with LP formats can change variable and constraint ID's.")
            new_model = cls.from_lp(model.to_lp())
            new_model.configuration = interface.Configuration.clone(model.configuration, problem=new_model)
            return new_model

        if use_json:
            new_model = cls.from_json(model.to_json())
            new_model.configuration = interface.Configuration.clone(model.configuration, problem=new_model)
            return new_model

        new_model = cls()
        for variable in model.variables:
            new_variable = interface.Variable.clone(variable)
            new_model._add_variable(new_variable)
        for constraint in model.constraints:
            new_constraint = interface.Constraint.clone(constraint, model=new_model)
            new_model._add_constraint(new_constraint)
        if model.objective is not None:
            new_model.objective = interface.Objective.clone(model.objective, model=new_model)
        new_model.configuration = interface.Configuration.clone(model.configuration, problem=new_model)
        return new_model
1022599
def copy(self):
        

        copied_model = GPModel( kernel = self.model.kern.copy(),
                                noise_var= self.noise_var ,
                                exact_feval= self.exact_feval,
                                n_samples = self.n_samples,
                                n_burnin = self.n_burnin,
                                subsample_interval = self.subsample_interval,
                                step_size = self.step_size,
                                leapfrog_steps= self.leapfrog_steps,
                                verbose= self.verbose)

        copied_model._create_model(self.model.X,self.model.Y)
        copied_model.updateModel(self.model.X,self.model.Y, None, None)
        return copied_model
290900
def save_optimizer_states(self, fname):
        
        assert self.optimizer_initialized

        if self._update_on_kvstore:
            self._kvstore.save_optimizer_states(fname)
        else:
            with open(fname, 'wb') as fout:
                fout.write(self._updater.get_states())
731255
function (aMethods) {
			var fnCreateTypesArr = function (sTypes) {
				return sTypes.split("|").map(function (sType) {
					return {value: sType}
				});
			};
			var fnExtractParameterProperties = function (oParameter, aParameters, iDepth, aPhoneName) {
				if (oParameter.parameterProperties) {
					Object.keys(oParameter.parameterProperties).forEach(function (sProperty) {
						var oProperty = oParameter.parameterProperties[sProperty];

						oProperty.depth = iDepth;

						// Handle types
						if (oProperty.type) {
							oProperty.types = fnCreateTypesArr(oProperty.type);
						}

						// Phone name - available only for parameters
						oProperty.phoneName = [aPhoneName.join("."), oProperty.name].join(".");

						// Add property to parameter array as we need a simple structure
						aParameters.push(oProperty);

						// Handle child parameterProperties
						fnExtractParameterProperties(oProperty, aParameters, (iDepth + 1), aPhoneName.concat([oProperty.name]));

						// Keep file size in check
						delete oProperty.type;
					});

					// Keep file size in check
					delete oParameter.parameterProperties;
				}
			};
			aMethods.forEach(function (oMethod) {
				// New array to hold modified parameters
				var aParameters = [];

				// Handle parameters
				if (oMethod.parameters) {
					oMethod.parameters.forEach(function (oParameter) {
						if (oParameter.type) {
							oParameter.types = fnCreateTypesArr(oParameter.type);
						}

						// Keep file size in check
						delete oParameter.type;

						// Add the parameter before the properties
						aParameters.push(oParameter);

						// Handle Parameter Properties
						// Note: We flatten the structure
						fnExtractParameterProperties(oParameter, aParameters, 1, [oParameter.name]);

					});

					// Override the old data
					oMethod.parameters = aParameters;
				}

				// Handle return values
				if (oMethod.returnValue && oMethod.returnValue.type) {
					// Handle types
					oMethod.returnValue.types = fnCreateTypesArr(oMethod.returnValue.type);
				}

			});
		}
571685
void optimizeReset() {
    FlatParagraphTools flatPara = new FlatParagraphTools(xContext);
    flatPara.markFlatParasAsChecked(resetFrom + divNum, resetTo + divNum, isChecked);
    resetCheck = false;
  }
257286
def save_model(self, net):
        
        if self.f_params is not None:
            f = self._format_target(net, self.f_params, -1)
            self._save_params(f, net, "f_params", "model parameters")

        if self.f_optimizer is not None:
            f = self._format_target(net, self.f_optimizer, -1)
            self._save_params(f, net, "f_optimizer", "optimizer state")

        if self.f_history is not None:
            f = self.f_history_
            self._save_params(f, net, "f_history", "history")

        if self.f_pickle:
            f_pickle = self._format_target(net, self.f_pickle, -1)
            with open_file_like(f_pickle, 'wb') as f:
                pickle.dump(net, f)
813204
def write_metadata(self, fp):
        
        fp.attrs['model'] = self.name
        fp.attrs['variable_params'] = list(self.variable_params)
        fp.attrs['sampling_params'] = list(self.sampling_params)
        fp.write_kwargs_to_attrs(fp.attrs, static_params=self.static_params)
131525
def _create_optimizer(self, X, y, status):
        """"""
        if self.optimizer is None:
            self.optimizer = 'avltree'

        times, ranks = y

        if self.optimizer == 'simple':
            optimizer = SimpleOptimizer(X, status, self.alpha, self.rank_ratio, timeit=self.timeit)
        elif self.optimizer == 'PRSVM':
            optimizer = PRSVMOptimizer(X, status, self.alpha, self.rank_ratio, timeit=self.timeit)
        elif self.optimizer == 'direct-count':
            optimizer = LargeScaleOptimizer(self.alpha, self.rank_ratio, self.fit_intercept,
                                            SurvivalCounter(X, ranks, status, len(ranks), times), timeit=self.timeit)
        elif self.optimizer == 'rbtree':
            optimizer = LargeScaleOptimizer(self.alpha, self.rank_ratio, self.fit_intercept,
                                            OrderStatisticTreeSurvivalCounter(X, ranks, status, RBTree, times),
                                            timeit=self.timeit)
        elif self.optimizer == 'avltree':
            optimizer = LargeScaleOptimizer(self.alpha, self.rank_ratio, self.fit_intercept,
                                            OrderStatisticTreeSurvivalCounter(X, ranks, status, AVLTree, times),
                                            timeit=self.timeit)
        else:
            raise ValueError('unknown optimizer: {0}'.format(self.optimizer))

        return optimizer
719254
protected void generateDefaultParameters(UseDefaultValues defValues){
      int count = defValues.optParamIndex().length;
      NativeType[] nt = defValues.nativeType();
      Variant.Type[] vt = defValues.variantType();
      String[] literal = defValues.literal();
      for (int i = 0; i < count; i++) {
        switch(nt[i]){
          case Bool:
          case VariantBool:
          case VariantBool_ByRef:
            defaultParameters[i] = Boolean.parseBoolean(literal[i]);
            break;
          case BSTR:
          case BSTR_ByRef:
          case CSTR:
          case Unicode:
            defaultParameters[i] = literal[i];
            break;
          case Double:
          case Double_ByRef:
            defaultParameters[i] = Double.parseDouble(literal[i]);
            break;
          case Float:
          case Float_ByRef:
            defaultParameters[i] = Float.parseFloat(literal[i]);
            break;
          case Int8:
          case Int8_ByRef:
            defaultParameters[i] = Byte.parseByte(literal[i]);
            break;
          case Int16:
          case Int16_ByRef:
            defaultParameters[i] = Short.parseShort(literal[i]);
            break;
          case Int32:
          case Int32_ByRef:
            defaultParameters[i] = Integer.parseInt(literal[i]);
            break;
          case Int64:
          case Int64_ByRef:
            defaultParameters[i] = Long.parseLong(literal[i]);
            break;
          case GUID:
            defaultParameters[i] = new GUID(literal[i]);
            break;
          case Currency:
          case Currency_ByRef:
            defaultParameters[i] = new BigDecimal(literal[i]);
            break;
          case VARIANT:
            Variant v = new Variant();
            switch(vt[i]){
              case VT_I1:
              case VT_UI1:
                v.set(Byte.parseByte(literal[i]));
                break;
              case VT_I2:
              case VT_UI2:
                v.set(Short.parseShort(literal[i]));
                break;
              case VT_I4:
              case VT_UI4:
              case VT_INT:
              case VT_UINT:
                v.set(Integer.parseInt(literal[i]));
                break;
              case VT_I8:
                v.set(Long.parseLong(literal[i]));
                break;
              case VT_R4:
                v.set(Float.parseFloat(literal[i]));
                break;
              case VT_R8:
                v.set(Double.parseDouble(literal[i]));
                break;
              case VT_BOOL:
                v.set(Boolean.parseBoolean(literal[i]));
                break;
              case VT_BSTR:
                v.set(literal[i]);
                break;
              case VT_EMPTY:
                v= new Variant();
                break;
              case VT_ERROR:
                v.makeError((int)Long.parseLong(literal[i], 16));
                break;
//              case VT_CY: ...
              default:
                throw new UnsupportedOperationException("Don't know how to parse literal " + literal[i] + " to an Java Object corresponding to Variant.Type." + vt[i].name());
            }
            v.setType(vt[i]);
            defaultParameters[i] = v;
            break;
          default:
            throw new UnsupportedOperationException("Don't know how to parse literal " + literal[i] + " to an Java Object corresponding to NativeType." + nt[i].name());
        }
      }
    }
52839
def _copy_params(self):
        
        cls = type(self)
        src_name_attrs = [(x, getattr(cls, x)) for x in dir(cls)]
        src_params = list(filter(lambda nameAttr: isinstance(nameAttr[1], Param), src_name_attrs))
        for name, param in src_params:
            setattr(self, name, param._copy_new_parent(self))
91672
def make_params(self):
    

    if self.needs_dummy_fprop:
      if hasattr(self, "_dummy_input"):
        return
      self._dummy_input = self.make_input_placeholder()
      self.fprop(self._dummy_input)
640977
def refine(pm, node, optimizations):
    
    # Sanitize input
    pm.apply(ExpandGlobals, node)
    pm.apply(ExpandImportAll, node)
    pm.apply(NormalizeTuples, node)
    pm.apply(ExpandBuiltins, node)
    pm.apply(ExpandImports, node)
    pm.apply(NormalizeMethodCalls, node)
    pm.apply(NormalizeIsNone, node)
    pm.apply(SplitStaticExpression, node)
    pm.apply(NormalizeStaticIf, node)
    pm.apply(NormalizeTuples, node)
    pm.apply(NormalizeException, node)
    pm.apply(NormalizeMethodCalls, node)

    # Some early optimizations
    pm.apply(ComprehensionPatterns, node)

    pm.apply(RemoveLambdas, node)
    pm.apply(RemoveNestedFunctions, node)
    pm.apply(NormalizeCompare, node)

    pm.gather(ExtendedSyntaxCheck, node)

    pm.apply(ListCompToGenexp, node)
    pm.apply(RemoveComprehension, node)
    pm.apply(RemoveNamedArguments, node)

    # sanitize input
    pm.apply(NormalizeReturn, node)
    pm.apply(UnshadowParameters, node)
    pm.apply(FalsePolymorphism, node)

    # some extra optimizations
    apply_optimisation = True
    while apply_optimisation:
        apply_optimisation = False
        for optimization in optimizations:
            apply_optimisation |= pm.apply(optimization, node)[0]
401205
def make_simulated_env_kwargs(real_env, hparams, **extra_kwargs):
  """"""
  objs_and_attrs = [
      (real_env, [
          "reward_range", "observation_space", "action_space", "frame_height",
          "frame_width"
      ]),
      (hparams, ["frame_stack_size", "intrinsic_reward_scale"])
  ]
  kwargs = {
      attr: getattr(obj, attr)  # pylint: disable=g-complex-comprehension
      for (obj, attrs) in objs_and_attrs for attr in attrs
  }
  kwargs["model_name"] = hparams.generative_model
  kwargs["model_hparams"] = trainer_lib.create_hparams(
      hparams.generative_model_params
  )
  if hparams.wm_policy_param_sharing:
    kwargs["model_hparams"].optimizer_zero_grads = True
  kwargs.update(extra_kwargs)
  return kwargs