repo_name
stringlengths
6
130
hexsha
list
file_path
list
code
list
apis
list
marcosfrenkel/PHYS-398
[ "323092b64b092c78d5c35acfd32d4a263dc00ea1" ]
[ "mls/variational.py" ]
[ "\"\"\"Variational inference utilities\nfor the UC Irvine course on 'ML & Statistics for Physicists'\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport scipy.stats\n\n\ndef calculate_KL(log_q, log_p, theta):\n \"\"\"Calculate the KL divergence of q wrt p for single-parameter PDFs.\n\n Uses the trapezoid rule for the numerical integration. Integrals are only\n calculated over the input theta range, so are not valid when p or q have\n significant mass outside this range.\n\n Regions where either PDF is zero are handled correctly, although an\n integrable singularity due to p=0 will result in a divergent KL because the\n inputs are tabulated.\n\n Parameters\n ----------\n log_q : array\n Values of log q(theta, s) tabulated on a grid with shape (ns, ntheta)\n of s (axis=0) and theta (axis=1).\n log_p : array\n Values of log p(theta) tabulated on a grid with shape (ntheta) of theta.\n theta : array\n Values of theta where log_q and log_p are tabulated.\n\n Returns\n -------\n tuple\n Tuple (KL, integrand) where KL is an array of ns divergence values and\n integrand is an array with shape (ns, ntheta) of KL integrands.\n \"\"\"\n # special handling for q=0.\n q_log_q = np.zeros_like(log_q)\n nonzero = log_q > -np.inf\n q_log_q[nonzero] = log_q[nonzero] * np.exp(log_q[nonzero])\n integrand = q_log_q - log_p * np.exp(log_q)\n return np.trapz(integrand, theta), integrand\n\n\ndef plot_KL(q, q_scale_range, p, p_scale, theta_range):\n \"\"\"Explanatory plots for the KL divergence.\n\n q and p are arbitrary PDFs defined in scipy.stats. q represents a\n family of PDFs by allowing its scale factor to vary in some range.\n The target pdf p uses a fixed scale factor.\n\n Parameters\n ----------\n q : str\n Name of a 1D continous random variable defined in scipy.stats.\n q_scale_range : list\n List [lo, hi] giving the range of scale factors to allow in defining the\n q family of PDFs.\n p : str\n Name of a 1D continous random variable defined in scipy.stats.\n p_scale : float\n Fixed scale factor to use for the target PDF p.\n theta_range : list\n List [lo, hi] giving the range to use for plotting and integration.\n \"\"\"\n q = getattr(scipy.stats, q)\n p = getattr(scipy.stats, p)\n\n theta = np.linspace(*theta_range, 251)\n log_p = p.logpdf(theta, scale=p_scale)\n assert np.all(np.isfinite(log_p))\n\n q_scale = np.linspace(*q_scale_range, 101)\n log_q = q.logpdf(theta, scale=q_scale[:, np.newaxis])\n\n KLs, KL_ints = calculate_KL(log_q, log_p, theta)\n ibest = np.argmin(KLs)\n\n fig = plt.figure(figsize=(12, 7))\n ax = [plt.subplot2grid((2,2), (0,0)), plt.subplot2grid((2,2), (1,0)),\n plt.subplot2grid((2,2), (0,1), rowspan=2)]\n cmap = sns.color_palette('bright', n_colors=1 + len(KLs)).as_hex()\n\n ax[0].plot(theta, np.exp(log_p), '-', lw=10, c=cmap[0],\n alpha=0.25, label='$p(\\\\theta)$')\n ax[0].axhline(0., color='gray', lw=1)\n ax[1].axhline(0., color='gray', lw=1)\n ax[2].axhline(0., color='gray', lw=1)\n ax[2].plot(q_scale, KLs, 'k-', label='KL$(q(s) \\parallel p)$')\n for i, idx in enumerate((0, ibest, -1)):\n c = cmap[i + 1]\n label = '$q(\\\\theta;s={:.2f})$'.format(q_scale[idx])\n ax[0].plot(theta, np.exp(log_q[idx]), '--', lw=2,\n alpha=1, c=c, label=label)\n ax[1].plot(theta, KL_ints[idx], '--', lw=2, alpha=1, c=c)\n ax[2].scatter(q_scale[idx], KLs[idx], lw=0, c=cmap[i + 1], s=150)\n ax[0].legend()\n ax[0].set_ylabel('$p(x), q(\\\\theta; s)$', fontsize='x-large')\n ax[0].set_xlim(*theta_range)\n ax[0].set_xticklabels([])\n ax[0].set_yticks([])\n ax[1].set_ylabel('KL$(q \\parallel p)$ integrand', fontsize='x-large')\n ax[1].set_xlim(*theta_range)\n ax[1].set_xlabel('$\\\\theta$', fontsize='large')\n ax[1].set_yticks([])\n ax[2].set_xlabel('$q(\\\\theta;s)$ scale $s$', fontsize='large')\n ax[2].legend(loc='upper center', fontsize='x-large')\n plt.subplots_adjust(left=0.05, hspace=0.05, wspace=0.1)\n\n\ndef calculate_ELBO(log_q, log_likelihood, log_prior, theta):\n \"\"\"Calculate the ELBO of q for single-parameter PDFs.\n \"\"\"\n KLqP, integrand = calculate_KL(log_q, log_prior, theta)\n integrand = np.exp(log_q) * log_likelihood - integrand\n return np.trapz(integrand, theta), integrand\n\n\ndef plot_ELBO(q, q_scale_range, likelihood, prior, theta_range, n_data, seed=123):\n \"\"\"Explanatory plots for the evidence lower bound (ELBO).\n\n Data is modeled with a single offset (loc) parameter theta with an arbitrary\n likelihood and prior. A random sample of generated data is used to calculate\n the posterior, which is approximated by adjusting the scale parameter of\n the arbitrary PDF family q.\n\n Parameters\n ----------\n q : str\n Name of a 1D continous random variable defined in scipy.stats.\n q_scale_range : list\n List [lo, hi] giving the range of scale factors to allow in defining the\n q family of PDFs.\n likelihood : str\n Name of a 1D continous random variable defined in scipy.stats.\n prior : str\n Name of a 1D continous random variable defined in scipy.stats.\n theta_range : list\n List [lo, hi] giving the range to use for plotting and integration.\n The true value of theta used to generate data is (lo + hi) / 2.\n n_data : int\n Number of data points to generate by sampling from the likelihood with\n theta = theta_true.\n seed : int\n Random number seed to use for reproducible results.\n \"\"\"\n q = getattr(scipy.stats, q)\n likelihood = getattr(scipy.stats, likelihood)\n prior = getattr(scipy.stats, prior)\n\n # Generate random data using the midpoint of the theta range as the\n # true value of theta for sampling the likelihood.\n theta = np.linspace(*theta_range, 251)\n theta_true = 0.5 * (theta[0] + theta[-1])\n D = likelihood.rvs(\n loc=theta_true, size=n_data,\n random_state=np.random.RandomState(seed=seed))\n\n # Calculate the likelihood and prior for each theta.\n log_L = likelihood.logpdf(D, loc=theta[:, np.newaxis]).sum(axis=1)\n log_P = prior.logpdf(theta)\n\n # Calculate the evidence and posterior.\n log_post = log_L + log_P\n log_evidence = np.log(np.trapz(np.exp(log_post), theta))\n log_post -= log_evidence\n assert np.all(np.isfinite(log_post))\n\n q_scale = np.linspace(*q_scale_range, 101)\n log_q = q.logpdf(theta, scale=q_scale[:, np.newaxis])\n\n KLs, KL_ints = calculate_KL(log_q, log_post, theta)\n ibest = np.argmin(KLs)\n\n ELBOs, ELBO_ints = calculate_ELBO(log_q, log_L, log_P, theta)\n\n fig = plt.figure(figsize=(12, 8))\n ax = [plt.subplot2grid((2,2), (0,0)), plt.subplot2grid((2,2), (1,0)),\n plt.subplot2grid((2,2), (0,1)), plt.subplot2grid((2,2), (1,1))]\n cmap = sns.color_palette('bright', n_colors=1 + len(KLs)).as_hex()\n\n ax[0].plot(theta, np.exp(log_post), '-', lw=10, c=cmap[0],\n alpha=0.25, label='$P(\\\\theta\\mid D)$')\n ax[0].axhline(0., color='gray', lw=1)\n ax[1].axhline(0., color='gray', lw=1)\n ax[2].axhline(0., color='gray', lw=1)\n ax[2].plot(q_scale, KLs, 'k-', label='KL$(q(s) \\parallel p)$')\n ax[2].plot(q_scale, log_evidence - ELBOs, 'k:', lw=6,\n alpha=0.5, label='$\\log P(D) - ELBO(q(s))$')\n for i, idx in enumerate((0, ibest, -1)):\n c = cmap[i + 1]\n label = '$q(\\\\theta;s={:.2f})$'.format(q_scale[idx])\n ax[0].plot(theta, np.exp(log_q[idx]), '--', lw=2,\n alpha=1, c=c, label=label)\n ax[1].plot(theta, KL_ints[idx], '--', lw=2, alpha=1, c=c)\n ax[2].scatter(q_scale[idx], KLs[idx], lw=0, c=c, s=150)\n ax[0].legend()\n ax[0].set_ylabel('$p(x), q(\\\\theta; s)$', fontsize='x-large')\n ax[0].set_xlim(*theta_range)\n ax[0].set_xlabel('Model parameter $\\\\theta$', fontsize='large')\n ax[0].set_yticks([])\n ax[1].set_ylabel('KL$(q \\parallel p)$ integrand', fontsize='x-large')\n ax[1].set_xlim(*theta_range)\n ax[1].set_xlabel('Model parameter $\\\\theta$', fontsize='large')\n ax[1].set_yticks([])\n ax[2].set_xlabel('$q(\\\\theta;s)$ scale $s$', fontsize='large')\n ax[2].legend(loc='upper center', fontsize='x-large')\n\n x_lim = 1.1 * np.max(np.abs(D))\n ax[3].hist(D, normed=True, range=(-x_lim, +x_lim), histtype='stepfilled')\n x = np.linspace(-x_lim, +x_lim, 250)\n dtheta = 0.25 * (theta[-1] - theta[0])\n for theta, ls in zip(\n (theta_true - dtheta, theta_true, theta_true + dtheta),\n ('--', '-', ':')):\n label = '$P(x\\mid \\\\theta={:+.2f})$'.format(theta)\n ax[3].plot(x, likelihood.pdf(x, loc=theta), 'k', ls=ls, label=label)\n ax[3].set_xlabel('Observed sample $x$')\n ax[3].set_xlim(-x_lim, +x_lim)\n ax[3].legend()\n\n plt.subplots_adjust(\n left=0.05, right=0.95, hspace=0.25, wspace=0.15, top=0.95)\n fig.suptitle(\n '$\\\\theta_{\\text{true}}' + ' = {:.2f}$ , $\\log P(D) = {:.1f}$'\n .format(theta_true, log_evidence), fontsize='large')\n" ]
[ [ "numpy.zeros_like", "numpy.argmin", "numpy.random.RandomState", "numpy.exp", "matplotlib.pyplot.figure", "numpy.trapz", "numpy.isfinite", "matplotlib.pyplot.subplot2grid", "numpy.abs", "numpy.linspace", "matplotlib.pyplot.subplots_adjust" ] ]
pplonski/my_ml_service_old
[ "00f5e4104a0f763af06f57cbe857b668d5a00dc6" ]
[ "backend/server/apps/ml/income_classifier/random_forest.py" ]
[ "import joblib\nimport pandas as pd\n\nclass RandomForestClassifier:\n def __init__(self):\n path_to_artifacts = \"../../research/\" \n self.values_fill_missing = joblib.load(path_to_artifacts + \"train_mode.joblib\")\n self.encoders = joblib.load(path_to_artifacts + \"encoders.joblib\")\n self.model = joblib.load(path_to_artifacts + \"random_forest.joblib\")\n\n def preprocessing(self, input_data):\n # JSON to pandas DataFrame\n input_data = pd.DataFrame(input_data, index=[0])\n # fill missing values\n input_data.fillna(self.values_fill_missing)\n # convert categoricals\n for column in [\n \"workclass\",\n \"education\",\n \"marital-status\",\n \"occupation\",\n \"relationship\",\n \"race\",\n \"sex\",\n \"native-country\",\n ]:\n categorical_convert = self.encoders[column]\n input_data[column] = categorical_convert.transform(input_data[column])\n\n return input_data\n\n def predict(self, input_data):\n return self.model.predict_proba(input_data)\n\n def postprocessing(self, input_data):\n label = \"<=50K\"\n if input_data[1] > 0.5:\n label = \">50K\"\n return {\"probability\": input_data[1], \"label\": label, \"status\": \"OK\"}\n\n def compute_prediction(self, input_data):\n try:\n input_data = self.preprocessing(input_data)\n prediction = self.predict(input_data)[0] # only one sample\n prediction = self.postprocessing(prediction)\n except Exception as e:\n return {\"status\": \"Error\", \"message\": str(e)}\n\n return prediction" ]
[ [ "pandas.DataFrame" ] ]
learningmatter-mit/GLAMOUR
[ "a283025fb38192fd49909ab21e35337cb5488867" ]
[ "utils/macro_unsupervised.py" ]
[ "import os\nimport grakel\nimport matplotlib.pyplot as plt\nimport networkx as nx\nimport numpy as np\nimport pandas as pd\nfrom scipy.spatial import distance\nfrom sklearn import decomposition, manifold\nimport umap.umap_ as umap\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\ndef edit_distance(graph1, graph2, node_attr='h', edge_attr='e', upper_bound=100, indel_mul=3, sub_mul=3):\n \"\"\"\n Calculates exact graph edit distance between 2 graphs.\n\n Args:\n graph1 : networkx graph, graph with node and edge attributes \n graph2 : networkx graph, graph with node and edge attributes \n node_attr : str, key for node attribute\n edge_attr : str, key for edge attribute\n upper_bound : int, maximum edit distance to consider\n indel_mul: float, insertion/deletion cost\n sub_mul: float, substitution cost\n\n Returns:\n np.float, distance, how similar graph1 is to graph2\n \"\"\"\n def node_substitution_scoring(dict_1, dict_2):\n \"\"\"Calculates node substitution score.\"\"\"\n multiplier = sub_mul if distance.rogerstanimoto(\n dict_1[node_attr], dict_2[node_attr]) != 0 else 0\n return multiplier*(1 - distance.rogerstanimoto(\n dict_1[node_attr], dict_2[node_attr]))\n\n def edge_substitution_scoring(dict_1, dict_2):\n \"\"\"Calculates edge substitution score.\"\"\"\n multiplier = sub_mul if distance.rogerstanimoto(\n dict_1[edge_attr], dict_2[edge_attr]) != 0 else 0\n return multiplier*(1 - distance.rogerstanimoto(\n dict_1[edge_attr], dict_2[edge_attr]))\n \n def constant_value(dict_1):\n \"\"\"Returns constant score for insertion/deletion.\"\"\"\n return indel_mul\n\n graph1 = feature_conversion(graph1, node_attr, edge_attr)\n graph2 = feature_conversion(graph2, node_attr, edge_attr)\n\n return min(\n nx.optimize_graph_edit_distance(\n graph1, graph2, \n node_subst_cost = node_substitution_scoring,\n edge_subst_cost = edge_substitution_scoring,\n upper_bound = upper_bound,\n node_del_cost = constant_value, \n node_ins_cost = constant_value, \n edge_del_cost = constant_value, \n edge_ins_cost = constant_value, \n ))\n\ndef feature_conversion(graph, node_attr, edge_attr):\n \"\"\"Converts networkx graph features from tensors to np array.\"\"\"\n for node in graph.nodes:\n graph.nodes[node][node_attr] = np.array(graph.nodes[node][node_attr])\n for edge in graph.edges:\n graph.edges[edge][edge_attr] = np.array(graph.edges[edge][edge_attr])\n return graph\n\ndef similarity_matrix(dict_graphs, method='kernel', **kwargs):\n \"\"\"\n Calculates an (n x n) similarity matrix for a dictionary of macromolecule networkx graphs.\n \n Args:\n dict_graphs : dict, dictionary of networkx graphs, key: graph_id, value: networkx graph object\n method : str, similarity matrix calculation method - 'kernel' or 'exact_distance'\n **kwargs : optional arguments for similarity matrix method\n\n Returns:\n matrix : np array, n x n similarity matrix\n \"\"\"\n\n node_attr = 'h' if 'node_attr' not in kwargs else kwargs['node_attr']\n edge_attr = 'e' if 'edge_attr' not in kwargs else kwargs['edge_attr']\n upper_bound = 100 if 'upper_bound' not in kwargs else kwargs['upper_bound']\n\n list_graphs = [feature_conversion(\n graph, node_attr, edge_attr) for graph in list(dict_graphs.values())]\n\n if method == 'kernel':\n grakel_graphs = grakel.graph_from_networkx(\n list_graphs, node_labels_tag=node_attr, edge_labels_tag=edge_attr)\n gk = grakel.PropagationAttr(\n n_jobs=-1 if 'n_jobs' not in kwargs else kwargs['n_jobs'], \n t_max=upper_bound, \n random_state=108 if 'random_state' not in kwargs else kwargs['random_state'],)\n return gk.fit_transform(grakel_graphs)\n\n elif method == 'exact_distance':\n matrix = np.zeros((len(list_graphs), len(list_graphs)))\n for idx_ref, ref_graph in enumerate(list_graphs):\n for idx_seq, tmp_graph in enumerate(list_graphs):\n if idx_ref >= idx_seq:\n distance = edit_distance(\n ref_graph, tmp_graph, node_attr, edge_attr, upper_bound)\n matrix[idx_ref, idx_seq] = distance\n matrix[idx_seq, idx_ref] = distance\n\n return matrix\n\ndef edit_distance(graph1, graph2, node_attr, edge_attr, upper_bound):\n \"\"\"\n Calculates exact graph edit distance between 2 graphs.\n\n Args:\n graph1 : networkx graph, graph with node and edge attributes \n graph2 : networkx graph, graph with node and edge attributes \n node_attr : str, key for node attribute\n edge_attr : str, key for edge attribute\n upper_bound : int, maximum edit distance to consider\n\n Returns:\n np.float, distance, how similar graph1 is to graph2\n \"\"\"\n def node_substitution_scoring(dict_1, dict_2):\n return 1 - distance.rogerstanimoto(\n dict_1[node_attr], dict_2[node_attr])\n\n def edge_substitution_scoring(dict_1, dict_2):\n return 1 - distance.rogerstanimoto(\n dict_1[edge_attr], dict_2[edge_attr])\n \n def constant_value(dict_1):\n return 5\n\n graph1 = feature_conversion(graph1, node_attr, edge_attr)\n graph2 = feature_conversion(graph2, node_attr, edge_attr)\n\n return min(\n nx.optimize_graph_edit_distance(\n graph1, graph2, \n node_subst_cost = node_substitution_scoring,\n edge_subst_cost = edge_substitution_scoring,\n upper_bound = upper_bound,\n node_del_cost = constant_value, \n node_ins_cost = constant_value, \n edge_del_cost = constant_value, \n edge_ins_cost = constant_value, \n ))\n\ndef dimensionality_reduction(matrix, method, **kwargs):\n \"\"\"\n Reduces dimensionality of similarity matrix.\n\n Args:\n matrix : np array, similarity matrix\n method : str, method of dimensionality reduction\n **kwargs : optional arguments for dimensionality reduction method\n\n Returns:\n embedding : np array, (n_samples, n_components) after the dimensionality reduction\n \"\"\"\n if method == 'umap':\n reducer = umap.UMAP(\n n_components=2 if 'n_components' not in kwargs else kwargs['n_components'], \n n_neighbors=4 if 'n_neighbors' not in kwargs else kwargs['n_neighbors'], \n random_state=108 if 'random_state' not in kwargs else kwargs['random_state'], \n metric = 'precomputed' if 'metric' not in kwargs else kwargs['metric'])\n\n elif method == 'tsne':\n reducer = manifold.TSNE(\n n_components=2 if 'n_components' not in kwargs else kwargs['n_components'], \n perplexity=10 if 'perplexity' not in kwargs else kwargs['perplexity'], \n n_iter=1000 if 'n_iter' not in kwargs else kwargs['n_iter'],\n n_jobs=-1 if 'n_jobs' not in kwargs else kwargs['n_jobs'], \n random_state=108 if 'random_state' not in kwargs else kwargs['random_state'],)\n return reducer.fit_transform(matrix)\n\ndef plot_embeddings(embeddings, NX_GRAPHS, DF_PATH, method):\n \"\"\"\n Plots 2D component embeddings obtained from dimensionality reduction.\n\n Args:\n embeddings : np array, (n_samples, n_components) after the dimensionality reduction\n NX_GRAPHS : dict, dictionary of networkx graphs, key: graph_id, value: networkx graph object\n DF_PATH : str, path of dataframe with labels\n method : str, method for xlabel, ylabel\n \"\"\"\n df = pd.read_csv(DF_PATH)\n immunogenic_idx = []\n non_immunogenic_idx = []\n colors = []\n\n for idx, graph_id in enumerate(NX_GRAPHS):\n if df[df.ID == graph_id]['Immunogenic'].tolist()[0] == 'Yes':\n immunogenic_idx.append(idx)\n colors.append('#B12122')\n else:\n non_immunogenic_idx.append(idx)\n colors.append('#2C7FFF')\n colors = np.array(colors)\n\n fig = plt.figure()\n plt.scatter(\n embeddings[:, 0][immunogenic_idx],\n embeddings[:, 1][immunogenic_idx],\n s = 100,\n c = colors[immunogenic_idx],\n alpha = 0.5,\n label = 'Immunogenic')\n plt.scatter(\n embeddings[:, 0][non_immunogenic_idx],\n embeddings[:, 1][non_immunogenic_idx],\n s = 100,\n c = colors[non_immunogenic_idx],\n alpha = 0.5,\n label = 'Non-Immunogenic')\n plt.xticks(fontsize=18)\n plt.yticks(fontsize=18)\n plt.legend(markerscale = 1, fontsize=12, \n borderpad=0.2, labelspacing=0.2, handletextpad=0.2, handlelength=1)\n plt.locator_params(nbins=5)\n plt.xlabel(method + ' C$\\mathregular{_1}$', fontsize=20)\n plt.ylabel(method + ' C$\\mathregular{_2}$', fontsize=20)\n plt.show()\n" ]
[ [ "numpy.array", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.legend", "matplotlib.pyplot.locator_params", "matplotlib.pyplot.yticks", "matplotlib.pyplot.figure", "sklearn.manifold.TSNE", "matplotlib.pyplot.show", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.scatter", "pandas.read_csv", "matplotlib.pyplot.xticks" ] ]
mtasende/disaster-response
[ "fed024d77ad9ab4cf409e8f65659ed8d4d95c007" ]
[ "models/train_classifier.py" ]
[ "import sys\nfrom sklearn.model_selection import train_test_split\n# from models.model import Model\nfrom models.model_004_xgboost_gridsearch import Model004\nfrom time import time\n\ncurrent_model = Model004() # Change this to use another model\n\n\ndef load_data(database_filepath):\n \"\"\" Wrapper function. \"\"\"\n return current_model.load_data(database_filepath)\n\n\ndef build_model():\n \"\"\" Wrapper function. \"\"\"\n return current_model.build_model()\n\n\ndef tune_params(model, X_train, Y_train):\n \"\"\" Wrapper function. \"\"\"\n return current_model.tune_params(X_train, Y_train)\n\n\ndef evaluate_model(model, X_test, Y_test, category_names):\n \"\"\" Wrapper function. \"\"\"\n current_model.evaluate_model(model, X_test, Y_test, category_names)\n\n\ndef save_model(model, model_filepath):\n \"\"\" Wrapper function. \"\"\"\n current_model.save_model(model, model_filepath)\n\n\ndef main():\n if len(sys.argv) == 3:\n database_filepath, model_filepath = sys.argv[1:]\n print('Loading data...\\n DATABASE: {}'.format(database_filepath))\n X, Y, category_names = load_data(database_filepath)\n X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2)\n\n print('Building model...')\n model = build_model()\n\n print('Hyperparameter Tuning.')\n print('-'*120)\n print('WARNING: THIS PROCESS TAKES ABOUT 1 HOUR OR EVEN MORE...')\n print('-' * 120)\n tic = time()\n model = tune_params(model, X_train, Y_train)\n toc = time()\n print('Hyperparameter tuning time: {} seconds'.format(toc - tic))\n\n print('Training model...')\n tic = time()\n model.fit(X_train, Y_train)\n toc = time()\n print('Training time: {} seconds'.format(toc - tic))\n\n print('Evaluating model...')\n tic = time()\n evaluate_model(model, X_test, Y_test, category_names)\n toc = time()\n print('Evaluation time: {} seconds'.format(toc - tic))\n\n print('Saving model...\\n MODEL: {}'.format(model_filepath))\n save_model(model, model_filepath)\n\n print('Trained model saved!')\n\n else:\n print('Please provide the filepath of the disaster messages database '\\\n 'as the first argument and the filepath of the pickle file to '\\\n 'save the model to as the second argument. \\n\\nExample: python '\\\n 'train_classifier.py ../data/DisasterResponse.db classifier.pkl')\n\n\nif __name__ == '__main__':\n main()\n" ]
[ [ "sklearn.model_selection.train_test_split" ] ]
elerac/polanalyser
[ "801c6ed71d635dfc20e1514f76408133956c8d9d" ]
[ "documents/create_AoLP_wheel.py" ]
[ "\"\"\"\nCreate a color map of the AoLP\n\"\"\"\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport cv2\n\ndef plot_hsv_wheel(filename, is_saturation=False, is_value=False, DoLP_tick=False, dpi=300):\n \"\"\"\n Plot HSV wheel\n\n H : AoLP\n S : DoLP or constant value\n V : DoLP or constant value\n \n reference: https://salad-bowl-of-knowledge.github.io/hp/python/2020/01/13/cieluv.html\n \"\"\"\n def func(r_norm, theta_norm, c, is_saturation=False, is_value=False):\n \"\"\"\n Function for HSV mapping\n \"\"\"\n # Calcukate AoLP and DoLP\n AoLP = np.mod(theta_norm*358, 179)\n DoLP = r_norm*255\n # Hue and Saturation and Value\n hue = AoLP\n saturation = DoLP*is_saturation + 255*(1-is_saturation)\n value = DoLP*is_value + 255*(1-is_value)\n return hue*(c==0) + saturation*(c==1) + value*(c==2)\n \n N_theta = 1000\n N_r = 256\n\n hsv = np.fromfunction(lambda r,theta,c: func(r/(N_r-1), theta/(N_theta-1), c, is_saturation, is_value), (N_r, N_theta, 3), dtype=np.float64).astype(np.uint8)\n\n rgb = cv2.cvtColor(hsv, cv2.COLOR_HSV2RGB)/255.0\n\n # hue wheel plot\n ax = plt.subplot(111, polar=True)\n if DoLP_tick:\n ax.set_yticks([0, 0.5, 1])\n else:\n ax.set_yticks([])\n \n #get coordinates:\n theta = np.linspace(0, 2*np.pi, rgb.shape[1]+1)\n r = np.linspace(0, 1, rgb.shape[0]+1)\n Theta,R = np.meshgrid(theta, r)\n \n # get color\n color = rgb.reshape((rgb.shape[0]*rgb.shape[1], rgb.shape[2]))\n m = plt.pcolormesh(Theta, R, rgb[:,:,0], color=color, linewidth=0)\n\n # This is necessary to let the `color` argument determine the color\n m.set_array(None)\n plt.savefig(filename, bbox_inches='tight', dpi=dpi)\n\n plt.close('all')\n\ndef main():\n print(\"AoLP(Hue) Color Map\")\n plot_hsv_wheel(\"AoLP_wheel.jpg\")\n\n print(\"AoLP(Hue)+DoLP(Saturation) Color Map\")\n plot_hsv_wheel(\"AoLP_wheel_saturation.jpg\", is_saturation=True, DoLP_tick=True)\n\n print(\"AoLP(Hue)+DoLP(Value) Color Map\")\n plot_hsv_wheel(\"AoLP_wheel_value.jpg\", is_value=True, DoLP_tick=True)\n\nif __name__==\"__main__\":\n main()\n" ]
[ [ "matplotlib.pyplot.pcolormesh", "matplotlib.pyplot.savefig", "matplotlib.pyplot.close", "numpy.linspace", "numpy.meshgrid", "numpy.mod", "matplotlib.pyplot.subplot" ] ]
SEDSIIT/performance-calculators
[ "1d6d490d44fb3517d10198c33eb979fe593b1aa9" ]
[ "Performance_Estimator/drag.py" ]
[ "'''\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n#############################################################################\nThese drag equations were heavily inspired by the OpenRocket technical documentation\nlink to documentation: http://openrocket.sourceforge.net/techdoc.pdf\n#############################################################################\n'''\nimport numpy as np\n\n\ndef drag_nosecone (vehicle, air_properties, velocity): # to do\n dynamic_pressure = 0.5 * air_properties.density * velocity**2\n mach = velocity / air_properties.speed_of_sound\n cone_angle = (90*np.pi/180) - np.arctan(vehicle.nosecone.height / (vehicle.nosecone.diameter/2))\n Cd0 = 0.8 * (np.sin(cone_angle))**2 # 3.86\n a, b = 0.01 # <--------------------- -----------Need to find what these are\n Cd = a * mach**b + Cd0 # 3.87\n drag = Cd * dynamic_pressure * vehicle.nosecone.reference_area\n return drag\n\ndef drag_skinfriction (vehicle, velocity, mach, density, Re): # (done?)\n R_crit = 51 * (vehicle.surface_roughness / vehicle.length)**(-1.039)\n\n # Calculating skin friction coefficient (3.81)\n if (Re > R_crit):\n C_f = 0.032 * (vehicle.surface_roughness / vehicle.length)**0.2\n elif(Re > 1e4 and Re <= R_crit):\n C_f = 1 / (1.50 * np.log(Re) - 5.6)**2\n else:\n C_f = 1.48 * 10**-2\n\n # Compressibility corrections\n C_f_roughness = C_f / (1 + 0.18 * mach**2)\n if (mach > 1):\n C_f = C_f / (1 + 0.15 * mach**2)**0.58 # 3.83\n else:\n C_f = C_f * (1 - 0.1 * mach**2) # 3.82\n if (C_f_roughness > C_f): # 3.84 Check if roughness limited\n C_f = C_f_roughness\n '''\n if (flags.booster_seperation == False):\n wetted_area = vehicle.wetted_area_staged\n else:\n wetted_area = vehicle.wetted_area\n '''\n wetted_area = vehicle.wetted_area\n drag = 0.5 * C_f * density * (velocity**2) * wetted_area\n return drag\n\ndef drag_boattail(vehicle, Cd_base):\n length_to_height_ratio = vehicle.boattail.height / (vehicle.boattail.diameter_top - vehicle.boattail.diameter_bottom)\n if (length_to_height_ratio <= 1):\n gamma = 1\n elif (length_to_height_ratio > 3 and length_to_height_ratio < 1):\n gamma = (3 - length_to_height_ratio) / 2\n else:\n gamma = 0\n # 3.88\n Cd_boattail = ((np.pi * vehicle.boattail.diameter_top**2) / (np.pi * vehicle.boattail.diameter_top**2)) * gamma\n return Cd_boattail\n\ndef drag_base (vehicle, mach, dynamic_pressure):\n if (mach < 1): # 3.94\n Cd = 0.12 + 0.13*mach**2\n else:\n Cd = 0.25 / mach\n '''\n if (flags.booster_seperation == True):\n pass\n else:\n pass\n '''\n return Cd\n\ndef drag_fin (mach): # Assumes rounded profile (for now)\n # 3.89\n if (mach < 0.9):\n Cd_le = (1 - mach**2)**-0.147 - 1\n elif (0.9 < mach and mach < 1):\n Cd_le = 1 - 1.785 * (mach - 0.9)\n else:\n Cd_le = 1.214 - (0.502 / mach**2) + (0.1095 / mach**4)\n # 3.92 / 3.94\n if (mach < 1):\n Cd_te = 0.12 + 0.13 * mach**2\n else:\n Cd_te = 0.25 / mach\n\n Cd = Cd_le + Cd_te # 3.93\n\n return Cd\n\ndef drag_parasitic (): # to do \n Cd = 1\n return Cd\n\ndef total_drag (vehicle, flags, air_properties, velocity, Re): # to do \n mach = velocity / air_properties.speed_of_sound\n dynamic_pressure = 0.5 * air_properties.density * velocity**2\n density = air_properties.density\n skin_drag = drag_skinfriction(vehicle, velocity, mach, density, Re)\n \n drag_force = skin_drag #+ drag_base + drag_fin + drag_nosecone\n return drag_force # Newtons" ]
[ [ "numpy.sin", "numpy.arctan", "numpy.log" ] ]
sneakers-the-rat/pyqtgraph
[ "65ef2a5a60a1a08d0106e819110528b2ca3499a3" ]
[ "pyqtgraph/widgets/TableWidget.py" ]
[ "# -*- coding: utf-8 -*-\nimport numpy as np\nfrom ..Qt import QtGui, QtCore\nfrom ..python2_3 import asUnicode, basestring\nfrom .. import metaarray\n\n\n__all__ = ['TableWidget']\n\n\ndef _defersort(fn):\n def defersort(self, *args, **kwds):\n # may be called recursively; only the first call needs to block sorting\n setSorting = False\n if self._sorting is None:\n self._sorting = self.isSortingEnabled()\n setSorting = True\n self.setSortingEnabled(False)\n try:\n return fn(self, *args, **kwds)\n finally:\n if setSorting:\n self.setSortingEnabled(self._sorting)\n self._sorting = None\n \n return defersort\n\n\nclass TableWidget(QtGui.QTableWidget):\n \"\"\"Extends QTableWidget with some useful functions for automatic data handling\n and copy / export context menu. Can automatically format and display a variety\n of data types (see :func:`setData() <pyqtgraph.TableWidget.setData>` for more\n information.\n \"\"\"\n \n def __init__(self, *args, **kwds):\n \"\"\"\n All positional arguments are passed to QTableWidget.__init__().\n \n ===================== =================================================\n **Keyword Arguments**\n editable (bool) If True, cells in the table can be edited\n by the user. Default is False.\n sortable (bool) If True, the table may be soted by\n clicking on column headers. Note that this also\n causes rows to appear initially shuffled until\n a sort column is selected. Default is True.\n *(added in version 0.9.9)*\n ===================== =================================================\n \"\"\"\n \n QtGui.QTableWidget.__init__(self, *args)\n \n self.itemClass = TableWidgetItem\n \n self.setVerticalScrollMode(self.ScrollPerPixel)\n self.setSelectionMode(QtGui.QAbstractItemView.ContiguousSelection)\n self.setSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred)\n self.clear()\n \n kwds.setdefault('sortable', True)\n kwds.setdefault('editable', False)\n self.setEditable(kwds.pop('editable'))\n self.setSortingEnabled(kwds.pop('sortable'))\n \n if len(kwds) > 0:\n raise TypeError(\"Invalid keyword arguments '%s'\" % kwds.keys())\n \n self._sorting = None # used when temporarily disabling sorting\n \n self._formats = {None: None} # stores per-column formats and entire table format\n self.sortModes = {} # stores per-column sort mode\n \n self.itemChanged.connect(self.handleItemChanged)\n \n self.contextMenu = QtGui.QMenu()\n self.contextMenu.addAction('Copy Selection').triggered.connect(self.copySel)\n self.contextMenu.addAction('Copy All').triggered.connect(self.copyAll)\n self.contextMenu.addAction('Save Selection').triggered.connect(self.saveSel)\n self.contextMenu.addAction('Save All').triggered.connect(self.saveAll)\n \n def clear(self):\n \"\"\"Clear all contents from the table.\"\"\"\n QtGui.QTableWidget.clear(self)\n self.verticalHeadersSet = False\n self.horizontalHeadersSet = False\n self.items = []\n self.setRowCount(0)\n self.setColumnCount(0)\n self.sortModes = {}\n \n def setData(self, data):\n \"\"\"Set the data displayed in the table.\n Allowed formats are:\n \n * numpy arrays\n * numpy record arrays \n * metaarrays\n * list-of-lists [[1,2,3], [4,5,6]]\n * dict-of-lists {'x': [1,2,3], 'y': [4,5,6]}\n * list-of-dicts [{'x': 1, 'y': 4}, {'x': 2, 'y': 5}, ...]\n \"\"\"\n self.clear()\n self.appendData(data)\n self.resizeColumnsToContents()\n \n @_defersort\n def appendData(self, data):\n \"\"\"\n Add new rows to the table.\n \n See :func:`setData() <pyqtgraph.TableWidget.setData>` for accepted\n data types.\n \"\"\"\n startRow = self.rowCount()\n \n fn0, header0 = self.iteratorFn(data)\n if fn0 is None:\n self.clear()\n return\n it0 = fn0(data)\n try:\n first = next(it0)\n except StopIteration:\n return\n fn1, header1 = self.iteratorFn(first)\n if fn1 is None:\n self.clear()\n return\n \n firstVals = [x for x in fn1(first)]\n self.setColumnCount(len(firstVals))\n \n if not self.verticalHeadersSet and header0 is not None:\n labels = [self.verticalHeaderItem(i).text() for i in range(self.rowCount())]\n self.setRowCount(startRow + len(header0))\n self.setVerticalHeaderLabels(labels + header0)\n self.verticalHeadersSet = True\n if not self.horizontalHeadersSet and header1 is not None:\n self.setHorizontalHeaderLabels(header1)\n self.horizontalHeadersSet = True\n \n i = startRow\n self.setRow(i, firstVals)\n for row in it0:\n i += 1\n self.setRow(i, [x for x in fn1(row)])\n \n if (self._sorting and self.horizontalHeadersSet and \n self.horizontalHeader().sortIndicatorSection() >= self.columnCount()):\n self.sortByColumn(0, QtCore.Qt.AscendingOrder)\n \n def setEditable(self, editable=True):\n self.editable = editable\n for item in self.items:\n item.setEditable(editable)\n \n def setFormat(self, format, column=None):\n \"\"\"\n Specify the default text formatting for the entire table, or for a\n single column if *column* is specified.\n \n If a string is specified, it is used as a format string for converting\n float values (and all other types are converted using str). If a \n function is specified, it will be called with the item as its only\n argument and must return a string. Setting format = None causes the \n default formatter to be used instead.\n \n Added in version 0.9.9.\n \n \"\"\"\n if format is not None and not isinstance(format, basestring) and not callable(format):\n raise ValueError(\"Format argument must string, callable, or None. (got %s)\" % format)\n \n self._formats[column] = format\n \n \n if column is None:\n # update format of all items that do not have a column format \n # specified\n for c in range(self.columnCount()):\n if self._formats.get(c, None) is None:\n for r in range(self.rowCount()):\n item = self.item(r, c)\n if item is None:\n continue\n item.setFormat(format)\n else:\n # set all items in the column to use this format, or the default \n # table format if None was specified.\n if format is None:\n format = self._formats[None]\n for r in range(self.rowCount()):\n item = self.item(r, column)\n if item is None:\n continue\n item.setFormat(format)\n \n \n def iteratorFn(self, data):\n ## Return 1) a function that will provide an iterator for data and 2) a list of header strings\n if isinstance(data, list) or isinstance(data, tuple):\n return lambda d: d.__iter__(), None\n elif isinstance(data, dict):\n return lambda d: iter(d.values()), list(map(asUnicode, data.keys()))\n elif (hasattr(data, 'implements') and data.implements('MetaArray')):\n if data.axisHasColumns(0):\n header = [asUnicode(data.columnName(0, i)) for i in range(data.shape[0])]\n elif data.axisHasValues(0):\n header = list(map(asUnicode, data.xvals(0)))\n else:\n header = None\n return self.iterFirstAxis, header\n elif isinstance(data, np.ndarray):\n return self.iterFirstAxis, None\n elif isinstance(data, np.void):\n return self.iterate, list(map(asUnicode, data.dtype.names))\n elif data is None:\n return (None,None)\n elif np.isscalar(data):\n return self.iterateScalar, None\n else:\n msg = \"Don't know how to iterate over data type: {!s}\".format(type(data))\n raise TypeError(msg)\n \n def iterFirstAxis(self, data):\n for i in range(data.shape[0]):\n yield data[i]\n \n def iterate(self, data):\n # for numpy.void, which can be iterated but mysteriously \n # has no __iter__ (??)\n for x in data:\n yield x\n \n def iterateScalar(self, data):\n yield data\n \n def appendRow(self, data):\n self.appendData([data])\n \n @_defersort\n def addRow(self, vals):\n row = self.rowCount()\n self.setRowCount(row + 1)\n self.setRow(row, vals)\n \n @_defersort\n def setRow(self, row, vals):\n if row > self.rowCount() - 1:\n self.setRowCount(row + 1)\n for col in range(len(vals)):\n val = vals[col]\n item = self.itemClass(val, row)\n item.setEditable(self.editable)\n sortMode = self.sortModes.get(col, None)\n if sortMode is not None:\n item.setSortMode(sortMode)\n format = self._formats.get(col, self._formats[None])\n item.setFormat(format)\n self.items.append(item)\n self.setItem(row, col, item)\n item.setValue(val) # Required--the text-change callback is invoked\n # when we call setItem.\n\n def setSortMode(self, column, mode):\n \"\"\"\n Set the mode used to sort *column*.\n \n ============== ========================================================\n **Sort Modes**\n value Compares item.value if available; falls back to text\n comparison.\n text Compares item.text()\n index Compares by the order in which items were inserted.\n ============== ========================================================\n \n Added in version 0.9.9\n \"\"\"\n for r in range(self.rowCount()):\n item = self.item(r, column)\n if hasattr(item, 'setSortMode'):\n item.setSortMode(mode)\n self.sortModes[column] = mode\n \n def sizeHint(self):\n # based on http://stackoverflow.com/a/7195443/54056\n width = sum(self.columnWidth(i) for i in range(self.columnCount()))\n width += self.verticalHeader().sizeHint().width()\n width += self.verticalScrollBar().sizeHint().width()\n width += self.frameWidth() * 2\n height = sum(self.rowHeight(i) for i in range(self.rowCount()))\n height += self.verticalHeader().sizeHint().height()\n height += self.horizontalScrollBar().sizeHint().height()\n return QtCore.QSize(width, height)\n \n def serialize(self, useSelection=False):\n \"\"\"Convert entire table (or just selected area) into tab-separated text values\"\"\"\n if useSelection:\n selection = self.selectedRanges()[0]\n rows = list(range(selection.topRow(),\n selection.bottomRow() + 1))\n columns = list(range(selection.leftColumn(),\n selection.rightColumn() + 1)) \n else:\n rows = list(range(self.rowCount()))\n columns = list(range(self.columnCount()))\n\n data = []\n if self.horizontalHeadersSet:\n row = []\n if self.verticalHeadersSet:\n row.append(asUnicode(''))\n \n for c in columns:\n row.append(asUnicode(self.horizontalHeaderItem(c).text()))\n data.append(row)\n \n for r in rows:\n row = []\n if self.verticalHeadersSet:\n row.append(asUnicode(self.verticalHeaderItem(r).text()))\n for c in columns:\n item = self.item(r, c)\n if item is not None:\n row.append(asUnicode(item.value))\n else:\n row.append(asUnicode(''))\n data.append(row)\n \n s = ''\n for row in data:\n s += ('\\t'.join(row) + '\\n')\n return s\n\n def copySel(self):\n \"\"\"Copy selected data to clipboard.\"\"\"\n QtGui.QApplication.clipboard().setText(self.serialize(useSelection=True))\n\n def copyAll(self):\n \"\"\"Copy all data to clipboard.\"\"\"\n QtGui.QApplication.clipboard().setText(self.serialize(useSelection=False))\n\n def saveSel(self):\n \"\"\"Save selected data to file.\"\"\"\n self.save(self.serialize(useSelection=True))\n\n def saveAll(self):\n \"\"\"Save all data to file.\"\"\"\n self.save(self.serialize(useSelection=False))\n\n def save(self, data):\n fileName = QtGui.QFileDialog.getSaveFileName(self, \"Save As..\", \"\", \"Tab-separated values (*.tsv)\")\n if isinstance(fileName, tuple):\n fileName = fileName[0] # Qt4/5 API difference\n if fileName == '':\n return\n with open(fileName, 'w') as fd:\n fd.write(data)\n\n def contextMenuEvent(self, ev):\n self.contextMenu.popup(ev.globalPos())\n \n def keyPressEvent(self, ev):\n if ev.key() == QtCore.Qt.Key_C and ev.modifiers() == QtCore.Qt.ControlModifier:\n ev.accept()\n self.copySel()\n else:\n QtGui.QTableWidget.keyPressEvent(self, ev)\n\n def handleItemChanged(self, item):\n item.itemChanged()\n\n\nclass TableWidgetItem(QtGui.QTableWidgetItem):\n def __init__(self, val, index, format=None):\n QtGui.QTableWidgetItem.__init__(self, '')\n self._blockValueChange = False\n self._format = None\n self._defaultFormat = '%0.3g'\n self.sortMode = 'value'\n self.index = index\n flags = QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled\n self.setFlags(flags)\n self.setValue(val)\n self.setFormat(format)\n \n def setEditable(self, editable):\n \"\"\"\n Set whether this item is user-editable.\n \"\"\"\n if editable:\n self.setFlags(self.flags() | QtCore.Qt.ItemIsEditable)\n else:\n self.setFlags(self.flags() & ~QtCore.Qt.ItemIsEditable)\n \n def setSortMode(self, mode):\n \"\"\"\n Set the mode used to sort this item against others in its column.\n \n ============== ========================================================\n **Sort Modes**\n value Compares item.value if available; falls back to text\n comparison.\n text Compares item.text()\n index Compares by the order in which items were inserted.\n ============== ========================================================\n \"\"\"\n modes = ('value', 'text', 'index', None)\n if mode not in modes:\n raise ValueError('Sort mode must be one of %s' % str(modes))\n self.sortMode = mode\n \n def setFormat(self, fmt):\n \"\"\"Define the conversion from item value to displayed text. \n \n If a string is specified, it is used as a format string for converting\n float values (and all other types are converted using str). If a \n function is specified, it will be called with the item as its only\n argument and must return a string.\n \n Added in version 0.9.9.\n \"\"\"\n if fmt is not None and not isinstance(fmt, basestring) and not callable(fmt):\n raise ValueError(\"Format argument must string, callable, or None. (got %s)\" % fmt)\n self._format = fmt\n self._updateText()\n \n def _updateText(self):\n self._blockValueChange = True\n try:\n self._text = self.format()\n self.setText(self._text)\n finally:\n self._blockValueChange = False\n\n def setValue(self, value):\n self.value = value\n self._updateText()\n\n def itemChanged(self):\n \"\"\"Called when the data of this item has changed.\"\"\"\n if self.text() != self._text:\n self.textChanged()\n\n def textChanged(self):\n \"\"\"Called when this item's text has changed for any reason.\"\"\"\n self._text = self.text()\n\n if self._blockValueChange:\n # text change was result of value or format change; do not\n # propagate.\n return\n \n try:\n\n self.value = type(self.value)(self.text())\n except ValueError:\n self.value = str(self.text())\n\n def format(self):\n if callable(self._format):\n return self._format(self)\n if isinstance(self.value, (float, np.floating)):\n if self._format is None:\n return self._defaultFormat % self.value\n else:\n return self._format % self.value\n else:\n return asUnicode(self.value)\n\n def __lt__(self, other):\n if self.sortMode == 'index' and hasattr(other, 'index'):\n return self.index < other.index\n if self.sortMode == 'value' and hasattr(other, 'value'):\n return self.value < other.value\n else:\n return self.text() < other.text()\n\n\nif __name__ == '__main__':\n app = QtGui.QApplication([])\n win = QtGui.QMainWindow()\n t = TableWidget()\n win.setCentralWidget(t)\n win.resize(800,600)\n win.show()\n \n ll = [[1,2,3,4,5]] * 20\n ld = [{'x': 1, 'y': 2, 'z': 3}] * 20\n dl = {'x': list(range(20)), 'y': list(range(20)), 'z': list(range(20))}\n \n a = np.ones((20, 5))\n ra = np.ones((20,), dtype=[('x', int), ('y', int), ('z', int)])\n \n t.setData(ll)\n \n ma = metaarray.MetaArray(np.ones((20, 3)), info=[\n {'values': np.linspace(1, 5, 20)}, \n {'cols': [\n {'name': 'x'},\n {'name': 'y'},\n {'name': 'z'},\n ]}\n ])\n t.setData(ma)\n \n" ]
[ [ "numpy.linspace", "numpy.ones", "numpy.isscalar" ] ]
danielhomola/federated_ml_platform
[ "353a2e8472f17bd4d3787748a96c269970ef1d3b" ]
[ "src/neoglia/etl/utils.py" ]
[ "import os\nimport logging\n\nimport psycopg2\nimport sshtunnel\nimport pandas as pd\n\nlogger = logging.getLogger(__name__)\n\n\ndef connect_to_db_via_ssh(ssh_info, db_info):\n \"\"\"\n Connects to a remote PostgreSQL db, via SSH tunnel.\n\n Args:\n ssh_info (obj): All ssh connection info.\n db_info (obj): All db related connection info.\n\n Returns:\n :class:`psycopg2.extensions.connection`: Live connection suitable for queries.\n \"\"\"\n tunnel = sshtunnel.SSHTunnelForwarder(\n ssh_info.host,\n ssh_private_key=ssh_info.ssh_private_key,\n ssh_username=ssh_info.ssh_username,\n remote_bind_address=ssh_info.remote_bind_address\n )\n\n tunnel.start()\n logger.info(\"SSH tunnel connected.\")\n\n conn = psycopg2.connect(\n database=db_info.db_name,\n user=db_info.db_user,\n password=db_info.db_password,\n host=tunnel.local_bind_host,\n port=tunnel.local_bind_port\n )\n logger.info(\"Postgres database %s connected\" % db_info.db_name)\n return conn\n\n\ndef run_eicu_query(query, conn):\n \"\"\"\n Runs a SQL query, with the appropriate search path for the eICU database.\n Returns a pandas DataFrame with the results.\n\n Args:\n query (str): SQL query to be executed.\n conn (:class:`psycopg2.extensions.connection`): Established psycopg2 connection.\n\n Returns:\n :class:`pandas.DataFrame`: DataFrame with the results of the query.\n \"\"\"\n query_schema = \"set search_path to eicu_crd;\"\n query = query_schema + query\n return pd.read_sql_query(query, conn)\n\n\ndef get_column_completeness(table_name, column_names, conn, verbose=True):\n \"\"\"\n Takes a PostgreSQL table and a list of column names and returns a pandas Series\n with the percentage completeness of all columns.\n\n Args:\n table_name (str): Name of the table to use.\n column_names (list<str>): Column names to use.\n conn (:class:`psycopg2.extensions.connection`): Established psycopg2 connection.\n verbose (bool): If False, we don't print out anything during the computation.\n\n Returns:\n :class:`pandas.Series`: Series with the percentage of non missing for each col.\n \"\"\"\n percentages = []\n for column_name in column_names:\n query =\"\"\"select 100.0 * count({col}) / count(1) as percentnotnull\n from {table};\"\"\".format(col=column_name, table=table_name)\n df = run_eicu_query(query, conn)\n percentage = df['percentnotnull'].values[0]\n percentages.append(percentage)\n if verbose:\n logger.debug('%s: %f' % (column_name, percentage))\n return pd.Series(percentages, index=column_names)\n\n\ndef load_schema_for_modelling():\n \"\"\"\n Loads the cleaned and edited schema (as a csv) of the tables used for modelling.\n\n Returns:\n :class:`pandas.DataFrame`: DF with the schema columns (indexed by table names).\n \"\"\"\n filename = \"modelling_schema.csv\"\n folder = os.path.abspath(os.path.dirname(__file__))\n path = os.path.join(folder, filename)\n return pd.read_csv(path).set_index('table_name')\n" ]
[ [ "pandas.read_csv", "pandas.Series", "pandas.read_sql_query" ] ]
anujdutt9/ESPCN
[ "896ba54940dd2fc1f6c7ae6a9257d3fcfdf85842" ]
[ "dataloader.py" ]
[ "import os\nimport cv2\nimport random\nimport numpy as np\nfrom PIL import Image\nfrom glob import glob\nimport matplotlib.pyplot as plt\nfrom torch.utils.data import IterableDataset, DataLoader\n\n\n# Ref.: https://github.com/yjn870/ESPCN-pytorch/blob/ab84ee1bccb2978f2f9b88f9e0315d9be12c099e/prepare.py#L16\n# Train Dataset Class\nclass SRTrainDataset(IterableDataset):\n def __init__(self, dirpath_images, scaling_factor, patch_size, stride):\n \"\"\" Training Dataset\n\n :param dirpath_images: path to training images directory\n :param scaling_factor: up-scaling factor to use, default = 3\n :param patch_size: size of sub-images to be extracted\n :param stride: stride used for extracting sub-images\n \"\"\"\n\n self.dirpath_images = dirpath_images\n self.scaling_factor = scaling_factor\n self.patch_size = patch_size\n self.stride = stride\n\n def __iter__(self):\n for fpath_image in glob(os.path.join(self.dirpath_images, \"*.png\")):\n # Load HR image: rH x rW x C, r: scaling factor\n hr_image = Image.open(fpath_image).convert('RGB')\n hr_width = (hr_image.width // self.scaling_factor) * self.scaling_factor\n hr_height = (hr_image.height // self.scaling_factor) * self.scaling_factor\n hr_image = hr_image.resize((hr_width, hr_height), resample=Image.BICUBIC)\n\n # LR Image: H x W x C\n # As in paper, Sec. 3.2: sub-sample images by up-scaling factor\n lr_image = hr_image.resize((hr_width // self.scaling_factor, hr_height // self.scaling_factor), resample=Image.BICUBIC)\n\n hr_image = np.array(hr_image).astype(np.float32)\n lr_image = np.array(lr_image).astype(np.float32)\n\n # Convert BGR to YCbCr\n hr_image = cv2.cvtColor(hr_image, cv2.COLOR_RGB2YCrCb)\n lr_image = cv2.cvtColor(lr_image, cv2.COLOR_RGB2YCrCb)\n\n # As per paper, using only the luminescence channel gave the best outcome\n hr_y = hr_image[:, :, 0]\n lr_y = lr_image[:, :, 0]\n\n # Get sub-image from Ihr and Ilr as per Sec. 3.2 in paper\n # using patch_size = 17 and stride = 13\n # This ensures that all pixels in the original image appear once and only once as the ground truth of the\n # training data\n rows = lr_y.shape[0]\n cols = lr_y.shape[1]\n for i in range(0, rows - self.patch_size + 1, self.stride):\n for j in range(0, cols - self.patch_size + 1, self.stride):\n # lr_crop: w = 17, h = 17\n lr_crop = lr_y[i:i + self.patch_size, j:j + self.patch_size]\n # hr_crop: w = 17 * r, h = 17 * r\n hr_crop = hr_y[i * self.scaling_factor:i * self.scaling_factor + self.patch_size * self.scaling_factor,\n j * self.scaling_factor:j * self.scaling_factor + self.patch_size * self.scaling_factor]\n lr_crop = np.expand_dims(lr_crop / 255.0, axis=0)\n hr_crop = np.expand_dims(hr_crop / 255.0, axis=0)\n yield lr_crop, hr_crop\n\n def __len__(self):\n return len(self.all_images)\n\n\n# Valid Dataset Class\nclass SRValidDataset(IterableDataset):\n def __init__(self, dirpath_images, scaling_factor):\n \"\"\" Validation Dataset\n\n :param dirpath_images: path to validation images directory\n :param scaling_factor: up-scaling factor to use, default = 3\n \"\"\"\n\n self.dirpath_images = dirpath_images\n self.scaling_factor = scaling_factor\n\n def __iter__(self):\n for fpath_image in glob(os.path.join(self.dirpath_images, \"*.png\")):\n # Load HR image: rH x rW x C, r: scaling factor\n hr_image = Image.open(fpath_image).convert('RGB')\n hr_width = (hr_image.width // self.scaling_factor) * self.scaling_factor\n hr_height = (hr_image.height // self.scaling_factor) * self.scaling_factor\n hr_image = hr_image.resize((hr_width, hr_height), resample=Image.BICUBIC)\n\n # LR Image: H x W x C\n # As in paper, Sec. 3.2: sub-sample images by up-scaling factor\n lr_image = hr_image.resize((hr_width // self.scaling_factor, hr_height // self.scaling_factor), resample=Image.BICUBIC)\n\n hr_image = np.array(hr_image).astype(np.float32)\n lr_image = np.array(lr_image).astype(np.float32)\n\n # Convert BGR to YCbCr\n hr_image = cv2.cvtColor(hr_image, cv2.COLOR_RGB2YCrCb)\n lr_image = cv2.cvtColor(lr_image, cv2.COLOR_RGB2YCrCb)\n\n # As per paper, using only the luminescence channel gave the best outcome\n hr_y = hr_image[:, :, 0]\n lr_y = lr_image[:, :, 0]\n\n lr_y = np.expand_dims(lr_y / 255.0, axis=0)\n hr_y = np.expand_dims(hr_y / 255.0, axis=0)\n yield lr_y, hr_y\n\n def __len__(self):\n return len(self.all_images)\n\n\n# Ref.: https://discuss.pytorch.org/t/how-to-shuffle-an-iterable-dataset/64130/6\nclass ShuffleDataset(IterableDataset):\n def __init__(self, dataset, buffer_size):\n super().__init__()\n self.dataset = dataset\n self.buffer_size = buffer_size\n\n def __iter__(self):\n shufbuf = []\n try:\n dataset_iter = iter(self.dataset)\n for i in range(self.buffer_size):\n shufbuf.append(next(dataset_iter))\n except:\n self.buffer_size = len(shufbuf)\n\n try:\n while True:\n try:\n item = next(dataset_iter)\n evict_idx = random.randint(0, self.buffer_size - 1)\n yield shufbuf[evict_idx]\n shufbuf[evict_idx] = item\n except StopIteration:\n break\n while len(shufbuf) > 0:\n yield shufbuf.pop()\n except GeneratorExit:\n pass\n\n\ndef get_data_loader(dirpath_train, dirpath_val, scaling_factor, patch_size, stride):\n \"\"\" Function to return train/val data loader\n\n :param dirpath_train (str): path to directory containing high resolution training images\n :param dirpath_val (str): path to directory containing high resolution validation images\n :param scaling_factor (int): Number by which to scale the lr image to hr image\n :param patch_size (int): size of sub-images extracted from original images\n :param stride (int): sub-images extraction stride\n :return (torch.utils.data.DataLoader): training and validation data loader\n \"\"\"\n # As per paper, Sec. 3.2, sub-images are extracted only during the training phase\n dataset = SRTrainDataset(dirpath_images=dirpath_train,\n scaling_factor=scaling_factor,\n patch_size=patch_size,\n stride=stride)\n train_dataset = ShuffleDataset(dataset, 1024)\n train_loader = DataLoader(train_dataset,\n batch_size=16,\n num_workers=4,\n pin_memory=True)\n\n valid_dataset = SRValidDataset(dirpath_images=dirpath_val,\n scaling_factor=scaling_factor)\n val_loader = DataLoader(valid_dataset,\n batch_size=1,\n pin_memory=True)\n\n return train_loader, val_loader\n\n\nif __name__ == '__main__':\n # Test DataLoaders\n train_loader, val_loader = get_data_loader(dirpath_train=\"./dataset/train\",\n dirpath_val=\"./dataset/val\",\n scaling_factor=3,\n patch_size=17,\n stride=13)\n\n for idx, (lr_image, hr_image) in enumerate(train_loader):\n print(f\"Training - lr_image: {lr_image.shape}, hr_image: {hr_image.shape}\")\n break\n\n for idx, (lr_image, hr_image) in enumerate(val_loader):\n print(f\"Validation - lr_image: {lr_image.shape}, hr_image: {hr_image.shape}\")\n break\n\n for idx, (lr_image, hr_image) in enumerate(train_loader):\n print(f\"lr_image: {lr_image.shape}, hr_image: {hr_image.shape}\")\n lr = lr_image[0].numpy().transpose(1, 2, 0)\n hr = hr_image[0].numpy().transpose(1, 2, 0)\n print(f\"{lr.shape}, {hr.shape}\")\n fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(20, 10))\n ax1.imshow(lr)\n ax1.set_title(\"Low Res\")\n ax2.imshow(hr)\n ax2.set_title(\"High Res\")\n plt.show()\n break\n" ]
[ [ "numpy.array", "matplotlib.pyplot.subplots", "torch.utils.data.DataLoader", "matplotlib.pyplot.show", "numpy.expand_dims" ] ]
zavalit/Multi-Human-Parsing
[ "26c0e4ed560ecb486ac59011c3fa579b12aca796" ]
[ "Evaluation/Multi-Human-Parsing/v2/voc_eval.py" ]
[ "# --------------------------------------------------------\n# Fast/er R-CNN\n# Licensed under The MIT License [see LICENSE for details]\n# Written by Bharath Hariharan\n# --------------------------------------------------------\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport xml.etree.ElementTree as ET\nimport os\nimport pickle\nimport numpy as np\n\ndef parse_rec(filename):\n \"\"\" Parse a PASCAL VOC xml file \"\"\"\n tree = ET.parse(filename)\n objects = []\n for obj in tree.findall('object'):\n obj_struct = {}\n obj_struct['name'] = obj.find('name').text\n obj_struct['pose'] = obj.find('pose').text\n obj_struct['truncated'] = int(obj.find('truncated').text)\n obj_struct['difficult'] = int(obj.find('difficult').text)\n bbox = obj.find('bndbox')\n obj_struct['bbox'] = [int(bbox.find('xmin').text),\n int(bbox.find('ymin').text),\n int(bbox.find('xmax').text),\n int(bbox.find('ymax').text)]\n objects.append(obj_struct)\n\n return objects\n\n\ndef voc_ap(rec, prec, use_07_metric=False):\n \"\"\" ap = voc_ap(rec, prec, [use_07_metric])\n Compute VOC AP given precision and recall.\n If use_07_metric is true, uses the\n VOC 07 11 point method (default:False).\n \"\"\"\n if use_07_metric:\n # 11 point metric\n ap = 0.\n for t in np.arange(0., 1.1, 0.1):\n if np.sum(rec >= t) == 0:\n p = 0\n else:\n p = np.max(prec[rec >= t])\n ap = ap + p / 11.\n else:\n # correct AP calculation\n # first append sentinel values at the end\n mrec = np.concatenate(([0.], rec, [1.]))\n mpre = np.concatenate(([0.], prec, [0.]))\n\n # compute the precision envelope\n for i in range(mpre.size - 1, 0, -1):\n mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i])\n\n # to calculate area under PR curve, look for points\n # where X axis (recall) changes value\n i = np.where(mrec[1:] != mrec[:-1])[0]\n\n # and sum (\\Delta recall) * prec\n ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1])\n return ap\n\n\ndef voc_eval(detpath,\n annopath,\n imagesetfile,\n classname,\n cachedir,\n ovthresh=0.5,\n use_07_metric=False):\n \"\"\"rec, prec, ap = voc_eval(detpath,\n annopath,\n imagesetfile,\n classname,\n [ovthresh],\n [use_07_metric])\n\n Top level function that does the PASCAL VOC evaluation.\n\n detpath: Path to detections\n detpath.format(classname) should produce the detection results file.\n annopath: Path to annotations\n annopath.format(imagename) should be the xml annotations file.\n imagesetfile: Text file containing the list of images, one image per line.\n classname: Category name (duh)\n cachedir: Directory for caching the annotations\n [ovthresh]: Overlap threshold (default = 0.5)\n [use_07_metric]: Whether to use VOC07's 11 point AP computation\n (default False)\n \"\"\"\n # assumes detections are in detpath.format(classname)\n # assumes annotations are in annopath.format(imagename)\n # assumes imagesetfile is a text file with each line an image name\n # cachedir caches the annotations in a pickle file\n\n # first load gt\n if not os.path.isdir(cachedir):\n os.mkdir(cachedir)\n cachefile = os.path.join(cachedir, 'annots.pkl')\n # read list of images\n with open(imagesetfile, 'r') as f:\n lines = f.readlines()\n imagenames = [x.strip() for x in lines]\n\n if not os.path.isfile(cachefile):\n # load annots\n recs = {}\n for i, imagename in enumerate(imagenames):\n recs[imagename] = parse_rec(annopath.format(imagename))\n if i % 100 == 0:\n print('Reading annotation for {:d}/{:d}'.format(\n i + 1, len(imagenames)))\n # save\n print('Saving cached annotations to {:s}'.format(cachefile))\n with open(cachefile, 'w') as f:\n pickle.dump(recs, f)\n else:\n # load\n with open(cachefile, 'rb') as f:\n try:\n recs = pickle.load(f)\n except:\n recs = pickle.load(f, encoding='bytes')\n\n # extract gt objects for this class\n class_recs = {}\n npos = 0\n for imagename in imagenames:\n R = [obj for obj in recs[imagename] if obj['name'] == classname]\n bbox = np.array([x['bbox'] for x in R])\n difficult = np.array([x['difficult'] for x in R]).astype(np.bool)\n det = [False] * len(R)\n npos = npos + sum(~difficult)\n class_recs[imagename] = {'bbox': bbox,\n 'difficult': difficult,\n 'det': det}\n\n # read dets\n detfile = detpath.format(classname)\n with open(detfile, 'r') as f:\n lines = f.readlines()\n\n splitlines = [x.strip().split(' ') for x in lines]\n image_ids = [x[0] for x in splitlines]\n confidence = np.array([float(x[1]) for x in splitlines])\n BB = np.array([[float(z) for z in x[2:]] for x in splitlines])\n\n nd = len(image_ids)\n tp = np.zeros(nd)\n fp = np.zeros(nd)\n\n if BB.shape[0] > 0:\n # sort by confidence\n sorted_ind = np.argsort(-confidence)\n sorted_scores = np.sort(-confidence)\n BB = BB[sorted_ind, :]\n image_ids = [image_ids[x] for x in sorted_ind]\n\n # go down dets and mark TPs and FPs\n for d in range(nd):\n R = class_recs[image_ids[d]]\n bb = BB[d, :].astype(float)\n ovmax = -np.inf\n BBGT = R['bbox'].astype(float)\n\n if BBGT.size > 0:\n # compute overlaps\n # intersection\n ixmin = np.maximum(BBGT[:, 0], bb[0])\n iymin = np.maximum(BBGT[:, 1], bb[1])\n ixmax = np.minimum(BBGT[:, 2], bb[2])\n iymax = np.minimum(BBGT[:, 3], bb[3])\n iw = np.maximum(ixmax - ixmin + 1., 0.)\n ih = np.maximum(iymax - iymin + 1., 0.)\n inters = iw * ih\n\n # union\n uni = ((bb[2] - bb[0] + 1.) * (bb[3] - bb[1] + 1.) +\n (BBGT[:, 2] - BBGT[:, 0] + 1.) *\n (BBGT[:, 3] - BBGT[:, 1] + 1.) - inters)\n\n overlaps = inters / uni\n ovmax = np.max(overlaps)\n jmax = np.argmax(overlaps)\n\n if ovmax > ovthresh:\n if not R['difficult'][jmax]:\n if not R['det'][jmax]:\n tp[d] = 1.\n R['det'][jmax] = 1\n else:\n fp[d] = 1.\n else:\n fp[d] = 1.\n\n # compute precision recall\n fp = np.cumsum(fp)\n tp = np.cumsum(tp)\n rec = tp / float(npos)\n # avoid divide by zero in case the first detection matches a difficult\n # ground truth\n prec = tp / np.maximum(tp + fp, np.finfo(np.float64).eps)\n ap = voc_ap(rec, prec, use_07_metric)\n\n return rec, prec, ap\n" ]
[ [ "numpy.concatenate", "numpy.max", "numpy.array", "numpy.zeros", "numpy.minimum", "numpy.sum", "numpy.where", "numpy.finfo", "numpy.arange", "numpy.sort", "numpy.argsort", "numpy.cumsum", "numpy.argmax", "numpy.maximum" ] ]
zfergus/fenics-topopt
[ "b8479f3b069fb86256be749c209698571260cac9" ]
[ "topopt/problem.py" ]
[ "from __future__ import division\n\nimport numpy as np\n\nimport pdb\n\nimport scipy.sparse\nfrom scipy.sparse import coo_matrix\nimport cvxopt\nimport cvxopt.cholmod\n\nfrom utils import deleterowcol\n\n\nclass Problem(object):\n\n @staticmethod\n def lk(E=1.):\n \"\"\"element stiffness matrix\"\"\"\n nu = 0.3\n k = np.array([0.5 - nu / 6., 0.125 + nu / 8., -0.25 - nu / 12.,\n -0.125 + 0.375 * nu, -0.25 + nu / 12., -0.125 - nu / 8., nu / 6.,\n 0.125 - 0.375 * nu])\n KE = E / (1 - nu**2) * np.array([\n [k[0], k[1], k[2], k[3], k[4], k[5], k[6], k[7]],\n [k[1], k[0], k[7], k[6], k[5], k[4], k[3], k[2]],\n [k[2], k[7], k[0], k[5], k[6], k[3], k[4], k[1]],\n [k[3], k[6], k[5], k[0], k[7], k[2], k[1], k[4]],\n [k[4], k[5], k[6], k[7], k[0], k[1], k[2], k[3]],\n [k[5], k[4], k[3], k[2], k[1], k[0], k[7], k[6]],\n [k[6], k[3], k[4], k[1], k[2], k[7], k[0], k[5]],\n [k[7], k[2], k[1], k[4], k[3], k[6], k[5], k[0]]])\n return KE\n\n def build_indices(self, nelx, nely):\n \"\"\" FE: Build the index vectors for the for coo matrix format. \"\"\"\n self.KE = self.lk()\n self.edofMat = np.zeros((nelx * nely, 8), dtype=int)\n for elx in range(nelx):\n for ely in range(nely):\n el = ely + elx * nely\n n1 = (nely + 1) * elx + ely\n n2 = (nely + 1) * (elx + 1) + ely\n self.edofMat[el, :] = np.array([2 * n1 + 2, 2 * n1 + 3,\n 2 * n2 + 2, 2 * n2 + 3, 2 * n2, 2 * n2 + 1, 2 * n1,\n 2 * n1 + 1])\n # Construct the index pointers for the coo format\n self.iK = np.kron(self.edofMat, np.ones((8, 1))).flatten()\n self.jK = np.kron(self.edofMat, np.ones((1, 8))).flatten()\n\n def __init__(self, nelx, nely, penal, bc):\n # Problem size\n self.nelx = nelx\n self.nely = nely\n\n # Max and min stiffness\n self.Emin = 1e-9\n self.Emax = 1.0\n\n # SIMP penalty\n self.penal = penal\n\n # dofs:\n self.ndof = 2 * (nelx + 1) * (nely + 1)\n\n # FE: Build the index vectors for the for coo matrix format.\n self.build_indices(nelx, nely)\n\n # BC's and support (half MBB-beam)\n dofs = np.arange(2 * (nelx + 1) * (nely + 1))\n self.fixed = bc.get_fixed_nodes()\n self.free = np.setdiff1d(dofs, self.fixed)\n\n # Solution and RHS vectors\n self.f = bc.get_forces()\n self.u = np.zeros(self.f.shape)\n\n # Per element compliance\n self.ce = np.zeros(nely * nelx)\n\n def compute_displacements(self, xPhys):\n # Setup and solve FE problem\n sK = ((self.KE.flatten()[np.newaxis]).T * (\n self.Emin + (xPhys)**self.penal *\n (self.Emax - self.Emin))).flatten(order='F')\n K = scipy.sparse.coo_matrix((sK, (self.iK, self.jK)),\n shape=(self.ndof, self.ndof)).tocsc()\n # Remove constrained dofs from matrix and convert to coo\n K = deleterowcol(K, self.fixed, self.fixed).tocoo()\n # Solve system\n K1 = cvxopt.spmatrix(K.data, K.row.astype(np.int), K.col.astype(np.int))\n B = cvxopt.matrix(self.f[self.free, :])\n cvxopt.cholmod.linsolve(K1, B)\n self.u[self.free, :] = np.array(B)[:, :]\n\n def compute_compliance(self, xPhys, dc):\n # Compute compliance and its gradient\n u = self.u[:, 0][self.edofMat].reshape(-1, 8)\n self.ce[:] = (u.dot(self.KE) * u).sum(1)\n obj = ((self.Emin + xPhys**self.penal *\n (self.Emax - self.Emin)) * self.ce).sum()\n dc[:] = (-self.penal * xPhys**(self.penal - 1.0) *\n (self.Emax - self.Emin)) * self.ce\n return obj\n" ]
[ [ "numpy.array", "numpy.setdiff1d", "numpy.zeros", "numpy.ones", "numpy.arange" ] ]
guoyingying432/lung-segmentation-by-unet-and-tensorflow
[ "f766b06cac2ad46f607cd81a9fa618f32c51bfc0" ]
[ "unet.py" ]
[ "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Nov 12 18:24:43 2019\r\nThe class of unet_3D for the centernet detection\r\n@author: wjcongyu\r\n\"\"\"\r\nimport os\r\nimport os.path as osp\r\nimport tensorflow as tf\r\nfrom tensorflow import math\r\nfrom tensorflow import keras\r\nfrom tensorflow.keras import layers as KL\r\nfrom tensorflow.keras import models as KM\r\nfrom tensorflow.keras import losses as KLOSS\r\nfrom tensorflow.keras import backend as KB\r\nfrom tensorflow.python.framework import ops\r\nfrom tensorflow.python.ops import math_ops\r\nfrom tensorflow.python.framework import tensor_util\r\nfrom tensorflow.python.keras.utils import losses_utils\r\nimport glob\r\nimport numpy as np\r\nimport sys\r\n\r\nclass Unet():\r\n def __init__(self,input_shape, is_training, config, num_classes, model_dir):\r\n self._is_training = is_training\r\n self.config = config\r\n self.input_shape = input_shape\r\n self.num_classes = num_classes\r\n self.model_dir = model_dir\r\n self.NET_NAME = 'Seg_3DUnet'\r\n self.__set_log_dir() #logging and saving checkpoints\r\n self.model = self.__build(is_training=is_training)\r\n\r\n #public functions\r\n def summary(self):\r\n '''\r\n print the network attributes\r\n :return:\r\n '''\r\n return self.model.summary()\r\n\r\n def find_last(self):\r\n \"\"\"Finds the last checkpoint file of the last trained model in the\r\n model directory.\r\n Returns:\r\n The path of the last checkpoint file\r\n \"\"\"\r\n weights_files = glob.glob(osp.join(self.log_dir, self.NET_NAME.lower() + '*.h5'))\r\n if len(weights_files) == 0:\r\n return ''\r\n weights_files = sorted(weights_files, key=lambda x: os.path.getmtime(x))\r\n return weights_files[-1]\r\n\r\n def load_weights(self, filepath, by_name=False, exclude=None):\r\n '''\r\n loading weights from checkpoint\r\n :param filepath:\r\n :param by_name:\r\n :param exclude:\r\n :return:\r\n '''\r\n print('loading weights from:', filepath)\r\n self.model.load_weights(filepath, by_name)\r\n\r\n def train(self, train_data_provider, val_data_provider, learning_rate, decay_steps, epochs, batch_size,\r\n augment=None, custom_callbacks=None):\r\n '''\r\n Start training the model from specified dataset\r\n :param train_dataset:\r\n :param learning_rate:\r\n :param decay_steps:\r\n :param epochs:\r\n :param augment:\r\n :param custom_callbacks:\r\n :return:\r\n '''\r\n assert self._is_training == True, 'not in training mode'\r\n\r\n\r\n if not osp.exists(self.log_dir):\r\n os.mkdir(self.log_dir)\r\n\r\n lr_schedule = keras.optimizers.schedules.ExponentialDecay(learning_rate,\r\n decay_steps,\r\n decay_rate = 0.95,\r\n staircase = True)\r\n optimizer =keras.optimizers.Adam(learning_rate = lr_schedule)\r\n #optimizer = keras.optimizers.SGD(lr=learning_rate, decay= learning_rate/decay_steps, momentum=0.92, nesterov=True)# \r\n self.summary_writer = tf.summary.create_file_writer(self.log_dir)\r\n with self.summary_writer.as_default(): \r\n max_accuracy = 0.0\r\n for self.epoch in range(epochs):\r\n print ('# epoch:'+str(self.epoch+1)+'/'+str(epochs))\r\n losses = []\r\n for step in range(self.config.STEPS_PER_EPOCH):\r\n ims, label_gt = train_data_provider.next_batch(batch_size)\r\n \r\n with tf.GradientTape(persistent=False) as tape:\r\n label_preds = self.model(ims)\r\n loss = (1.0 - self.get_dice_coefficient(label_gt, label_preds, self.num_classes))+self.__compute_loss(label_gt, label_preds)\r\n \r\n losses.append(loss)\r\n grad = tape.gradient(loss, self.model.trainable_variables)\r\n optimizer.apply_gradients(grads_and_vars=zip(grad, self.model.trainable_variables))\r\n self.__draw_progress_bar(step+1,self.config.STEPS_PER_EPOCH)\r\n \r\n tst_ims, tst_y_gt = val_data_provider.next_batch(8)\r\n \r\n predictions = self.predict(tst_ims)\r\n \r\n label_preds = tf.reshape(predictions,[-1, self.num_classes])\r\n gt_labels = tf.reshape(tst_y_gt, [-1])\r\n \r\n pred_labels = tf.argmax(label_preds, axis=-1)\r\n \r\n keep = tf.where(tf.not_equal(gt_labels, 0))\r\n gt_labels = tf.gather(gt_labels, keep) \r\n \r\n pred_labels = tf.gather(pred_labels, keep)\r\n \r\n m = keras.metrics.Accuracy()\r\n m.update_state(gt_labels, pred_labels)\r\n accuracy = m.result().numpy()\r\n mean_loss = tf.reduce_mean(losses)\r\n print ('\\nLoss:%f; Accuracy:%f; Lr: %f' % (mean_loss, accuracy, KB.eval(optimizer._decayed_lr('float32'))))\r\n tf.summary.scalar('train_loss', mean_loss, step = (self.epoch+1))\r\n tf.summary.scalar('eval_accuracy', float(accuracy), step = (self.epoch+1))\r\n \r\n m.reset_states()\r\n if accuracy >= max_accuracy or accuracy > 0.98:\r\n max_accuracy = accuracy\r\n self.checkpoint_path = osp.join(self.log_dir, self.NET_NAME.lower() + \"_epoch{0}.h5\".format(self.epoch + 1)) \r\n print ('Saving weights to %s' % (self.checkpoint_path))\r\n self.model.save_weights(self.checkpoint_path)\r\n self.__delete_old_weights(self.config.MAX_KEEPS_CHECKPOINTS)\r\n\r\n \r\n\r\n def predict(self, image):\r\n return self.model.predict(image)\r\n\r\n #private functions\r\n def __set_log_dir(self):\r\n self.epoch = 0\r\n self.log_dir = osp.join(self.model_dir, self.NET_NAME.lower())\r\n\r\n def __build(self, is_training):\r\n #define inputs:[batch_size, Depth, Height, Width, Channels], for keras, you don't need\r\n #to specify the batch_size\r\n dtype = tf.float32\r\n input_image = KL.Input(shape = self.input_shape + [1], dtype= dtype, name='input_image')\r\n filters = [32, 64, 128, 256]\r\n x1 = KL.Conv3D(filters[0], (3, 3, 3), (1, 1, 1), padding='same')(input_image) \r\n x1 = KL.BatchNormalization(axis=-1)(x1, training=is_training)\r\n x1 = KL.ReLU()(x1) \r\n x1 = KL.Conv3D(filters[0], (3, 3, 3), (1, 1, 1), padding='same')(x1) \r\n x1 = KL.BatchNormalization(axis=-1)(x1, training=is_training)\r\n x1 = KL.ReLU()(x1)\r\n d1 = KL.MaxPooling3D(pool_size=(2, 2, 2))(x1) #16 \r\n \r\n x2 = KL.Conv3D(filters[1], (3, 3, 3), (1, 1, 1), padding='same')(d1) \r\n x2 = KL.BatchNormalization(axis=-1)(x2, training=is_training)\r\n x2 = KL.ReLU()(x2) \r\n x2 = KL.Conv3D(filters[1], (3, 3, 3), (1, 1, 1), padding='same')(x2) \r\n x2 = KL.BatchNormalization(axis=-1)(x2, training=is_training)\r\n x2 = KL.ReLU()(x2)\r\n d2 = KL.MaxPooling3D(pool_size=(2, 2, 2))(x2) #8\r\n \r\n x3 = KL.Conv3D(filters[2], (3, 3, 3), (1, 1, 1), padding='same')(d2) \r\n x3 = KL.BatchNormalization(axis=-1)(x3, training=is_training)\r\n x3 = KL.ReLU()(x3) \r\n x3 = KL.Conv3D(filters[2], (3, 3, 3), (1, 1, 1), padding='same')(x3) \r\n x3 = KL.BatchNormalization(axis=-1)(x3, training=is_training)\r\n x3 = KL.ReLU()(x3)\r\n d3 = KL.MaxPooling3D(pool_size=(2, 2, 2))(x3) #4\r\n \r\n x4 = KL.Conv3D(filters[3], (3, 3, 3), (1, 1, 1), padding='same')(d3) \r\n x4 = KL.BatchNormalization(axis=-1)(x4, training=is_training)\r\n x4 = KL.ReLU()(x4) \r\n x4 = KL.Conv3D(filters[3], (3, 3, 3), (1, 1, 1), padding='same')(x4) \r\n x4 = KL.BatchNormalization(axis=-1)(x4, training=is_training)\r\n x4 = KL.ReLU()(x4)\r\n d4 = KL.MaxPooling3D(pool_size=(2, 2, 2))(x4) #2\r\n \r\n u5 = KL.Conv3DTranspose(filters[3], (3, 3, 3), (2, 2, 2), padding='same')(d4)#KL.UpSampling3D()(d4)\r\n x5 = KL.Conv3D(filters[3], (3, 3, 3), (1, 1, 1), padding='same')(u5) \r\n x5 = KL.BatchNormalization(axis=-1)(x5, training=is_training)\r\n x5 = KL.ReLU()(x5)\r\n x5 = KL.Conv3D(filters[3], (3, 3, 3), (1, 1, 1), padding='same')(x5) \r\n x5 = KL.BatchNormalization(axis=-1)(x5, training=is_training)\r\n x5 = KL.ReLU()(x5)\r\n m5 = KL.Concatenate()([x5,x4])\r\n x5 = KL.Conv3D(filters[3], (3, 3, 3), (1, 1, 1), padding='same')(m5) \r\n x5 = KL.BatchNormalization(axis=-1)(x5, training=is_training)\r\n x5 = KL.ReLU()(x5)\r\n \r\n u6 = KL.Conv3DTranspose(filters[3], (3, 3, 3), (2, 2, 2), padding='same')(x4)#KL.UpSampling3D()(x5)\r\n x6 = KL.Conv3D(filters[2], (3, 3, 3), (1, 1, 1), padding='same')(u6) \r\n x6 = KL.BatchNormalization(axis=-1)(x6, training=is_training)\r\n x6 = KL.ReLU()(x6)\r\n x6 = KL.Conv3D(filters[2], (3, 3, 3), (1, 1, 1), padding='same')(x6) \r\n x6 = KL.BatchNormalization(axis=-1)(x6, training=is_training)\r\n x6 = KL.ReLU()(x6)\r\n m6 = KL.Concatenate()([x6,x3])\r\n x6 = KL.Conv3D(filters[2], (3, 3, 3), (1, 1, 1), padding='same')(m6) \r\n x6 = KL.BatchNormalization(axis=-1)(x6, training=is_training)\r\n x6 = KL.ReLU()(x6)\r\n \r\n u7 = KL.Conv3DTranspose(filters[3], (3, 3, 3), (2, 2, 2), padding='same')(x6)#KL.UpSampling3D()(x6)\r\n x7 = KL.Conv3D(filters[1], (3, 3, 3), (1, 1, 1), padding='same')(u7) \r\n x7 = KL.BatchNormalization(axis=-1)(x7, training=is_training)\r\n x7 = KL.ReLU()(x7)\r\n x7 = KL.Conv3D(filters[1], (3, 3, 3), (1, 1, 1), padding='same')(x7) \r\n x7 = KL.BatchNormalization(axis=-1)(x7, training=is_training)\r\n x7 = KL.ReLU()(x7)\r\n m7 = KL.Concatenate()([x7,x2])\r\n x7 = KL.Conv3D(filters[1], (3, 3, 3), (1, 1, 1), padding='same')(m7) \r\n x7 = KL.BatchNormalization(axis=-1)(x7, training=is_training)\r\n x7 = KL.ReLU()(x7)\r\n \r\n u8 = KL.Conv3DTranspose(filters[3], (3, 3, 3), (2, 2, 2), padding='same')(x7)#KL.UpSampling3D()(x7)\r\n x8 = KL.Conv3D(filters[0], (3, 3, 3), (1, 1, 1), padding='same')(u8) \r\n x8 = KL.BatchNormalization(axis=-1)(x8, training=is_training)\r\n x8 = KL.ReLU()(x8)\r\n x8 = KL.Conv3D(filters[0], (3, 3, 3), (1, 1, 1), padding='same')(x8) \r\n x8 = KL.BatchNormalization(axis=-1)(x8, training=is_training)\r\n x8 = KL.ReLU()(x8)\r\n m8 = KL.Concatenate()([x8,x1])\r\n x8 = KL.Conv3D(filters[0], (3, 3, 3), (1, 1, 1), padding='same')(m8) \r\n x8 = KL.BatchNormalization(axis=-1)(x8, training=is_training)\r\n x8 = KL.ReLU()(x8)\r\n \r\n #define output logits\r\n x9 = KL.Conv3D(self.num_classes, (3, 3, 3), padding='same')(x8) \r\n output = KL.Reshape([-1, self.num_classes])(x9)\r\n output = KL.Activation('softmax')(output)\r\n output = KL.Reshape(self.config.INPUT_SHAPE + [self.num_classes])(output)\r\n \r\n model = KM.Model(input_image, output, name=self.NET_NAME.lower())\r\n return model\r\n\r\n \r\n def __compute_loss(self, label_gt, label_preds):\r\n '''\r\n the loss for center keypoint loss\r\n :param cnt_gt:\r\n :param cnt_preds:\r\n :return:\r\n '''\r\n label_preds = ops.convert_to_tensor(label_preds)\r\n label_gt = math_ops.cast(label_gt, label_preds.dtype)\r\n label_preds = tf.reshape(label_preds,[-1, self.num_classes])\r\n label_gt = tf.reshape(label_gt, [-1, 1])\r\n \r\n return KLOSS.SparseCategoricalCrossentropy()(label_gt, label_preds)\r\n \r\n def get_dice_coefficient(self, gt_masks, pred_masks, cls_num): \r\n pred_masks = ops.convert_to_tensor(pred_masks) \r\n pred_masks = tf.reshape(pred_masks,[-1, cls_num])\r\n \r\n gt_masks = tf.keras.utils.to_categorical(gt_masks, cls_num)\r\n gt_masks = tf.reshape(gt_masks, [-1, cls_num])\r\n gt_masks = math_ops.cast(gt_masks, pred_masks.dtype)\r\n \r\n intersection = tf.reduce_sum(pred_masks*gt_masks)\r\n union = tf.reduce_sum(pred_masks) +tf.reduce_sum(gt_masks)\r\n return (2*intersection+1.0)/(union+1.0)\r\n\r\n\r\n def __delete_old_weights(self, nun_max_keep):\r\n '''\r\n keep num_max_keep weight files, the olds are deleted\r\n :param nun_max_keep:\r\n :return:\r\n '''\r\n weights_files = glob.glob(osp.join(self.log_dir, self.NET_NAME.lower() + '*.h5'))\r\n if len(weights_files) <= nun_max_keep:\r\n return\r\n\r\n weights_files = sorted(weights_files, key=lambda x: os.path.getmtime(x))\r\n\r\n weights_files = weights_files[0:len(weights_files) - nun_max_keep]\r\n\r\n for weight_file in weights_files:\r\n if weight_file != self.checkpoint_path:\r\n os.remove(weight_file)\r\n\r\n def __draw_progress_bar(self, cur, total, bar_len=50):\r\n cur_len = int(cur/total*bar_len)\r\n sys.stdout.write('\\r')\r\n sys.stdout.write(\"[{:<{}}] {}/{}\".format(\"=\" * cur_len, bar_len, cur, total))\r\n sys.stdout.flush()" ]
[ [ "tensorflow.keras.utils.to_categorical", "tensorflow.keras.layers.Activation", "tensorflow.reshape", "tensorflow.keras.layers.Reshape", "tensorflow.keras.layers.BatchNormalization", "tensorflow.python.ops.math_ops.cast", "tensorflow.keras.layers.MaxPooling3D", "tensorflow.GradientTape", "tensorflow.argmax", "tensorflow.keras.losses.SparseCategoricalCrossentropy", "tensorflow.keras.optimizers.Adam", "tensorflow.keras.layers.Concatenate", "tensorflow.summary.scalar", "tensorflow.keras.layers.Conv3D", "tensorflow.reduce_sum", "tensorflow.keras.metrics.Accuracy", "tensorflow.keras.layers.Conv3DTranspose", "tensorflow.keras.layers.Input", "tensorflow.not_equal", "tensorflow.python.framework.ops.convert_to_tensor", "tensorflow.keras.optimizers.schedules.ExponentialDecay", "tensorflow.gather", "tensorflow.summary.create_file_writer", "tensorflow.reduce_mean", "tensorflow.keras.layers.ReLU" ] ]
Daybreak2019/pytorch
[ "b80c6f863f2327c712c478f67c248b94d66b65ac" ]
[ "test/test_nn.py" ]
[ "\nimport math\nimport random\nimport string\nimport unittest\nimport io\nimport unittest.mock as mock\nimport itertools\nimport warnings\nimport pickle\nfrom copy import deepcopy\nfrom itertools import repeat, product\nfrom functools import reduce\nfrom operator import mul\nfrom collections import OrderedDict\n\nimport torch\n\n# TODO: remove this global setting\n# NN tests use double as the default dtype\ntorch.set_default_dtype(torch.double)\n\nfrom torch._six import inf, nan\nimport torch.backends.cudnn as cudnn\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.nn.init as init\nimport torch.nn.utils.rnn as rnn_utils\nfrom torch.nn.utils import clip_grad_norm_, clip_grad_value_\nimport torch.nn.utils.parametrize as parametrize\nimport torch.nn.utils.prune as prune\nfrom torch.nn.utils import parameters_to_vector, vector_to_parameters\nfrom torch.nn import Parameter\nfrom torch.nn.parameter import UninitializedParameter, UninitializedBuffer\nfrom torch.nn.parallel._functions import Broadcast\nfrom torch.testing import get_all_fp_dtypes\nfrom torch.testing._internal.common_utils import freeze_rng_state, run_tests, TestCase, skipIfNoLapack, skipIfRocm, \\\n TEST_NUMPY, TEST_SCIPY, TEST_WITH_ROCM, download_file, \\\n get_function_arglist, load_tests, repeat_test_for_types, ALL_TENSORTYPES, \\\n ALL_TENSORTYPES2, suppress_warnings, TemporaryFileName, TEST_WITH_UBSAN, IS_PPC\nfrom torch.testing._internal.common_cuda import TEST_CUDA, TEST_MULTIGPU, TEST_CUDNN, TEST_CUDNN_VERSION\nfrom torch.testing._internal.common_nn import NNTestCase, NewModuleTest, CriterionTest, \\\n module_tests, criterion_tests, loss_reference_fns, \\\n ctcloss_reference, new_module_tests\nfrom torch.testing._internal.common_device_type import instantiate_device_type_tests, dtypes, \\\n dtypesIfCUDA, precisionOverride, skipCUDAIfNoCudnn, skipCUDAIfCudnnVersionLessThan, onlyCUDA, onlyCPU, \\\n skipCUDAIfRocm, skipCUDAIf, skipCUDAIfNotRocm, onlyOnCPUAndCUDA, \\\n deviceCountAtLeast, expectedAlertNondeterministic, largeTensorTest, expectedFailureMeta\nfrom torch.nn import MultiheadAttention\n\nfrom hypothesis import given\nimport torch.testing._internal.hypothesis_utils as hu\nfrom torch.testing._internal.common_utils import _assertGradAndGradgradChecks, gradcheck, gradgradcheck\nfrom torch.testing._internal.common_utils import dtype2prec_DONTUSE\nfrom torch.testing._internal.common_cuda import tf32_on_and_off, tf32_is_not_fp32, tf32_off, tf32_on\nfrom torch.types import _TensorOrTensors\n\n\nAMPERE_OR_ROCM = TEST_WITH_ROCM or tf32_is_not_fp32()\n\n# load_tests from common_utils is used to automatically filter tests for\n# sharding on sandcastle. This line silences flake warnings\nload_tests = load_tests\n\nif TEST_SCIPY:\n from scipy import stats\n import scipy.ndimage\n\nif TEST_NUMPY:\n import numpy as np\n\nDOUBLE_TENSORTYPES = [torch.double]\n\n\n# WARNING: If you add a new top-level test case to this file, you MUST\n# update test/run_test.py to list it, otherwise it will NOT be run in\n# CI.\n\n\nclass PackedSequenceTest(TestCase):\n\n _type_by_name = {\n 'torch.DoubleTensor': (torch.DoubleTensor, 'double'),\n 'torch.FloatTensor': (torch.FloatTensor, 'float'),\n # We leave out `'torch.HalfTensor': (torch.HalfTensor, 'half'),`\n # because of an error in `pad_packed_sequence`\n # > AttributeError: 'torch.HalfTensor' object has no attribute 'fill_'\n 'torch.LongTensor': (torch.LongTensor, 'long'),\n 'torch.IntTensor': (torch.IntTensor, 'int'),\n 'torch.ShortTensor': (torch.ShortTensor, 'short'),\n 'torch.CharTensor': (torch.CharTensor, 'char'),\n 'torch.ByteTensor': (torch.ByteTensor, 'byte'),\n }\n\n def __init__(self, *args, **kwargs):\n super(PackedSequenceTest, self).__init__(*args, **kwargs)\n self.batch_size = 5\n self.max_length = 6\n\n def _ordered_sequence(self, tensor_type):\n \"\"\"Create ordered list of random sequences\"\"\"\n seqs = [tensor_type(random.randint(1, self.max_length))\n for _ in range(self.batch_size)]\n if tensor_type == torch.ByteTensor:\n seqs = [s.random_(0, 256) for s in seqs]\n else:\n seqs = [s.random_(-128, 128) for s in seqs]\n ordered = sorted(seqs, key=len, reverse=True)\n return ordered\n\n def _padded_sequence(self, tensor_type):\n \"\"\"Create Tensor of random padded sequences\"\"\"\n ordered = self._ordered_sequence(tensor_type)\n lengths = [len(i) for i in ordered]\n padded_tensor = rnn_utils.pad_sequence(ordered)\n return padded_tensor, lengths\n\n def test_type_casts(self):\n \"\"\"Test type casting of `PackedSequence` against type casting of tensor\"\"\"\n for _, (input_type, _) in self._type_by_name.items():\n for expected_type_str, (_, cast_str) in self._type_by_name.items():\n for enforce_sorted in [True, False]:\n padded, lengths = self._padded_sequence(input_type)\n packed = rnn_utils.pack_padded_sequence(\n padded, lengths, enforce_sorted=enforce_sorted)\n # Apply cast to `PackedSequence` instance and unpack\n masked = getattr(packed, cast_str)()\n unpacked, lengths_out = rnn_utils.pad_packed_sequence(masked)\n self.assertEqual(unpacked.type(), expected_type_str)\n\n def test_wrong_order(self):\n a = torch.ones(25, 300)\n b = torch.ones(22, 300)\n b_a = rnn_utils.pad_sequence([b, a])\n self.assertRaises(\n RuntimeError,\n lambda: rnn_utils.pack_padded_sequence(b_a, [22, 25], enforce_sorted=True))\n\n def test_total_length(self):\n padded, lengths = self._padded_sequence(torch.FloatTensor)\n max_length = max(lengths)\n packed = rnn_utils.pack_padded_sequence(padded, lengths)\n # test ValueError if total_length < max_length\n for total_length in (-1, 0, max_length - 1):\n for batch_first in (True, False):\n def err_fn():\n rnn_utils.pad_packed_sequence(packed, batch_first=batch_first,\n total_length=total_length)\n self.assertRaisesRegex(ValueError,\n r'Expected total_length to be at least the '\n r'length of the longest sequence in input',\n err_fn)\n # test that pad_packed_sequence returns results of correct length\n for batch_first in (True, False):\n no_extra_pad, _ = rnn_utils.pad_packed_sequence(packed, batch_first=batch_first)\n for total_length_delta in (0, 1, 8):\n total_length = max_length + total_length_delta\n unpacked, lengths_out = rnn_utils.pad_packed_sequence(packed, batch_first=batch_first,\n total_length=total_length)\n self.assertEqual(lengths, lengths_out)\n self.assertEqual(unpacked.size(1 if batch_first else 0), total_length)\n if total_length_delta == 0:\n ref_output = no_extra_pad\n elif batch_first:\n extra_pad = no_extra_pad.new_zeros(self.batch_size, total_length_delta)\n ref_output = torch.cat([no_extra_pad, extra_pad], 1)\n else:\n extra_pad = no_extra_pad.new_zeros(total_length_delta, self.batch_size)\n ref_output = torch.cat([no_extra_pad, extra_pad], 0)\n self.assertEqual(unpacked, ref_output)\n\n def test_to(self):\n for enforce_sorted in (True, False):\n padded, lengths = self._padded_sequence(torch.IntTensor)\n a = rnn_utils.pack_padded_sequence(\n padded, lengths, enforce_sorted=enforce_sorted).cpu()\n\n self.assertIs(a, a.to('cpu'))\n self.assertIs(a, a.cpu())\n self.assertIs(a, a.to('cpu', dtype=torch.int32))\n self.assertEqual(a.long(), a.to(torch.int64))\n\n if torch.cuda.is_available():\n for cuda in ['cuda', 'cuda:0' if torch.cuda.device_count() == 1 else 'cuda:1']:\n b = a.cuda(device=cuda)\n self.assertIs(b, b.to(cuda))\n self.assertIs(b, b.cuda())\n self.assertEqual(a, b.to('cpu'))\n self.assertEqual(b, a.to(cuda))\n self.assertEqual(a, b.to('cpu', dtype=torch.int32))\n self.assertIs(b, b.to(dtype=torch.int32))\n self.assertEqual(b.long(), b.to(dtype=torch.int64))\n\n def test_to_memory_format(self):\n m = torch.nn.Conv2d(in_channels=16, out_channels=32, kernel_size=2, bias=True)\n m = m.to(memory_format=torch.channels_last)\n for param in m.parameters():\n if param.dim() == 4:\n self.assertTrue(param.is_contiguous(memory_format=torch.channels_last))\n\nclass TestAvgPool(TestCase):\n def _sum_pool2d(self, x, kernel_size):\n windows = torch.nn.functional.unfold(x, kernel_size=kernel_size, stride=kernel_size)\n return torch.sum(windows, dim=1)\n\n def _sum_pool3d(self, x, kernel_size):\n # Because unfold does not support 3D sliding window we will split tensor to multiple tensors and calculate sum\n h = kernel_size[0]\n splited_x = [t.sum(0) for t in x.split(h) if t.size(0) == h]\n # sum_pool2d assumes tensor in (1, 1, n, m) view, so unsqueeze two times\n splited_x = [self._sum_pool2d(t.unsqueeze(0).unsqueeze(0), kernel_size[1:]) for t in splited_x]\n joined_x = torch.cat(splited_x)\n return joined_x.view(1, joined_x.numel())\n\n def _avg_pool2d(self, x, kernel_size):\n size = reduce((lambda x, y: x * y), kernel_size)\n return self._sum_pool2d(x, kernel_size) / size\n\n def _avg_pool3d(self, x, kernel_size):\n size = reduce((lambda x, y: x * y), kernel_size)\n return self._sum_pool3d(x, kernel_size) / size\n\n def test_doubletensor_avg_pool2d(self):\n n, m = 5, 8\n input = torch.rand(1, 1, n, m)\n for i in range(1, n + 1):\n for j in range(1, m + 1):\n actual = torch.nn.functional.avg_pool2d(input[0], (i, j))\n actual = actual.view(1, actual.numel())\n expected = self._avg_pool2d(input, (i, j))\n self.assertTrue(torch.allclose(actual, expected, rtol=0, atol=1e-5))\n\n def test_avg_pool2d_with_zero_divisor(self):\n self.assertRaisesRegex(RuntimeError, \"divisor must be not zero\",\n lambda: F.avg_pool2d(torch.zeros(3, 3, 3), (2, 2), divisor_override=0))\n\n def test_doubletensor_avg_pool2d_with_divisor(self):\n n, m = 3, 3\n input = torch.rand(1, 1, n, m)\n for i in range(1, n + 1):\n for j in range(1, m + 1):\n for divisor in [1, 7, i * j]:\n actual = F.avg_pool2d(input[0], (i, j), divisor_override=divisor)\n actual = actual.view(1, actual.numel())\n expected = self._sum_pool2d(input, (i, j)) / divisor\n self.assertTrue(torch.allclose(actual, expected, rtol=0, atol=1e-5))\n\n def test_doubletensor_avg_pool3d(self):\n h, w, d = 5, 6, 7\n input = torch.rand(h, w, d)\n for i in range(1, h + 1):\n for j in range(1, w + 1):\n for k in range(1, d + 1):\n actual = torch.nn.functional.avg_pool3d(input.unsqueeze(0), (i, j, k))\n actual = actual.view(1, actual.numel())\n expected = self._avg_pool3d(input, (i, j, k))\n self.assertTrue(torch.allclose(actual, expected, rtol=0, atol=1e-5))\n\n def test_doubletensor_avg_pool3d_with_divisor(self):\n h, w, d = 6, 5, 7\n input = torch.rand(h, w, d)\n for i in range(1, h + 1):\n for j in range(1, w + 1):\n for k in range(1, d + 1):\n for divisor in [1, 7, i * j]:\n actual = torch.nn.functional.avg_pool3d(input.unsqueeze(0), (i, j, k), divisor_override=divisor)\n actual = actual.view(1, actual.numel())\n expected = self._sum_pool3d(input, (i, j, k)) / divisor\n self.assertTrue(torch.allclose(actual, expected, rtol=0, atol=1e-5))\n\n def test_avg_pool3d_with_zero_divisor(self):\n self.assertRaisesRegex(RuntimeError, \"divisor must be not zero\",\n lambda: F.avg_pool3d(torch.zeros(3, 3, 3, 3), (2, 2, 2), divisor_override=0))\n\n def test_avg_pool1d_ceil_mode(self):\n # Regression test for gh-36977\n x = 10 * torch.randn((1, 16, 4))\n y = torch.nn.functional.avg_pool1d(\n x, ceil_mode=True, count_include_pad=True, kernel_size=1, stride=2)\n self.assertTrue(not torch.isnan(y).any())\n\n if TEST_CUDA:\n y = torch.nn.functional.avg_pool1d(\n x.to('cuda'), ceil_mode=True, count_include_pad=True, kernel_size=1, stride=2)\n self.assertTrue(not torch.isnan(y).any())\n\n\n def test_avg_pool2d_ceil_mode(self):\n # Regression test for gh-36977\n x = 10 * torch.randn((1, 16, 4, 4))\n y = torch.nn.functional.avg_pool2d(\n x, ceil_mode=True, count_include_pad=True, kernel_size=(1, 2),\n padding=(0, 1), stride=2)\n self.assertTrue(not torch.isnan(y).any())\n\n if TEST_CUDA:\n y = torch.nn.functional.avg_pool2d(\n x.to('cuda'), ceil_mode=True, count_include_pad=True, kernel_size=(1, 2),\n padding=(0, 1), stride=2)\n self.assertTrue(not torch.isnan(y).any())\n\n\n def test_avg_pool3d_ceil_mode(self):\n # Regression test for gh-36977\n x = 10 * torch.randn((1, 16, 4, 4, 4))\n y = torch.nn.functional.avg_pool3d(\n x, ceil_mode=True, count_include_pad=True, kernel_size=(1, 2, 3), stride=2)\n self.assertTrue(not torch.isnan(y).any())\n\n if TEST_CUDA:\n y = torch.nn.functional.avg_pool3d(\n x.to('cuda'), ceil_mode=True, count_include_pad=True, kernel_size=(1, 2, 3), stride=2)\n self.assertTrue(not torch.isnan(y).any())\n\n\nclass TestNN(NNTestCase):\n _do_cuda_memory_leak_check = True\n _do_cuda_non_default_stream = True\n\n def _forward(self, module, input: _TensorOrTensors):\n with freeze_rng_state():\n if isinstance(input, tuple):\n return module(*input)\n else:\n return module(input)\n\n def _backward(self, module, input: _TensorOrTensors, output, grad_output, create_graph=False):\n output.backward(grad_output, retain_graph=True, create_graph=create_graph)\n if isinstance(input, tuple):\n return tuple(i.grad.data if i.grad is not None else None for i in input)\n else:\n return input.grad.data if input.grad is not None else None\n\n def _forward_criterion(self, criterion, input, target, extra_args=None):\n if extra_args is None:\n extra_args = tuple()\n if isinstance(input, tuple):\n args = input + (target,) + extra_args\n output = criterion(*args)\n else:\n output = criterion(input, target, *extra_args)\n return output\n\n def _backward_criterion(self, criterion, input, output, target, gradOutput=None, extra_args=None):\n if extra_args is None:\n extra_args = tuple()\n input_tuple = input if isinstance(input, tuple) else (input,)\n output_tuple = output if isinstance(output, tuple) else (output,)\n for i in input_tuple:\n if i.grad is not None:\n i.grad.data.zero_()\n args = input_tuple + (target,) + extra_args\n if gradOutput is None:\n gradOutput = torch.ones(())\n criterion(*args).backward(gradOutput.to(output_tuple[0]))\n if isinstance(input, tuple):\n return tuple(i.grad.data for i in input)\n else:\n return input.grad.data\n\n def _zero_grad_parameters(self, module):\n for p in module.parameters():\n if p.grad is not None:\n with torch.no_grad():\n p.grad.zero_()\n p.grad.detach_()\n\n def _get_parameters(self, module):\n params = []\n d_params = []\n for p in module.parameters():\n params.append(p)\n d_params.append(p.grad)\n return params, d_params\n\n def _create_basic_net(self):\n class Layer(nn.Module):\n def __init__(self):\n super(Layer, self).__init__()\n self.layer_dummy_param = Parameter(torch.Tensor(3, 5))\n self.register_buffer('layer_dummy_buf', torch.zeros(1, 3, 3, 7))\n\n class Net(nn.Module):\n def __init__(self):\n super(Net, self).__init__()\n self.l1 = Layer()\n self.dummy_param = Parameter(torch.Tensor(3, 5))\n self.register_buffer('dummy_buf', torch.zeros(7, 3, 3, 1))\n\n l = Layer()\n n = Net()\n s = nn.Sequential(n, n)\n\n return l, n, s\n\n def test_requires_grad_(self):\n m = self._create_basic_net()[-1]\n assert len(list(m.buffers())) > 0, 'invalid test'\n assert all(not b.requires_grad for b in m.buffers()) > 0, 'invalid test'\n assert len(list(m.parameters())) > 0, 'invalid test'\n assert all(p.requires_grad for p in m.parameters()) > 0, 'invalid test'\n for requires_grad in (False, True):\n self.assertIs(m.requires_grad_(requires_grad), m)\n for p in m.parameters():\n self.assertEqual(p.requires_grad, requires_grad)\n for b in m.buffers():\n self.assertFalse(b.requires_grad)\n\n def test_module_backcompat(self):\n from torch.serialization import SourceChangeWarning\n path = download_file('https://download.pytorch.org/test_data/linear.pt')\n with warnings.catch_warnings():\n warnings.simplefilter('ignore', SourceChangeWarning)\n m = torch.load(path)\n input = torch.randn(2, 3, dtype=torch.float)\n self.assertEqual(m(input).size(), (2, 5))\n\n def test_conv_backcompat(self):\n from torch.serialization import SourceChangeWarning\n # This file was generated by running on PyTorch 1.0.1 on Python 2:\n #\n # import torch\n # from torch import nn\n # m = nn.Conv2d(1, 1, 1)\n # torch.save(m, 'legacy_conv2d.pt')\n #\n # NB: This Pickle also contains some Unicode data!\n path = download_file('https://download.pytorch.org/test_data/legacy_conv2d.pt')\n with warnings.catch_warnings():\n warnings.simplefilter('ignore', SourceChangeWarning)\n m = torch.load(path, encoding='utf-8')\n input = torch.randn((1, 1, 1, 1), dtype=torch.float)\n self.assertEqual(m(input).size(), (1, 1, 1, 1))\n\n def test_share_memory(self):\n class Net(nn.Module):\n def __init__(self):\n super(Net, self).__init__()\n self.p = nn.Parameter(torch.eye(5))\n self.par = nn.ParameterList()\n self.par.append(nn.Parameter(torch.randn(10)))\n\n def forward(self, inp):\n # NB: dead code\n return inp.clone()\n\n net = Net()\n for p in net.parameters():\n self.assertFalse(p.storage().is_shared())\n for b in net.buffers():\n self.assertFalse(b.storage().is_shared())\n net.share_memory()\n for p in net.parameters():\n self.assertTrue(p.storage().is_shared())\n for b in net.buffers():\n self.assertTrue(b.storage().is_shared())\n\n def _test_hooks(self, backward_register_fn):\n module = nn.Sigmoid()\n input = torch.ones(5, 5, requires_grad=True)\n\n counter = {\n 'forwards': 0,\n 'backwards': 0\n }\n\n def fw_hook(inc, h_module, input, output):\n self.assertIsInstance(input, tuple)\n self.assertTrue(isinstance(output, torch.Tensor))\n self.assertTrue(h_module is module)\n self.assertEqual(input[0], torch.ones(5, 5))\n self.assertEqual(output, torch.Tensor(5, 5).fill_(1 / (1 + 1 / math.e)))\n counter['forwards'] += inc\n\n def bw_hook(inc, h_module, grad_input, grad_output):\n self.assertIsInstance(grad_input, tuple)\n self.assertIsInstance(grad_output, tuple)\n self.assertTrue(h_module is module)\n self.assertEqual(grad_output[0], torch.ones(5, 5) * 2)\n counter['backwards'] += inc\n\n test_fwd = module.register_forward_hook(lambda *args: fw_hook(1, *args))\n\n module(input)\n module(input)\n self.assertEqual(counter['forwards'], 2)\n self.assertEqual(counter['backwards'], 0)\n\n test_bwd = getattr(module, backward_register_fn)(\n lambda *args: bw_hook(1, *args))\n\n output = module(input)\n self.assertEqual(counter['forwards'], 3)\n self.assertEqual(counter['backwards'], 0)\n\n output.backward(torch.ones(5, 5) * 2, retain_graph=True)\n self.assertEqual(counter['forwards'], 3)\n self.assertEqual(counter['backwards'], 1)\n\n output.backward(torch.ones(5, 5) * 2, retain_graph=True)\n self.assertEqual(counter['forwards'], 3)\n self.assertEqual(counter['backwards'], 2)\n\n test2_fwd = module.register_forward_hook(lambda *args: fw_hook(2, *args))\n\n output = module(input)\n self.assertEqual(counter['forwards'], 6)\n self.assertEqual(counter['backwards'], 2)\n\n test2_bwd = getattr(module, backward_register_fn)(lambda *args: bw_hook(2, *args))\n\n module(input).backward(torch.ones(5, 5) * 2)\n self.assertEqual(counter['forwards'], 9)\n self.assertEqual(counter['backwards'], 5)\n\n test2_bwd.remove()\n\n module(input).backward(torch.ones(5, 5) * 2)\n self.assertEqual(counter['forwards'], 12)\n self.assertEqual(counter['backwards'], 6)\n\n test2_fwd.remove()\n\n module(input).backward(torch.ones(5, 5) * 2)\n self.assertEqual(counter['forwards'], 13)\n self.assertEqual(counter['backwards'], 7)\n\n test_fwd.remove()\n test_bwd.remove()\n\n def test_hooks(self):\n self._test_hooks(\"register_backward_hook\")\n self._test_hooks(\"register_full_backward_hook\")\n\n def test_hook_cpp(self):\n bn = nn.BatchNorm1d(5)\n\n def hook(module, grad_inputs, grad_outputs):\n self.assertEqual(len(grad_inputs), 1)\n self.assertEqual(len(grad_outputs), 1)\n self.assertEqual(module, bn)\n\n bn.register_full_backward_hook(hook)\n output = bn(torch.randn(5, 5, requires_grad=True))\n output.sum().backward()\n\n def test_hook_invalid_outputs(self):\n module = nn.Sigmoid()\n input = torch.randn(5, 5, requires_grad=True)\n\n def bw_fail1(self, grad_input, grad_output):\n return grad_input[:-1]\n\n def bw_fail2(self, grad_input, grad_output):\n return grad_input + (torch.randn(2, 2),)\n\n with module.register_backward_hook(bw_fail1):\n with self.assertRaisesRegex(RuntimeError, 'got 0, but expected 1'):\n module(input).sum().backward()\n\n with module.register_backward_hook(bw_fail2):\n with self.assertRaisesRegex(RuntimeError, 'got 2, but expected 1'):\n module(input).sum().backward()\n\n def test_hook_requires_grad(self):\n test_self = self\n\n class MyModule(nn.Module):\n def forward(self, arg1, arg2, arg3):\n test_self.assertTrue(arg1.requires_grad)\n test_self.assertFalse(arg2.requires_grad)\n test_self.assertTrue(arg3.requires_grad)\n return arg1.sum() + arg2.sum() + arg3.sum()\n\n inp = torch.rand(2, requires_grad=True)\n mod = MyModule()\n\n mod(inp, inp.detach(), inp)\n # Ensure that requires grad is properly propagated\n mod.register_full_backward_hook(lambda mod, gI, gO: None)\n mod(inp, inp.detach(), inp)\n\n def test_hook_extra_input(self):\n class MyModule(nn.Module):\n def forward(self, non_tensor, tensor):\n return tensor.clone(), non_tensor\n\n inp = torch.rand(2, requires_grad=True)\n mod = MyModule()\n\n def hook(mod, grad_input, grad_output):\n self.assertIsNone(grad_input[0])\n self.assertIsInstance(grad_input[1], torch.Tensor)\n\n self.assertIsInstance(grad_output[0], torch.Tensor)\n self.assertIsNone(grad_output[1])\n\n mod.register_full_backward_hook(hook)\n out, _ = mod(True, inp)\n out.sum().backward()\n\n def test_hook_inplace(self):\n class MyModule(nn.Module):\n def forward(self, inp, do_inplace):\n self.inp = inp\n if do_inplace:\n inp += 1\n return inp.clone()\n\n hook_called = [0]\n\n def hook(mod, grad_input, grad_output):\n hook_called[0] += 1\n\n inp = torch.rand(10, requires_grad=True)\n mod = MyModule()\n mod.register_full_backward_hook(hook)\n\n # No inplace should work\n mod(inp, False).sum().backward()\n self.assertEqual(hook_called[0], 1)\n\n # Input inplace error should throw an error (warning during deprecation cycle)\n with self.assertWarnsRegex(UserWarning, \"Output 0 of BackwardHookFunctionBackward is \"\n \"a view and is being modified inplace.\"):\n mod(inp.clone(), True)\n\n # Input inplace error should throw an error if we try to re-use the view after they have\n # been modified (warning during deprecation cycle)\n local_inp = inp.clone()\n out = mod(local_inp, False)\n local_inp[0] *= 1\n with self.assertWarnsRegex(UserWarning, \"Output 0 of BackwardHookFunctionBackward is \"\n \"a view and its base or another view\"):\n # Any operation involving the view will fail here\n mod.inp + 2\n\n # Output inplace error should throw an error (warning during deprecation cycle)\n with self.assertWarnsRegex(UserWarning, \"BackwardHookFunctionBackward is a view \"\n \"and is being modified inplace.\"):\n # This error won't happen once the warning above is a proper error\n with self.assertRaisesRegex(RuntimeError, \"Module backward hook for grad_input is \"\n \"called before the grad_output one.\"):\n out = mod(inp, False)\n out += 1\n out.sum().backward()\n\n def test_hook_non_full_warning(self):\n def noop(*args):\n pass\n\n a = torch.rand(2, requires_grad=True)\n b = torch.rand(2, requires_grad=True)\n\n # Check invalid input container\n class MyModule(nn.Module):\n def forward(self, l):\n return l[0].clone(), l[1].clone()\n\n m = MyModule()\n m.register_backward_hook(noop)\n\n with self.assertWarnsRegex(UserWarning, \"does not take as input a single Tensor or a tuple of Tensors\"):\n m([a, b])\n\n # Check invalid output container\n class MyModule(nn.Module):\n def forward(self, a, b):\n return [a.clone(), b.clone()]\n\n m = MyModule()\n m.register_backward_hook(noop)\n\n with self.assertWarnsRegex(UserWarning, \"does not return a single Tensor or a tuple of Tensors\"):\n m(a, b)\n\n # Check invalid output from different Nodes\n class MyModule(nn.Module):\n def forward(self, a, b):\n return a.clone(), b.clone()\n\n m = MyModule()\n m.register_backward_hook(noop)\n\n with self.assertWarnsRegex(UserWarning, \"outputs are generated by different autograd Nodes\"):\n m(a, b)\n\n # Check invalid forward with multiple Nodes\n class MyModule(nn.Module):\n def forward(self, a):\n return a.clone().clone()\n\n m = MyModule()\n m.register_backward_hook(noop)\n\n with self.assertWarnsRegex(UserWarning, \"the forward contains multiple autograd Nodes\"):\n m(a)\n\n def test_hook_backward_size(self):\n # Make module with multiple operations in forward\n # And different size for input and outputs\n class MyModule(nn.Module):\n def forward(self, arg1, arg2):\n tmp = arg1.sum() * arg2\n tmp = tmp + arg2.sum() * arg1.sum()\n tmp = tmp.sum().view(1)\n tmp = tmp.expand(8).contiguous()\n return tmp\n\n module = MyModule()\n inp1 = torch.randn(5, 5, requires_grad=True)\n inp2 = torch.randn(10, 10, requires_grad=True)\n\n def bw_hook(module, grad_input, grad_output):\n self.assertEqual(len(grad_input), 2)\n self.assertEqual(grad_input[0].size(), torch.Size([5, 5]))\n self.assertEqual(grad_input[1].size(), torch.Size([10, 10]))\n self.assertEqual(len(grad_output), 1)\n self.assertEqual(grad_output[0].size(), torch.Size([8]))\n\n with module.register_full_backward_hook(bw_hook):\n module(inp1, inp2).sum().backward()\n\n def test_hook_backward_writeable(self):\n module = nn.Sigmoid()\n input = torch.randn(5, 5, requires_grad=True)\n sig_x = torch.nn.functional.sigmoid(input)\n\n def bw_hook(module, grad_input, grad_output):\n for grad in grad_input:\n self.assertTrue(isinstance(grad, torch.Tensor))\n for grad in grad_output:\n self.assertTrue(isinstance(grad, torch.Tensor))\n return tuple(gi * 2 for gi in grad_input)\n\n module.register_backward_hook(bw_hook)\n module(input).backward(torch.ones(5, 5))\n expected_grad = sig_x * (1 - sig_x) * 2\n self.assertEqual(input.grad, expected_grad)\n\n def test_hook_forward_preforward_writable(self):\n module = nn.Sigmoid()\n input = torch.randn(5, 5, requires_grad=True)\n sig_x = torch.nn.functional.sigmoid(input)\n\n def forward_pre_hook(m, input):\n return torch.nn.functional.relu(input[0])\n\n def forward_hook(m, input, output):\n return -output\n\n module.register_forward_pre_hook(forward_pre_hook)\n module.register_forward_hook(forward_hook)\n output = module(input)\n expected_res = -torch.nn.functional.sigmoid(torch.nn.functional.relu(input))\n self.assertEqual(output, expected_res)\n output.backward(torch.ones(5, 5) * 2, retain_graph=True)\n mask = (input > 0).double()\n expected_grad = -sig_x * (1 - sig_x) * 2 * mask\n self.assertEqual(input.grad, expected_grad)\n\n def test_to(self):\n m = nn.Linear(3, 5)\n self.assertIs(m, m.to('cpu'))\n self.assertIs(m, m.to('cpu', dtype=torch.float32))\n self.assertEqual(m.double(), m.to(torch.float64))\n self.assertRaises(RuntimeError, lambda: m.to('cpu', copy=True))\n\n if torch.cuda.is_available():\n for cuda in ['cuda', 'cuda:0' if torch.cuda.device_count() == 1 else 'cuda:1']:\n m2 = m.cuda(device=cuda)\n self.assertIs(m2, m2.to(cuda))\n self.assertEqual(m, m2.to('cpu'))\n self.assertEqual(m2, m.to(cuda))\n self.assertIs(m2, m2.to(dtype=torch.float32))\n self.assertEqual(m2.double(), m2.to(dtype=torch.float64))\n\n def test_zero_grad(self):\n i = torch.randn(2, 5, requires_grad=True)\n module = nn.Linear(5, 5)\n for p in module.parameters():\n p.requires_grad = False\n module.zero_grad()\n\n module.weight.requires_grad = True\n module.zero_grad()\n self.assertIsNone(module.weight.grad) # uninitialized grad\n\n module(i).sum().backward()\n self.assertIsNotNone(module.weight.grad)\n self.assertGreater(module.weight.grad.data.abs().sum(), 0)\n module.zero_grad()\n self.assertEqual(module.weight.grad.data, module.weight.data.clone().zero_())\n\n module.bias.requires_grad = True\n module.zero_grad()\n self.assertIsNotNone(module.weight.grad)\n self.assertIsNone(module.bias.grad)\n module(i).sum().backward()\n self.assertIsNotNone(module.weight.grad)\n self.assertIsNotNone(module.bias.grad)\n self.assertGreater(module.weight.grad.data.abs().sum(), 0)\n self.assertGreater(module.bias.grad.data.abs().sum(), 0)\n module.zero_grad()\n self.assertEqual(module.weight.grad.data, module.weight.data.clone().zero_())\n self.assertEqual(module.bias.grad.data, module.bias.data.clone().zero_())\n\n # Force set to None.\n module.zero_grad(set_to_none=True)\n self.assertIsNone(module.weight.grad)\n\n\n def test_no_grad(self):\n for dtype in [torch.bfloat16, torch.float, torch.double]:\n module = nn.Conv2d(2, 5, kernel_size=3, padding=1).to(dtype)\n input = torch.randn(1, 2, 10, 10).to(dtype)\n x = input\n y = input.clone()\n\n output = module(x)\n self.assertTrue(output.requires_grad)\n output.backward(torch.ones(1, 5, 10, 10))\n\n with torch.no_grad():\n output2 = module(y)\n self.assertFalse(output2.requires_grad)\n self.assertRaises(RuntimeError, lambda: output2.backward(torch.ones(1, 5, 10, 10)))\n\n def test_invalid_conv1d(self):\n for dtype in [torch.bfloat16, torch.float, torch.double]:\n module = nn.Conv1d(in_channels=3, out_channels=33, kernel_size=10, stride=1, bias=True).to(dtype)\n input = torch.randn(1, 3, 4).to(dtype)\n with self.assertRaisesRegex(RuntimeError,\n r'Calculated padded input size per channel: \\(4\\). ' +\n r'Kernel size: \\(10\\). Kernel size can\\'t be greater than actual input size'):\n module(input)\n\n # Negative stride check\n module = nn.Conv1d(in_channels=3, out_channels=6, kernel_size=3, stride=-1, bias=True).to(dtype)\n input = torch.randn(1, 3, 4).to(dtype)\n with self.assertRaisesRegex(RuntimeError, 'non-positive stride is not supported'):\n module(input)\n\n def test_mismatch_shape_conv2d(self):\n x = torch.randn(1, 10, 1, 28, 28)\n w = torch.randn(6, 1, 5, 5)\n\n with self.assertRaisesRegex(RuntimeError,\n r'Expected 4-dimensional input for 4-dimensional weight \\[6, 1, 5, 5\\],' +\n r' but got 5-dimensional input of size \\[1, 10, 1, 28, 28\\] instead'):\n\n F.conv2d(x, w)\n\n def test_invalid_conv2d(self):\n for dtype in [torch.bfloat16, torch.float, torch.double]:\n module = torch.nn.Conv2d(1, 1, kernel_size=3, dilation=2, stride=2).to(dtype)\n input = torch.empty(1, 1, 4, 4).to(dtype)\n self.assertRaises(RuntimeError, lambda: module(input))\n\n module = nn.Conv2d(in_channels=3, out_channels=33, kernel_size=10, stride=1, bias=True)\n input = torch.randn(1, 3, 1, 1)\n with self.assertRaisesRegex(RuntimeError,\n r'Calculated padded input size per channel: \\(1 x 1\\). ' +\n r'Kernel size: \\(10 x 10\\). Kernel size can\\'t be greater than actual input size'):\n module(input)\n\n # Negative stride check\n module = nn.Conv2d(in_channels=3, out_channels=6, kernel_size=4, stride=-1, bias=True).to(dtype)\n input = torch.randn(1, 3, 4, 4).to(dtype)\n with self.assertRaisesRegex(RuntimeError, 'non-positive stride is not supported'):\n module(input)\n\n # Zero stride check\n module = nn.Conv2d(in_channels=3, out_channels=6, kernel_size=4, stride=0, bias=True).to(dtype)\n input = torch.randn(1, 3, 4, 4).to(dtype)\n with self.assertRaisesRegex(RuntimeError, 'non-positive stride is not supported'):\n module(input)\n\n def test_invalid_conv3d(self):\n for dtype in [torch.bfloat16, torch.float, torch.double]:\n module = torch.nn.Conv3d(1, 1, kernel_size=3, dilation=2, stride=2).to(dtype)\n input = torch.empty(1, 1, 4, 4, 4).to(dtype)\n self.assertRaises(RuntimeError, lambda: module(input))\n\n # Negative stride check\n module = torch.nn.Conv3d(1, 1, kernel_size=3, stride=-2)\n input = torch.empty(1, 1, 4, 4, 4)\n with self.assertRaisesRegex(RuntimeError, 'non-positive stride is not supported'):\n module(input)\n\n def test_Conv1d_module_same_padding(self):\n # Compare module against functional: without strides/dilation, asymmetric padding\n x = torch.rand(1, 1, 20)\n module = nn.Conv1d(in_channels=1, out_channels=1, kernel_size=10,\n padding='same')\n expect = F.conv1d(x, module.weight, module.bias, padding='same')\n self.assertEqual(expect, module(x))\n\n # Test dilation, symmetric padding\n module = nn.Conv1d(in_channels=1, out_channels=1, kernel_size=10,\n padding='same', dilation=2)\n expect = F.conv1d(x, module.weight, module.bias, padding='same', dilation=2)\n self.assertEqual(expect, module(x))\n\n # Test non-zero padding_mode, requiring explicit padding\n module = nn.Conv1d(in_channels=1, out_channels=1, kernel_size=10,\n padding='same', padding_mode='replicate')\n x_padded = F.pad(x, [4, 5], mode='replicate')\n expect = F.conv1d(x_padded, module.weight, module.bias, padding='valid')\n self.assertEqual(expect, module(x))\n self.assertEqual(x.size(), expect.size())\n\n # Test connstruction with invalid padding string raises\n with self.assertRaisesRegex(ValueError, 'Invalid padding string'):\n module = nn.Conv1d(in_channels=3, out_channels=33, kernel_size=10, padding='foo')\n\n # Test connstruction with same padding and strides raises\n with self.assertRaisesRegex(ValueError, \"padding='same'\"):\n module = nn.Conv1d(in_channels=3, out_channels=33, kernel_size=10, padding='same', stride=2)\n\n def test_Conv2d_module_same_padding(self):\n # Compare module against functional:\n # without strides/dilation, both symmetric and asymmetric padding\n x = torch.rand(1, 1, 9, 20)\n module = nn.Conv2d(in_channels=1, out_channels=1, kernel_size=(5, 10),\n padding='same')\n expect = F.conv2d(x, module.weight, module.bias, padding='same')\n self.assertEqual(expect, module(x))\n\n # with dilation, symmetric padding\n module = nn.Conv2d(in_channels=1, out_channels=1, kernel_size=(3, 4),\n padding='same', dilation=(1, 2))\n expect = F.conv2d(x, module.weight, module.bias, padding='same', dilation=(1, 2))\n self.assertEqual(expect, module(x))\n\n # Test non-zero padding_mode, requiring explicit padding\n module = nn.Conv2d(in_channels=1, out_channels=1, kernel_size=(3, 4),\n padding='same', padding_mode='reflect')\n x_padded = F.pad(x, [1, 2, 1, 1], mode='reflect')\n expect = F.conv2d(x_padded, module.weight, module.bias, padding='valid')\n self.assertEqual(expect, module(x))\n self.assertEqual(x.size(), expect.size())\n\n # Test connstruction with invalid padding string raises\n with self.assertRaisesRegex(ValueError, 'Invalid padding string'):\n module = nn.Conv2d(in_channels=3, out_channels=33, kernel_size=10, padding='foo')\n\n # Test connstruction with same padding and strides raises\n with self.assertRaisesRegex(ValueError, \"padding='same'\"):\n module = nn.Conv2d(in_channels=3, out_channels=33, kernel_size=10, padding='same', stride=2)\n with self.assertRaisesRegex(ValueError, \"padding='same'\"):\n module = nn.Conv2d(in_channels=3, out_channels=33, kernel_size=10, padding='same', stride=(1, 3))\n with self.assertRaisesRegex(ValueError, \"padding='same'\"):\n module = nn.Conv2d(in_channels=3, out_channels=33, kernel_size=10, padding='same', stride=(4, 1))\n\n def test_Conv3d_module_same_padding(self):\n # Compare module against functional:\n x = torch.rand(1, 1, 4, 4, 4)\n # without dilation, both symmetric and asymmetric padding\n module = nn.Conv3d(in_channels=1, out_channels=1, kernel_size=(2, 3, 4),\n padding='same')\n expect = F.conv3d(x, module.weight, module.bias, padding='same')\n self.assertEqual(expect, module(x))\n\n # with dilation, both symmetric and asymmetric padding\n module = nn.Conv3d(in_channels=1, out_channels=1, kernel_size=(2, 3, 4),\n padding='same', dilation=(3, 2, 1))\n expect = F.conv3d(x, module.weight, module.bias, padding='same', dilation=(3, 2, 1))\n self.assertEqual(expect, module(x))\n\n # Test non-zero padding_mode, requiring explicit padding\n module = nn.Conv3d(in_channels=1, out_channels=1, kernel_size=(2, 3, 4),\n padding='same', padding_mode='circular')\n x_padded = F.pad(x, [1, 2, 1, 1, 0, 1], mode='circular')\n expect = F.conv3d(x_padded, module.weight, module.bias, padding='valid')\n self.assertEqual(expect, module(x))\n self.assertEqual(x.size(), expect.size())\n\n # Test connstruction with invalid padding string raises\n with self.assertRaisesRegex(ValueError, 'Invalid padding string'):\n module = nn.Conv3d(in_channels=3, out_channels=33, kernel_size=10, padding='foo')\n\n # Test connstruction with same padding and strides raises\n with self.assertRaisesRegex(ValueError, \"padding='same'\"):\n module = nn.Conv2d(in_channels=3, out_channels=33, kernel_size=10, padding='same', stride=2)\n with self.assertRaisesRegex(ValueError, \"padding='same'\"):\n module = nn.Conv2d(in_channels=3, out_channels=33, kernel_size=10, padding='same', stride=(1, 1, 3))\n with self.assertRaisesRegex(ValueError, \"padding='same'\"):\n module = nn.Conv2d(in_channels=3, out_channels=33, kernel_size=10, padding='same', stride=(1, 4, 1))\n with self.assertRaisesRegex(ValueError, \"padding='same'\"):\n module = nn.Conv2d(in_channels=3, out_channels=33, kernel_size=10, padding='same', stride=(5, 1, 1))\n\n def _test_alpha_dropout(self, cls, input):\n mean = input.mean()\n std = input.std()\n\n for p in [0.2, 0.5, 0.8]:\n module = cls(p)\n input_var = input.detach().clone().requires_grad_()\n output = module(input_var)\n # output mean should be close to input mean\n self.assertLess(abs(output.data.mean() - mean), 0.1)\n # output std should be close to input std\n self.assertLess(abs(output.data.std() - std), 0.1)\n output.backward(input)\n\n def test_parameters_and_named_parameters(self):\n def names(named_parameters):\n return [k for k, _ in named_parameters]\n\n l, n, s = self._create_basic_net()\n\n self.assertEqual(len(list(l.parameters())), 1)\n self.assertEqual(\n names(l.named_parameters()),\n ['layer_dummy_param'])\n\n self.assertEqual(len(list(n.parameters())), 2)\n self.assertEqual(\n names(n.named_parameters()),\n ['dummy_param', 'l1.layer_dummy_param'])\n\n self.assertEqual(len(list(n.parameters(recurse=False))), 1)\n self.assertEqual(\n names(n.named_parameters(recurse=False)),\n ['dummy_param'])\n\n self.assertEqual(len(list(s.parameters())), 2)\n self.assertEqual(\n names(s.named_parameters()),\n ['0.dummy_param', '0.l1.layer_dummy_param'])\n\n def test_buffers_and_named_buffers(self):\n def names(named_buffers):\n return [k for k, _ in named_buffers]\n\n l, n, s = self._create_basic_net()\n\n self.assertEqual(len(list(l.buffers())), 1)\n self.assertEqual(\n names(l.named_buffers()),\n ['layer_dummy_buf'])\n\n self.assertEqual(len(list(n.buffers())), 2)\n self.assertEqual(\n names(n.named_buffers()),\n ['dummy_buf', 'l1.layer_dummy_buf'])\n\n self.assertEqual(len(list(n.buffers(recurse=False))), 1)\n self.assertEqual(\n names(n.named_buffers(recurse=False)),\n ['dummy_buf'])\n\n self.assertEqual(len(list(s.buffers())), 2)\n self.assertEqual(\n names(s.named_buffers()),\n ['0.dummy_buf', '0.l1.layer_dummy_buf'])\n\n def test_call_supports_python_dict_output(self):\n class Net(nn.Module):\n def __init__(self):\n super(Net, self).__init__()\n self.l1 = nn.Linear(10, 20)\n self.register_backward_hook(self.hook)\n self.check_backward_hook_flag = False\n\n def hook(self, module, grad_out, grad_in):\n self.check_backward_hook_flag = True\n\n def forward(self, inputs):\n return {\"output\": self.l1(inputs).sum()}\n\n net = Net()\n model_output = net(torch.randn([5, 10]))\n model_output[\"output\"].backward()\n self.assertTrue(net.check_backward_hook_flag)\n\n def test_children(self):\n l1 = nn.Linear(2, 2)\n l2 = nn.Linear(2, 2)\n l3 = nn.Linear(2, 2)\n l4 = nn.Linear(2, 2)\n subnet = nn.Sequential(l3, l4)\n s = nn.Sequential(l1, l2, l1, l2, subnet)\n self.assertEqual(list(s.children()), [l1, l2, subnet])\n\n def test_dir(self):\n linear = nn.Linear(2, 2)\n linear._test_submodule = nn.Linear(2, 2)\n linear._test_parameter = Parameter(torch.Tensor(2, 2))\n linear.register_buffer('_test_buffer', torch.Tensor(2, 2))\n keys = dir(linear)\n self.assertIn('_test_submodule', keys)\n self.assertIn('_test_parameter', keys)\n self.assertIn('_test_buffer', keys)\n\n for key in keys:\n self.assertTrue(hasattr(linear, key))\n\n def test_repr(self):\n # no extra information or sub-modules\n empty_sequential = nn.Sequential()\n expected_repr_empty = 'Sequential()'\n self.assertEqual(repr(empty_sequential), expected_repr_empty)\n\n # one liner extra information\n linear = nn.Linear(1, 1)\n expected_repr_linear = 'Linear(in_features=1, out_features=1, bias=True)'\n self.assertEqual(repr(linear), expected_repr_linear)\n\n # sub-modules repr\n sequential = nn.Sequential(linear)\n expected_repr_sequential = 'Sequential(\\n' \\\n ' (0): Linear(in_features=1, out_features=1, bias=True)\\n' \\\n ')'\n self.assertEqual(repr(sequential), expected_repr_sequential)\n\n def test_dir_digit(self):\n model = nn.Sequential(nn.Linear(2, 2))\n keys = dir(model)\n self.assertNotIn('0', keys)\n\n def test_named_children(self):\n l1 = nn.Linear(2, 2)\n l2 = nn.Linear(2, 2)\n l3 = nn.Linear(2, 2)\n l4 = nn.Linear(2, 2)\n subnet = nn.Sequential(l3, l4)\n s = nn.Sequential()\n with self.assertRaises(KeyError):\n s.add_module('', l1)\n with self.assertRaises(KeyError):\n s.add_module('name.with.dot', l1)\n s.add_module('layer1', l1)\n s.add_module('layer2', l2)\n s.add_module('layer3', l1)\n s.add_module('layer4', l2)\n s.add_module('subnet', subnet)\n self.assertEqual(list(s.named_children()), [('layer1', l1), ('layer2', l2), ('subnet', subnet)])\n\n def test_modules(self):\n class Net(nn.Module):\n def __init__(self):\n super(Net, self).__init__()\n self.l1 = l\n self.l2 = l\n self.param = torch.empty(3, 5)\n\n l = nn.Linear(10, 20)\n n = Net()\n s = nn.Sequential(n, n, n, n)\n self.assertEqual(list(s.modules()), [s, n, l])\n\n def test_named_modules(self):\n class Net(nn.Module):\n def __init__(self):\n super(Net, self).__init__()\n self.l1 = l\n self.l2 = l\n self.param = torch.empty(3, 5)\n self.block = block\n l = nn.Linear(10, 20)\n l1 = nn.Linear(10, 20)\n l2 = nn.Linear(10, 20)\n block = nn.Sequential()\n block.add_module('linear1', l1)\n block.add_module('linear2', l2)\n n = Net()\n s = nn.Sequential(n, n, n, n)\n self.assertEqual(list(s.named_modules()), [('', s), ('0', n), ('0.l1', l),\n ('0.block', block), ('0.block.linear1', l1),\n ('0.block.linear2', l2)])\n\n def test_register_buffer_raises_error_if_name_is_not_string(self):\n m = nn.Module()\n expected_error = 'buffer name should be a string. Got '\n with self.assertRaisesRegex(TypeError, expected_error + 'int'):\n m.register_buffer(1, torch.rand(5))\n with self.assertRaisesRegex(TypeError, expected_error + 'NoneType'):\n m.register_buffer(None, torch.rand(5))\n\n def test_register_buffer_raises_error_if_attr_exists(self):\n m = nn.Module()\n m.attribute_name = 5\n with self.assertRaises(KeyError):\n m.register_buffer('attribute_name', torch.rand(5))\n\n del m.attribute_name\n m.register_parameter('attribute_name', nn.Parameter())\n with self.assertRaises(KeyError):\n m.register_buffer('attribute_name', torch.rand(5))\n\n del m.attribute_name\n m.add_module('attribute_name', nn.Module())\n with self.assertRaises(KeyError):\n m.register_buffer('attribute_name', torch.rand(5))\n\n def test_register_buffer_raises_error_if_not_tensor(self):\n m = nn.Module()\n with self.assertRaises(TypeError):\n m.register_buffer('attribute_name', 5)\n\n def test_register_buffer_allows_overwriting_with_same_name(self):\n m = nn.Module()\n buffer1 = torch.rand(5)\n buffer2 = buffer1 + 5\n buffer3 = None\n m.register_buffer('buffer_name', buffer1)\n self.assertEqual(m.buffer_name, buffer1)\n m.register_buffer('buffer_name', buffer2)\n self.assertEqual(m.buffer_name, buffer2)\n m.register_buffer('buffer_name', buffer3)\n self.assertEqual(m.buffer_name, buffer3)\n\n def test_buffer_not_persistent(self):\n m = nn.Module()\n m.register_buffer('buf', torch.rand(5), persistent=False)\n self.assertTrue(len(list(m.buffers())) == 1)\n self.assertTrue(len(m.state_dict()) == 0)\n\n def test_buffer_not_persistent_del(self):\n m = nn.Module()\n m.register_buffer('buf', torch.rand(5), persistent=False)\n del m.buf\n self.assertTrue(len(list(m.buffers())) == 0)\n\n def test_buffer_not_persistent_overwrite(self):\n m = nn.Module()\n m.register_buffer('buf', torch.rand(5), persistent=False)\n m.register_buffer('buf', torch.rand(5))\n\n # can we overwrite a non-persistent buffer with a persistent one?\n self.assertTrue(len(list(m.buffers())) == 1)\n self.assertTrue(len(m.state_dict()) == 1)\n\n # can we overwrite a persistent buffer with a non-persistent one?\n m.register_buffer('buf', torch.rand(5), persistent=False)\n self.assertTrue(len(list(m.buffers())) == 1)\n self.assertTrue(len(m.state_dict()) == 0)\n\n def test_buffer_not_persistent_assign(self):\n m = nn.Module()\n m.register_buffer('buf', torch.rand(5), persistent=False)\n\n # Assigning None removes the buffer but if we then assign a new Tensor\n # to the same property, it should still be marked as a buffer.\n m.buf = None\n self.assertTrue(len(list(m.buffers())) == 0)\n self.assertTrue(len(m.state_dict()) == 0)\n m.buf = torch.rand(5)\n self.assertTrue(len(list(m.buffers())) == 1)\n self.assertTrue(len(m.state_dict()) == 0)\n\n # Assigning a Parameter removes the buffer.\n m.buf = nn.Parameter(torch.rand(5))\n self.assertTrue(len(list(m.buffers())) == 0)\n self.assertTrue(len(m.state_dict()) == 1)\n\n def test_buffer_not_persistent_load(self):\n m = nn.Module()\n m.register_buffer('buf', torch.rand(5), persistent=False)\n m.load_state_dict({})\n\n def test_register_parameter_raises_error_if_name_is_not_string(self):\n m = nn.Module()\n expected_error = 'parameter name should be a string. Got '\n with self.assertRaisesRegex(TypeError, expected_error + 'int'):\n m.register_parameter(1, nn.Parameter())\n with self.assertRaisesRegex(TypeError, expected_error + 'NoneType'):\n m.register_parameter(None, nn.Parameter())\n\n def test_register_parameter_raises_error_if_attr_exists(self):\n m = nn.Module()\n m.attribute_name = 5\n with self.assertRaises(KeyError):\n m.register_parameter('attribute_name', nn.Parameter())\n\n del m.attribute_name\n m.register_buffer('attribute_name', torch.rand(5))\n with self.assertRaises(KeyError):\n m.register_parameter('attribute_name', nn.Parameter())\n\n del m.attribute_name\n m.add_module('attribute_name', nn.Module())\n with self.assertRaises(KeyError):\n m.register_parameter('attribute_name', nn.Parameter())\n\n def test_register_parameter_allows_overwriting_with_same_name(self):\n m = nn.Module()\n param1 = nn.Parameter(torch.rand(5))\n param2 = nn.Parameter(param1.data + 5)\n param3 = None\n m.register_parameter('param_name', param1)\n self.assertEqual(m.param_name, param1)\n m.register_parameter('param_name', param2)\n self.assertEqual(m.param_name, param2)\n m.register_parameter('param_name', param3)\n self.assertEqual(m.param_name, param3)\n\n def test_add_module_raises_error_if_attr_exists(self):\n m = nn.Module()\n m.attribute_name = 5\n with self.assertRaises(KeyError):\n m.add_module('attribute_name', nn.Module())\n\n del m.attribute_name\n m.register_buffer('attribute_name', torch.rand(5))\n with self.assertRaises(KeyError):\n m.add_module('attribute_name', nn.Module())\n\n del m.attribute_name\n m.register_parameter('attribute_name', nn.Parameter())\n with self.assertRaises(KeyError):\n m.add_module('attribute_name', nn.Module())\n\n @unittest.expectedFailure\n def test_getattr_with_property(self):\n class Model(nn.Module):\n @property\n def some_property(self):\n return self.something_that_doesnt_exist\n\n model = Model()\n\n with self.assertRaisesRegex(\n AttributeError,\n r\"'Model' object has no attribute 'something_that_doesnt_exist'\"):\n model.some_property\n\n def test_Sequential_getitem(self):\n l1 = nn.Linear(10, 20)\n l2 = nn.Linear(20, 30)\n l3 = nn.Linear(30, 40)\n l4 = nn.Linear(40, 50)\n n = nn.Sequential(l1, l2, l3, l4)\n self.assertIs(n[0], l1)\n self.assertIs(n[1], l2)\n self.assertIs(n[2], l3)\n self.assertIs(n[3], l4)\n self.assertIs(n[torch.tensor(3, dtype=torch.int64)], l4)\n self.assertEqual(n[1:], nn.Sequential(l2, l3, l4))\n self.assertEqual(n[3:], nn.Sequential(l4))\n self.assertEqual(n[:-1], nn.Sequential(l1, l2, l3))\n self.assertEqual(n[:-3], nn.Sequential(l1))\n self.assertEqual(n[::-1], nn.Sequential(l4, l3, l2, l1))\n\n def test_Sequential_setitem(self):\n l1 = nn.Linear(10, 20)\n l2 = nn.Linear(20, 30)\n l3 = nn.Linear(30, 40)\n l4 = nn.Linear(40, 50)\n n = nn.Sequential(l1, l2, l3)\n n[0] = l4\n n[-1] = l4\n n[torch.tensor(1, dtype=torch.int16)] = l1\n self.assertIs(n[0], l4)\n self.assertIs(n[1], l1)\n self.assertIs(n[2], l4)\n\n def test_Sequential_setitem_named(self):\n l1 = nn.Linear(10, 20)\n l2 = nn.Linear(20, 30)\n l3 = nn.Linear(30, 40)\n l4 = nn.Linear(40, 50)\n n = nn.Sequential(OrderedDict([\n ('linear1', l1),\n ('linear2', l2),\n ('linear3', l3),\n ]))\n\n n[0] = l4\n n[-1] = l4\n self.assertEqual(n.linear1, l4)\n self.assertEqual(n.linear3, l4)\n\n def test_Sequential_delitem(self):\n l1 = nn.Linear(10, 20)\n l2 = nn.Linear(20, 30)\n l3 = nn.Linear(30, 40)\n l4 = nn.Linear(40, 50)\n n = nn.Sequential(l1, l2, l3, l4)\n del n[-1]\n self.assertEqual(n, nn.Sequential(l1, l2, l3))\n del n[1::2]\n self.assertEqual(n, nn.Sequential(l1, l3))\n\n def test_ModuleList(self):\n modules = [nn.ReLU(), nn.Linear(5, 5)]\n module_list = nn.ModuleList(modules)\n\n def check():\n self.assertEqual(len(module_list), len(modules))\n for m1, m2 in zip(modules, module_list):\n self.assertIs(m1, m2)\n for m1, m2 in zip(modules, module_list.children()):\n self.assertIs(m1, m2)\n for i in range(len(modules)):\n self.assertIs(module_list[i], modules[i])\n\n check()\n modules += [nn.Conv2d(3, 4, 3)]\n module_list += [modules[-1]]\n check()\n modules.insert(1, nn.Linear(3, 2))\n module_list.insert(1, modules[1])\n check()\n modules.append(nn.Tanh())\n module_list.append(modules[-1])\n check()\n next_modules = [nn.Linear(5, 5), nn.Sigmoid()]\n modules.extend(next_modules)\n module_list.extend(next_modules)\n check()\n modules[2] = nn.Conv2d(5, 3, 2)\n module_list[2] = modules[2]\n check()\n modules[-1] = nn.Conv2d(5, 2, 1)\n module_list[-1] = modules[-1]\n check()\n idx = torch.tensor(2, dtype=torch.int32)\n modules[2] = nn.Conv2d(5, 3, 2)\n module_list[idx] = modules[2]\n self.assertIs(module_list[idx], modules[2])\n check()\n self.assertEqual(module_list[1:], nn.ModuleList(modules[1:]))\n self.assertEqual(module_list[3:], nn.ModuleList(modules[3:]))\n self.assertEqual(module_list[:-1], nn.ModuleList(modules[:-1]))\n self.assertEqual(module_list[:-3], nn.ModuleList(modules[:-3]))\n self.assertEqual(module_list[::-1], nn.ModuleList(modules[::-1]))\n del module_list[-1]\n self.assertEqual(module_list, nn.ModuleList(modules[:-1]))\n del module_list[1::2]\n self.assertEqual(module_list, nn.ModuleList(modules[:-1][0::2]))\n\n with self.assertRaises(TypeError):\n module_list += nn.ReLU()\n with self.assertRaises(TypeError):\n module_list.extend(nn.ReLU())\n\n l1 = nn.Linear(1, 2)\n l2 = nn.Linear(2, 3)\n l3 = nn.Linear(3, 2)\n l4 = nn.Linear(2, 3)\n subnet = nn.Sequential(l3, l4)\n s = nn.Sequential(\n OrderedDict([\n (\"layer1\", l1),\n (\"layer2\", l2),\n (\"layer3\", l3),\n (\"layer4\", l4),\n (\"subnet_layer\", subnet)\n ])\n )\n modules = list(s.modules())\n module_list = nn.ModuleList()\n module_list.extend(s.modules())\n check()\n\n def test_ModuleDict(self):\n modules = OrderedDict([\n ('act', nn.ReLU()),\n ('conv', nn.Conv2d(10, 10, 5)),\n ('fc', nn.Linear(5, 5)),\n ])\n\n module_dict = nn.ModuleDict(modules)\n\n def check():\n self.assertEqual(len(module_dict), len(modules))\n for k1, m2 in zip(modules, module_dict.children()):\n self.assertIs(modules[k1], m2)\n for k1, k2 in zip(modules, module_dict):\n self.assertIs(modules[k1], module_dict[k2])\n for k in module_dict:\n self.assertIs(module_dict[k], modules[k])\n for k in module_dict.keys():\n self.assertIs(module_dict[k], modules[k])\n for k, v in module_dict.items():\n self.assertIs(modules[k], v)\n for k1, m2 in zip(modules, module_dict.values()):\n self.assertIs(modules[k1], m2)\n for k in modules.keys():\n self.assertTrue(k in module_dict)\n check()\n\n modules['conv'] = nn.Conv2d(3, 4, 3)\n module_dict['conv'] = modules['conv']\n check()\n\n next_modules = [\n ('fc2', nn.Linear(5, 5)),\n ('act', nn.Sigmoid()),\n ]\n modules.update(next_modules)\n module_dict.update(next_modules)\n check()\n\n next_modules = OrderedDict([\n ('fc3', nn.Linear(5, 5)),\n ('act2', nn.Sigmoid()),\n ])\n modules.update(next_modules)\n module_dict.update(next_modules)\n check()\n\n next_modules = {\n 'fc4': nn.Linear(5, 5),\n 'act3': nn.Sigmoid()\n }\n modules.update(next_modules.items())\n module_dict.update(next_modules)\n check()\n\n next_modules = nn.ModuleDict([\n ('fc5', nn.Linear(5, 5)),\n ('act4', nn.Sigmoid()),\n ])\n modules.update(next_modules)\n module_dict.update(next_modules)\n check()\n\n del module_dict['fc']\n del modules['fc']\n check()\n\n with self.assertRaises(TypeError):\n module_dict.update(nn.ReLU())\n\n with self.assertRaises(TypeError):\n module_dict.update([nn.ReLU()])\n\n with self.assertRaises(ValueError):\n module_dict.update([[nn.ReLU()]])\n\n with self.assertRaises(TypeError):\n module_dict[1] = nn.ReLU()\n\n s = nn.Sequential(modules)\n module_dict = nn.ModuleDict(s.named_children())\n check()\n\n c = module_dict.pop('conv')\n self.assertIs(c, modules['conv'])\n modules.pop('conv')\n check()\n\n module_dict.clear()\n self.assertEqual(len(module_dict), 0)\n modules.clear()\n check()\n\n def test_ParameterList(self):\n def make_param():\n return Parameter(torch.randn(10, 10))\n parameters = [make_param(), make_param()]\n param_list = nn.ParameterList(parameters)\n\n def check():\n self.assertEqual(len(parameters), len(param_list))\n for p1, p2 in zip(parameters, param_list):\n self.assertIs(p1, p2)\n for p1, p2 in zip(parameters, param_list.parameters()):\n self.assertIs(p1, p2)\n for i in range(len(parameters)):\n self.assertIs(parameters[i], param_list[i])\n\n check()\n parameters += [make_param()]\n param_list += [parameters[-1]]\n check()\n parameters.append(make_param())\n param_list.append(parameters[-1])\n check()\n next_params = [make_param(), make_param()]\n parameters.extend(next_params)\n param_list.extend(next_params)\n check()\n parameters[2] = make_param()\n param_list[2] = parameters[2]\n check()\n parameters[-1] = make_param()\n param_list[-1] = parameters[-1]\n check()\n idx = torch.tensor(2, dtype=torch.int32)\n parameters[2] = make_param()\n param_list[idx] = parameters[2]\n self.assertIs(param_list[idx], parameters[2])\n check()\n self.assertEqual(param_list[1:], nn.ParameterList(parameters[1:]))\n self.assertEqual(param_list[3:], nn.ParameterList(parameters[3:]))\n self.assertEqual(param_list[:-1], nn.ParameterList(parameters[:-1]))\n self.assertEqual(param_list[:-3], nn.ParameterList(parameters[:-3]))\n self.assertEqual(param_list[::-1], nn.ParameterList(parameters[::-1]))\n\n with self.assertRaises(TypeError):\n param_list += make_param()\n with self.assertRaises(TypeError):\n param_list.extend(make_param())\n\n l1 = nn.Linear(1, 2)\n l2 = nn.Linear(2, 3)\n l3 = nn.Linear(3, 2)\n l4 = nn.Linear(2, 3)\n subnet = nn.Sequential(l3, l4)\n s = nn.Sequential(\n OrderedDict([\n (\"layer1\", l1),\n (\"layer2\", l2),\n (\"layer3\", l3),\n (\"layer4\", l4),\n (\"subnet_layer\", subnet)\n ])\n )\n parameters = list(s.parameters())\n param_list = nn.ParameterList()\n param_list.extend(s.parameters())\n check()\n\n def test_ParameterDict(self):\n parameters = OrderedDict([\n ('p1', Parameter(torch.randn(10, 10))),\n ('p2', Parameter(torch.randn(10, 10))),\n ('p3', Parameter(torch.randn(10, 10))),\n ])\n\n parameter_dict = nn.ParameterDict(parameters)\n\n def check():\n self.assertEqual(len(parameter_dict), len(parameters))\n for k1, m2 in zip(parameters, parameter_dict.parameters()):\n self.assertIs(parameters[k1], m2)\n for k1, k2 in zip(parameters, parameter_dict):\n self.assertIs(parameters[k1], parameter_dict[k2])\n for k in parameter_dict:\n self.assertIs(parameter_dict[k], parameters[k])\n for k in parameter_dict.keys():\n self.assertIs(parameter_dict[k], parameters[k])\n for k, v in parameter_dict.items():\n self.assertIs(v, parameters[k])\n for k1, m2 in zip(parameters, parameter_dict.values()):\n self.assertIs(parameters[k1], m2)\n for k in parameters.keys():\n self.assertTrue(k in parameter_dict)\n\n check()\n\n parameters['p4'] = Parameter(torch.randn(10, 10))\n parameter_dict['p4'] = parameters['p4']\n check()\n\n next_parameters = [\n ('p5', Parameter(torch.randn(10, 10))),\n ('p2', Parameter(torch.randn(10, 10))),\n ]\n parameters.update(next_parameters)\n parameter_dict.update(next_parameters)\n check()\n\n next_parameters = OrderedDict([\n ('p6', Parameter(torch.randn(10, 10))),\n ('p5', Parameter(torch.randn(10, 10))),\n ])\n parameters.update(next_parameters)\n parameter_dict.update(next_parameters)\n check()\n\n next_parameters = {\n 'p8': Parameter(torch.randn(10, 10)),\n 'p7': Parameter(torch.randn(10, 10))\n }\n parameters.update(sorted(next_parameters.items()))\n parameter_dict.update(next_parameters)\n check()\n\n next_parameters = nn.ParameterDict([\n ('p10', Parameter(torch.randn(10, 10))),\n ('p9', Parameter(torch.randn(10, 10))),\n ])\n parameters.update(next_parameters)\n parameter_dict.update(next_parameters)\n check()\n\n del parameter_dict['p3']\n del parameters['p3']\n check()\n\n with self.assertRaises(TypeError):\n parameter_dict.update(1)\n\n with self.assertRaises(TypeError):\n parameter_dict.update([1])\n\n with self.assertRaises(ValueError):\n parameter_dict.update(Parameter(torch.randn(10, 10)))\n\n with self.assertRaises(TypeError):\n parameter_dict[1] = Parameter(torch.randn(10, 10))\n\n p_pop = parameter_dict.pop('p4')\n self.assertIs(p_pop, parameters['p4'])\n parameters.pop('p4')\n check()\n\n parameter_dict.clear()\n self.assertEqual(len(parameter_dict), 0)\n parameters.clear()\n check()\n\n def test_add_module(self):\n l = nn.Linear(10, 20)\n net = nn.Module()\n net.l = l\n net.l2 = l\n net.add_module('empty', None)\n self.assertEqual(net.l, l)\n self.assertEqual(net.l2, l)\n self.assertEqual(net.empty, None)\n net.add_module('l3', l)\n self.assertEqual(net.l3, l)\n l3 = nn.Linear(20, 10)\n net.add_module('l', l3)\n self.assertEqual(net.l, l3)\n self.assertRaises(TypeError, lambda: net.add_module('x', 'non-module'))\n self.assertRaisesRegex(TypeError, 'module name should be a string. Got int',\n lambda: net.add_module(1, l))\n self.assertRaisesRegex(TypeError, 'module name should be a string. Got NoneType',\n lambda: net.add_module(None, l))\n\n def test_module_to_argparse(self):\n net = nn.Sequential(nn.Linear(3, 3))\n cpu = torch.device('cpu')\n with self.assertRaises(TypeError):\n net.to(cpu, True)\n with self.assertRaises(TypeError):\n net.to(torch.long)\n with self.assertRaises(TypeError):\n net.to(None, True)\n with self.assertRaises(TypeError):\n net.to(cpu, torch.long, True)\n with self.assertRaises(TypeError):\n net.to(cpu, dtype=torch.long, non_blocking=True)\n with self.assertRaises(TypeError):\n net.to([])\n with self.assertRaises(TypeError):\n net.to({}, non_blocking=True)\n with self.assertRaises(TypeError):\n net.to(torch.tensor(3, dtype=torch.long), non_blocking=True)\n with self.assertRaises(TypeError):\n net.to(cpu, torch.tensor(3, dtype=torch.long), non_blocking=True)\n\n def test_RNN_nonlinearity(self):\n rnn = torch.nn.RNN(1, 10)\n self.assertEqual(rnn.nonlinearity, 'tanh')\n\n rnn = torch.nn.RNN(1, 10, nonlinearity='relu')\n self.assertEqual(rnn.nonlinearity, 'relu')\n\n with self.assertRaisesRegex(ValueError, 'Unknown nonlinearity'):\n rnn = torch.nn.RNN(1, 10, nonlinearity='garbage')\n\n def test_module_apply_inplace_op(self):\n def add_one_inplace(t):\n return t.add_(1.0)\n\n # Test that applying an in-place operation to a module would bump\n # the module's parameters' version counter.\n m = nn.Linear(20, 10)\n pvm = m.weight.mul(m.weight)\n m_weight_version_saved = m.weight._version\n m = m._apply(add_one_inplace)\n self.assertGreater(m.weight._version, m_weight_version_saved)\n with self.assertRaisesRegex(RuntimeError, \"modified by an inplace operation\"):\n pvm.backward(torch.randn(10, 20))\n\n # Test that applying an in-place operation to a module would bump\n # the module's parameters' gradients' version counter.\n m = nn.Linear(20, 10)\n m.weight.grad = torch.randn(10, 20).requires_grad_()\n pgm = m.weight.grad.mul(m.weight.grad)\n m_weight_grad_version_saved = m.weight.grad._version\n m = m._apply(add_one_inplace)\n self.assertGreater(m.weight.grad._version, m_weight_grad_version_saved)\n with self.assertRaisesRegex(RuntimeError, \"modified by an inplace operation\"):\n pgm.backward(torch.randn(10, 20))\n\n def test_overwrite_module_params_on_conversion(self):\n # Test that if the conversion function passed to `module._apply()`\n # changes the TensorImpl type of `module`'s parameters, the `module`'s\n # parameters are always overwritten, regardless of the value of\n # `torch.__future__.get_overwrite_module_params_on_conversion()`.\n m = nn.Linear(20, 10)\n m.weight.grad = torch.randn(10, 20)\n weight_ref = m.weight\n weight_grad_ref = m.weight.grad\n m = m._apply(lambda t: torch.sparse_coo_tensor(torch.zeros([2, 1]), torch.ones([1]), torch.Size([10, 20])))\n self.assertNotEqual(weight_ref.layout, m.weight.layout)\n self.assertNotEqual(weight_grad_ref.layout, m.weight.grad.layout)\n\n # Test that under the current default settings\n # (`torch.__future__.get_overwrite_module_params_on_conversion() == False`),\n # a view to a module's parameters is not pointing to the same storage as\n # its base variable after converting the module to a different dtype.\n m = nn.Linear(20, 10).float()\n mw = m.weight[:]\n m.double()\n with torch.no_grad():\n mw[0][0] = 5\n self.assertTrue(mw[0][0].dtype == torch.float)\n self.assertTrue(mw._base[0][0].dtype == torch.double)\n\n try:\n torch.__future__.set_overwrite_module_params_on_conversion(True)\n\n # Test that if `torch.__future__.get_overwrite_module_params_on_conversion() == True`,\n # a view to a module's parameters is still pointing to the same storage as\n # its base variable after converting the module to a different dtype.\n m = nn.Linear(20, 10).float()\n mw = m.weight[:]\n m.double()\n with torch.no_grad():\n mw[0][0] = 5\n self.assertTrue(mw[0][0] == mw._base[0][0])\n\n # Test that if `torch.__future__.get_overwrite_module_params_on_conversion() == True`,\n # `float_module.double()` doesn't preserve previous references to\n # `float_module`'s parameters or gradients.\n m = nn.Linear(20, 10).float()\n m.weight.grad = torch.randn(10, 20).float()\n weight_ref = m.weight\n weight_grad_ref = m.weight.grad\n m.double()\n self.assertNotEqual(weight_ref.dtype, m.weight.dtype)\n self.assertNotEqual(weight_grad_ref.dtype, m.weight.grad.dtype)\n\n def add_one_inplace(t):\n return t.add_(1.0)\n\n # Test that if `torch.__future__.get_overwrite_module_params_on_conversion() == True`,\n # applying an in-place operation to a module would bump the module's\n # original parameters' version counter.\n m = nn.Linear(20, 10)\n pvm = m.weight.mul(m.weight)\n weight_ref = m.weight\n m_weight_version_saved = weight_ref._version\n m = m._apply(add_one_inplace)\n # Test that the in-place operation bumps the original parameter's version counter\n self.assertGreater(weight_ref._version, m_weight_version_saved)\n with self.assertRaisesRegex(RuntimeError, \"modified by an inplace operation\"):\n pvm.backward(torch.randn(10, 20))\n\n # Test that if `torch.__future__.get_overwrite_module_params_on_conversion() == True`,\n # applying an in-place operation to a module would bump the module's\n # original parameters' gradients' version counter.\n m = nn.Linear(20, 10)\n m.weight.grad = torch.randn(10, 20).requires_grad_()\n pgm = m.weight.grad.mul(m.weight.grad)\n weight_grad_ref = m.weight.grad\n m_weight_grad_version_saved = weight_grad_ref._version\n m = m._apply(add_one_inplace)\n self.assertGreater(weight_grad_ref._version, m_weight_grad_version_saved)\n with self.assertRaisesRegex(RuntimeError, \"modified by an inplace operation\"):\n pgm.backward(torch.randn(10, 20))\n\n # Test that if `torch.__future__.get_overwrite_module_params_on_conversion() == True`,\n # applying an out-of-place operation to a module doesn't bump\n # the module's original parameters' version counter.\n m = nn.Linear(20, 10)\n weight_ref = m.weight\n m_weight_version_saved = weight_ref._version\n m = m._apply(lambda t: torch.randn(t.shape))\n self.assertEqual(weight_ref._version, m_weight_version_saved)\n\n # Test that if `torch.__future__.get_overwrite_module_params_on_conversion() == True`,\n # applying an out-of-place operation to a module doesn't bump\n # the module's original parameters' gradients' version counter.\n m = nn.Linear(20, 10)\n m.weight.grad = torch.randn(10, 20).requires_grad_()\n weight_grad_ref = m.weight.grad\n m_weight_grad_version_saved = weight_grad_ref._version\n m = m._apply(lambda t: torch.randn(t.shape))\n self.assertEqual(weight_grad_ref._version, m_weight_grad_version_saved)\n finally:\n torch.__future__.set_overwrite_module_params_on_conversion(False)\n\n def test_type(self):\n l = nn.Linear(10, 20)\n net = nn.Module()\n net.l = l\n net.l2 = l\n net.add_module('empty', None)\n net.register_buffer('indices', torch.LongTensor(1))\n net.float()\n self.assertIsInstance(l.weight.data, torch.FloatTensor)\n self.assertIsInstance(l.bias.data, torch.FloatTensor)\n self.assertIsInstance(net.indices, torch.LongTensor)\n net.double()\n self.assertIsInstance(l.weight.data, torch.DoubleTensor)\n self.assertIsInstance(l.bias.data, torch.DoubleTensor)\n self.assertIsInstance(net.indices, torch.LongTensor)\n net.to(torch.half)\n self.assertIsInstance(l.weight.data, torch.HalfTensor)\n self.assertIsInstance(l.bias.data, torch.HalfTensor)\n self.assertIsInstance(net.indices, torch.LongTensor)\n if TEST_CUDA:\n net.float().cuda()\n self.assertIsInstance(l.weight.data, torch.cuda.FloatTensor)\n self.assertIsInstance(l.bias.data, torch.cuda.FloatTensor)\n self.assertIsInstance(net.indices, torch.cuda.LongTensor)\n net.cpu()\n self.assertIsInstance(l.weight.data, torch.FloatTensor)\n self.assertIsInstance(l.bias.data, torch.FloatTensor)\n self.assertIsInstance(net.indices, torch.LongTensor)\n net.to(\"cuda\", torch.double, True)\n self.assertIsInstance(l.weight.data, torch.cuda.DoubleTensor)\n self.assertIsInstance(l.bias.data, torch.cuda.DoubleTensor)\n self.assertIsInstance(net.indices, torch.cuda.LongTensor)\n net.to(torch.empty(1, device=\"cuda:0\", dtype=torch.half))\n self.assertIsInstance(l.weight.data, torch.cuda.HalfTensor)\n self.assertIsInstance(l.bias.data, torch.cuda.HalfTensor)\n self.assertIsInstance(net.indices, torch.cuda.LongTensor)\n net.to(torch.device(\"cpu\"), non_blocking=True)\n self.assertIsInstance(l.weight.data, torch.HalfTensor)\n self.assertIsInstance(l.bias.data, torch.HalfTensor)\n self.assertIsInstance(net.indices, torch.LongTensor)\n net.to(torch.float)\n self.assertIsInstance(l.weight.data, torch.FloatTensor)\n self.assertIsInstance(l.bias.data, torch.FloatTensor)\n net.to(torch.DoubleTensor(1))\n self.assertIsInstance(l.weight.data, torch.DoubleTensor)\n self.assertIsInstance(l.bias.data, torch.DoubleTensor)\n if TEST_CUDA:\n net.to(device='cuda', dtype=torch.float)\n self.assertIsInstance(l.weight.data, torch.cuda.FloatTensor)\n self.assertIsInstance(l.bias.data, torch.cuda.FloatTensor)\n\n def test_non_leaf_parameters(self):\n l1 = nn.Linear(10, 10)\n l2 = nn.Linear(10, 10)\n\n def assign_weight():\n l2.weight = l1.weight + 2\n\n self.assertRaises(TypeError, assign_weight)\n # This should work though\n l2.weight = Parameter(torch.randn(10, 10))\n\n def test_clip_grad_norm(self):\n l = nn.Linear(10, 10)\n max_norm = 2\n\n def compute_norm(norm_type):\n norm_type = float(norm_type)\n if norm_type != inf:\n total_norm = 0\n for p in l.parameters():\n total_norm += p.grad.data.abs().pow(norm_type).sum()\n return pow(total_norm, 1. / norm_type)\n else:\n return max(p.grad.data.abs().max() for p in l.parameters())\n\n def compare_scaling(grads):\n p_scale = [p.grad.data.div(g).view(-1) for p, g in zip(l.parameters(), grads)]\n scale = torch.cat(p_scale)\n self.assertEqual(scale.std(), 0)\n return scale[0]\n\n grads = torch.arange(1., 101).view(10, 10), torch.ones(10).div(1000)\n for norm_type in [0.5, 1.5, 2, 4, 'inf']:\n for p, g in zip(l.parameters(), grads):\n p._grad = g.clone().view_as(p.data)\n norm_before = compute_norm(norm_type)\n norm = clip_grad_norm_(l.parameters(), max_norm, norm_type=norm_type)\n norm_after = compute_norm(norm_type)\n self.assertEqual(norm, norm_before)\n self.assertEqual(norm_after, max_norm)\n self.assertLessEqual(norm_after, norm_before)\n compare_scaling(grads)\n\n # Small gradients should be left unchanged\n grads = torch.rand(10, 10).div(10000), torch.ones(10).div(500)\n for norm_type in [0.5, 1.5, 2, 4, 'inf']:\n for p, g in zip(l.parameters(), grads):\n p.grad.data.copy_(g)\n norm_before = compute_norm(norm_type)\n norm = clip_grad_norm_(l.parameters(), max_norm, norm_type=norm_type)\n norm_after = compute_norm(norm_type)\n self.assertEqual(norm, norm_before)\n self.assertEqual(norm_before, norm_after)\n self.assertLessEqual(norm_after, max_norm)\n scale = compare_scaling(grads)\n self.assertEqual(scale, 1)\n\n # Should accept a single Tensor as input\n p1, p2 = torch.randn(10, 10), torch.randn(10, 10)\n g = torch.arange(1., 101).view(10, 10)\n p1._grad = g.clone()\n p2._grad = g.clone()\n for norm_type in [0.5, 1.5, 2, 4, 'inf']:\n clip_grad_norm_(p1, max_norm, norm_type=norm_type)\n clip_grad_norm_([p2], max_norm, norm_type=norm_type)\n self.assertEqual(p1.grad, p2.grad)\n\n def test_clip_grad_value(self):\n l = nn.Linear(10, 10)\n clip_value = 2.5\n\n grad_w, grad_b = torch.arange(-50., 50).view(10, 10).div_(5), torch.ones(10).mul_(2)\n for grad_list in [[grad_w, grad_b], [grad_w, None]]:\n for p, g in zip(l.parameters(), grad_list):\n p._grad = g.clone().view_as(p.data) if g is not None else g\n\n clip_grad_value_(l.parameters(), clip_value)\n for p in filter(lambda p: p.grad is not None, l.parameters()):\n self.assertLessEqual(p.grad.data.max(), clip_value)\n self.assertGreaterEqual(p.grad.data.min(), -clip_value)\n\n # Should accept a single Tensor as input\n p1, p2 = torch.randn(10, 10), torch.randn(10, 10)\n g = torch.arange(-50., 50).view(10, 10).div_(5)\n p1._grad = g.clone()\n p2._grad = g.clone()\n clip_grad_value_(p1, clip_value)\n clip_grad_value_([p2], clip_value)\n self.assertEqual(p1.grad, p2.grad)\n\n def test_parameters_to_vector(self):\n conv1 = nn.Conv2d(3, 10, 5)\n fc1 = nn.Linear(10, 20)\n model = nn.Sequential(conv1, fc1)\n\n vec = parameters_to_vector(model.parameters())\n self.assertEqual(vec.size(0), 980)\n\n def test_vector_to_parameters(self):\n conv1 = nn.Conv2d(3, 10, 5)\n fc1 = nn.Linear(10, 20)\n model = nn.Sequential(conv1, fc1)\n\n vec = torch.arange(0., 980)\n vector_to_parameters(vec, model.parameters())\n\n sample = next(model.parameters())[0, 0, 0]\n self.assertTrue(torch.equal(sample.data, vec.data[:5]))\n\n # torch/nn/utils/parametrize\n def test_register_and_remove_parametrization(self):\n r\"\"\"Test that it is possible to add a few parametrizations\n on a parameter or a buffer and that removing them restores the initial state\n It also tests that backpropagating through them works as expected\n \"\"\"\n # Define a couple matrix parametrizations\n class Skew(nn.Module):\n def forward(self, X):\n X = X.tril(-1)\n return X - X.T\n\n class Orthogonal(nn.Module):\n def forward(self, X):\n # Cayley map\n # If X is skew-symmetric it returns an orthogonal matrix\n Id = torch.eye(X.size(0), device=X.device)\n return torch.solve(Id - X, Id + X).solution\n\n # Define a couple vector parametrizations\n class FirstZero(nn.Module):\n def forward(self, x):\n return torch.cat([x.new_zeros(1), x[1:]])\n\n class LastZero(nn.Module):\n def forward(self, x):\n return torch.cat([x[:-1], x.new_zeros(1)])\n\n model = nn.Linear(8, 8)\n initial_weight_id = id(model.weight)\n initial_bias_id = id(model.bias)\n initial_model = deepcopy(model)\n\n # Test one parametrization\n parametrize.register_parametrization(model, \"weight\", Skew())\n self.assertTrue(hasattr(model, \"parametrizations\"))\n self.assertTrue(parametrize.is_parametrized(model))\n self.assertTrue(parametrize.is_parametrized(model, \"weight\"))\n self.assertFalse(parametrize.is_parametrized(model, \"bias\"))\n self.assertNotIn(\"weight\", model._parameters)\n # Result should be skew-symmetric\n A = model.weight\n self.assertTrue(torch.allclose(A, -A.T))\n # Remove and check consistency\n parametrize.remove_parametrizations(model, \"weight\", leave_parametrized=False)\n self.assertFalse(hasattr(model, \"parametrizations\"))\n self.assertEqual(model.weight, initial_model.weight)\n self.assertEqual(id(model.weight), initial_weight_id)\n self.assertEqual(model.__class__, nn.Linear)\n\n # Test two parametrizations at the same time and removing them\n parametrize.register_parametrization(model, \"weight\", Skew())\n parametrize.register_parametrization(model, \"weight\", Orthogonal())\n # Result should be orthogonal\n X = model.weight\n Id = torch.eye(X.size(0), device=X.device)\n self.assertTrue(torch.allclose(X.T @ X, Id))\n # Structure tests\n self.assertTrue(hasattr(model, \"parametrizations\"))\n self.assertTrue(parametrize.is_parametrized(model))\n self.assertTrue(parametrize.is_parametrized(model, \"weight\"))\n self.assertFalse(parametrize.is_parametrized(model, \"bias\"))\n self.assertIn(\"weight\", model.parametrizations)\n self.assertNotIn(\"weight\", model._parameters)\n # Remove\n parametrize.remove_parametrizations(model, \"weight\", leave_parametrized=False)\n self.assertEqual(model.weight, initial_model.weight)\n self.assertEqual(id(model.weight), initial_weight_id)\n self.assertFalse(hasattr(model, \"parametrizations\"))\n self.assertEqual(model.__class__, nn.Linear)\n\n # Add everything\n parametrize.register_parametrization(model, \"weight\", Skew())\n parametrize.register_parametrization(model, \"weight\", Orthogonal())\n parametrize.register_parametrization(model, \"bias\", FirstZero())\n parametrize.register_parametrization(model, \"bias\", LastZero())\n\n # Basic tests\n self.assertTrue(parametrize.is_parametrized(model))\n self.assertTrue(parametrize.is_parametrized(model, \"weight\"))\n self.assertTrue(parametrize.is_parametrized(model, \"bias\"))\n self.assertEqual(model.bias[0].item(), 0.)\n self.assertEqual(model.bias[-1].item(), 0.)\n self.assertEqual(len(list(model.parameters())), 2) # Nothing weird has happpened\n # Should not throw\n (model.weight.T @ model.bias).sum().backward()\n with torch.no_grad():\n for p in model.parameters():\n p.add_(- p.grad, alpha=0.01)\n\n # Remove first parametrization.\n # Check that the model is still parametrized and so is the second parameter\n parametrize.remove_parametrizations(model, \"weight\", leave_parametrized=False)\n self.assertTrue(parametrize.is_parametrized(model)) # Still parametrized\n self.assertFalse(parametrize.is_parametrized(model, \"weight\")) # Parametrization removed\n self.assertTrue(parametrize.is_parametrized(model, \"bias\")) # Still parametrized\n self.assertEqual(model.bias[0].item(), 0.) # Still parametrized\n self.assertEqual(model.bias[-1].item(), 0.) # Still parametrized\n self.assertNotEqual(model.weight, initial_model.weight) # Has been updated\n self.assertEqual(id(model.weight), initial_weight_id) # Keeps the same id\n self.assertEqual(len(list(model.parameters())), 2) # Nothing weird has happened\n # Should not throw\n (model.weight.T @ model.bias).sum().backward()\n with torch.no_grad():\n for p in model.parameters():\n p.add_(- p.grad, alpha=0.01)\n\n # Remove the second parametrization.\n # Check that the module is not parametrized\n parametrize.remove_parametrizations(model, \"bias\", leave_parametrized=False)\n self.assertFalse(parametrize.is_parametrized(model)) # Not parametrized\n self.assertNotEqual(model.bias, initial_model.bias) # Has been updated\n self.assertNotEqual(model.bias[0].item(), 0.) # Not parametrized\n self.assertNotEqual(model.bias[-1].item(), 0.) # Not parametrized\n self.assertEqual(id(model.bias), initial_bias_id) # Keeps the same id\n self.assertFalse(hasattr(model, \"parametrizations\")) # Not parametrized the module\n self.assertEqual(model.__class__, nn.Linear) # Resores the previous class\n self.assertEqual(len(list(model.parameters())), 2) # Nothing weird has happeed\n # Should not throw\n (model.weight.T @ model.bias).sum().backward()\n with torch.no_grad():\n for p in model.parameters():\n p.add_(- p.grad, alpha=0.01)\n\n # Test leave_parametrized=True\n for _ in range(2):\n parametrize.register_parametrization(model, \"weight\", Skew())\n parametrize.register_parametrization(model, \"weight\", Orthogonal())\n parametrize.remove_parametrizations(model, \"weight\", leave_parametrized=True)\n # Should not throw\n (model.weight.T @ model.bias).sum().backward()\n with torch.no_grad():\n for p in model.parameters():\n p.add_(- p.grad, alpha=0.01)\n\n def test_register_and_remove_buffer_parametrization(self):\n r\"\"\"Test that it is possible to add and remove parametrizations on buffers\"\"\"\n # Define a couple vector parametrizations\n class FirstZero(nn.Module):\n def forward(self, x):\n return torch.cat([x.new_zeros(1), x[1:]])\n\n class LastZero(nn.Module):\n def forward(self, x):\n return torch.cat([x[:-1], x.new_zeros(1)])\n\n model = nn.Linear(8, 8)\n\n # Instantiate parametrizations on buffers. It should work as expected\n delattr(model, \"bias\")\n model.register_buffer(\"bias\", torch.ones(8))\n parametrize.register_parametrization(model, \"bias\", FirstZero())\n parametrize.register_parametrization(model, \"bias\", LastZero())\n self.assertTrue(parametrize.is_parametrized(model))\n self.assertTrue(parametrize.is_parametrized(model, \"bias\"))\n self.assertEqual(model.bias[0].item(), 0.)\n self.assertEqual(model.bias[-1].item(), 0.)\n self.assertTrue((model.bias[1:-1] == torch.ones(6)).all())\n self.assertEqual(len(list(model.parameters())), 1)\n\n # Remove parametrizations on buffers. It should work as expected\n parametrize.remove_parametrizations(model, \"bias\", leave_parametrized=True)\n self.assertFalse(parametrize.is_parametrized(model))\n self.assertFalse(parametrize.is_parametrized(model, \"bias\"))\n self.assertEqual(model.bias[0].item(), 0.)\n self.assertEqual(model.bias[-1].item(), 0.)\n self.assertTrue((model.bias[1:-1] == torch.ones(6)).all())\n self.assertEqual(len(list(model.parameters())), 1)\n\n def test_serialization_parametrization(self):\n r\"\"\"Test that it is possible to serialize a parametrized model via state_dict\"\"\"\n # A stateful parametrization\n class Orthogonal(nn.Module):\n def __init__(self, n):\n super().__init__()\n self.register_buffer(\"id\", torch.eye(n))\n self.register_buffer(\"B\", torch.empty(n, n))\n init.orthogonal_(self.B)\n\n def forward(self, X):\n A = X.triu(1)\n A = A - A.T\n return self.B @ torch.solve(self.id - A, self.id + A).solution\n\n def get_model():\n model = torch.nn.Sequential(\n torch.nn.Linear(5, 5),\n torch.nn.ReLU(),\n torch.nn.Linear(5, 1),\n )\n\n parametrize.register_parametrization(model[0], \"weight\", Orthogonal(5))\n return model\n\n model = get_model()\n\n prev_weight = model[0].weight\n prev_B = model[0].parametrizations.weight[0].B\n\n new_model = get_model()\n with TemporaryFileName() as fname:\n torch.save(model.state_dict(), fname)\n new_model.load_state_dict(torch.load(fname))\n\n # Integrity tests\n self.assertTrue(parametrize.is_parametrized(new_model[0], \"weight\"))\n self.assertEqual(prev_weight, new_model[0].weight)\n self.assertEqual(prev_B, new_model[0].parametrizations.weight[0].B)\n\n # Trying to save the whole parametrized model raises\n with self.assertRaisesRegex(RuntimeError, \"state_dict\"):\n with TemporaryFileName() as fname:\n torch.save(model, fname)\n\n def test_initialization_parametrization(self):\n r\"\"\"Test that it is possible to initialize a parametrization when it\n implements a `right_inverse` method\n \"\"\"\n class Skew(nn.Module):\n def forward(self, X):\n A = X.triu(1)\n return A - A.T\n\n def is_skew(self, A):\n return torch.allclose(A, -A.T, atol=1e-6)\n\n def right_inverse(self, X):\n if not self.is_skew(X):\n raise ValueError(\"The matrix is not skew-symmetric.\")\n return X.triu(1)\n\n # Implements a Cayley map where right_inverse is not quite the inverse of forward\n class Orthogonal(nn.Module):\n def __init__(self, n):\n super().__init__()\n self.register_buffer(\"B\", torch.eye(n))\n\n def forward(self, A):\n Id = torch.eye(X.size(0))\n return self.B @ torch.solve(Id - A, Id + A).solution\n\n def is_orthogonal(self, X):\n Id = torch.eye(X.size(0))\n return torch.allclose(X.T @ X, Id, atol=1e-4)\n\n def right_inverse(self, X):\n if not self.is_orthogonal(X):\n raise ValueError(\"The input is not orthogonal.\")\n # cayley(0) == Id, so B @ cayley(0) == B\n self.B = X\n return torch.zeros_like(X)\n\n N = 5\n model = nn.Linear(N, N)\n # Register the skew-symmetric onstraint. The result is now skew-symmetric\n parametrize.register_parametrization(model, \"weight\", Skew())\n X = torch.rand(N, N)\n # X is not skew-symmetric, so it throws an error\n with self.assertRaises(ValueError):\n model.weight = X\n # Make X skew-symmetric\n X = X - X.T\n model.weight = X\n self.assertEqual(model.parametrizations.weight.original, X.triu(1))\n self.assertEqual(model.weight, X)\n\n # Having several parametrizations registered should work in the same way\n parametrize.register_parametrization(model, \"weight\", Orthogonal(N))\n # Register now the Cayley map. The result is now orthogonal\n X = torch.rand(N, N)\n # X is not orthogonal, so it throws an error\n with self.assertRaises(ValueError):\n model.weight = X\n init.orthogonal_(X)\n model.weight = X\n self.assertEqual(model.weight, X)\n self.assertEqual(model.parametrizations.weight.original, torch.zeros_like(X))\n\n def test_errors_parametrization(self):\n # A parametrization shall not change the size of the parameter\n class ChangeSize(nn.Module):\n def forward(self, x):\n return x[:-1]\n\n # A simple parametrization that does not implement a right_inverse\n class Double(nn.Module):\n def forward(self, x):\n return 2 * x\n\n module = nn.Linear(3, 4)\n # This should not throw when registering\n parametrize.register_parametrization(module, \"weight\", ChangeSize())\n # It throws in the forward\n with self.assertRaisesRegex(RuntimeError, \"may not change the size\"):\n module(torch.rand(2))\n # Undo\n parametrize.remove_parametrizations(module, \"weight\", leave_parametrized=False)\n self.assertFalse(parametrize.is_parametrized(module))\n\n # Removing a parametrization from an unparametrized tensor throws\n with self.assertRaisesRegex(ValueError, \"does not have a parametrization\"):\n parametrize.remove_parametrizations(module, \"bias\")\n # Nothing odd happens\n self.assertFalse(parametrize.is_parametrized(module))\n\n # Register a parametrization on a non-existing parameter breaks\n with self.assertRaisesRegex(ValueError, \"does not have a parameter\"):\n parametrize.register_parametrization(module, \"foo\", ChangeSize())\n self.assertFalse(parametrize.is_parametrized(module))\n\n # Try to assign to a parametrization that does not implement `right_inverse`\n parametrize.register_parametrization(module, \"weight\", Double())\n with self.assertRaisesRegex(RuntimeError, \"right_inverse\"):\n module.weight = torch.rand(4, 3)\n # Undo\n parametrize.remove_parametrizations(module, \"weight\", leave_parametrized=False)\n self.assertFalse(parametrize.is_parametrized(module))\n\n def test_caching_parametrization(self):\n r\"\"\"Test the caching system of a parametrization\"\"\"\n # Define a couple matrix parametrizations\n class Skew(nn.Module):\n def forward(self, X):\n X = X.tril(-1)\n return X - X.T\n\n class Orthogonal(nn.Module):\n def forward(self, X):\n Id = torch.eye(X.size(0), device=X.device)\n return torch.solve(Id - X, Id + X).solution\n\n model = nn.Linear(5, 5)\n parametrize.register_parametrization(model, \"weight\", Skew())\n parametrize.register_parametrization(model, \"weight\", Orthogonal())\n\n # Test that the caching system works\n with parametrize.cached():\n X = model.weight\n Y = model.weight\n self.assertEqual(id(X), id(Y))\n\n def test_dtype_parametrization(self):\n r\"\"\"Test a case that is not allowed when removing a parametrization\"\"\"\n class ChangeType(nn.Module):\n def forward(self, X):\n return X.double()\n\n module = nn.Linear(4, 4).float()\n input_ = torch.rand(4).double()\n # It is allowed to register a parametrization that changes the dtype\n parametrize.register_parametrization(module, \"weight\", ChangeType())\n module(input_)\n # We can remove it leaving the original tensor\n parametrize.remove_parametrizations(module, \"weight\", leave_parametrized=False)\n # But leaving it parametrized breaks\n parametrize.register_parametrization(module, \"weight\", ChangeType())\n with self.assertRaisesRegex(ValueError, \"changes the dtype\"):\n parametrize.remove_parametrizations(module, \"weight\", leave_parametrized=True)\n\n # torch/nn/utils/prune.py\n @unittest.skipIf(not TEST_NUMPY, \"numpy not found\")\n def test_validate_pruning_amount_init(self):\n r\"\"\"Test the first util function that validates the pruning\n amount requested by the user the moment the pruning method\n is initialized. This test checks that the expected errors are\n raised whenever the amount is invalid.\n The original function runs basic type checking + value range checks.\n It doesn't check the validity of the pruning amount with\n respect to the size of the tensor to prune. That's left to\n `_validate_pruning_amount`, tested below.\n \"\"\"\n # neither float not int should raise TypeError\n with self.assertRaises(TypeError):\n prune._validate_pruning_amount_init(amount=\"I'm a string\")\n\n # float not in [0, 1] should raise ValueError\n with self.assertRaises(ValueError):\n prune._validate_pruning_amount_init(amount=1.1)\n with self.assertRaises(ValueError):\n prune._validate_pruning_amount_init(amount=20.)\n\n # negative int should raise ValueError\n with self.assertRaises(ValueError):\n prune._validate_pruning_amount_init(amount=-10)\n\n # all these should pass without errors because they're valid amounts\n prune._validate_pruning_amount_init(amount=0.34)\n prune._validate_pruning_amount_init(amount=1500)\n prune._validate_pruning_amount_init(amount=0)\n prune._validate_pruning_amount_init(amount=0.)\n prune._validate_pruning_amount_init(amount=1)\n prune._validate_pruning_amount_init(amount=1.)\n self.assertTrue(True)\n\n @unittest.skipIf(not TEST_NUMPY, \"numpy not found\")\n def test_validate_pruning_amount(self):\n r\"\"\"Tests the second util function that validates the pruning\n amount requested by the user, this time with respect to the size\n of the tensor to prune. The rationale is that if the pruning amount,\n converted to absolute value of units to prune, is larger than\n the number of units in the tensor, then we expect the util function\n to raise a value error.\n \"\"\"\n # if amount is int and amount > tensor_size, raise ValueError\n with self.assertRaises(ValueError):\n prune._validate_pruning_amount(amount=20, tensor_size=19)\n\n # amount is a float so this should not raise an error\n prune._validate_pruning_amount(amount=0.3, tensor_size=0)\n\n # this is okay\n prune._validate_pruning_amount(amount=19, tensor_size=20)\n prune._validate_pruning_amount(amount=0, tensor_size=0)\n prune._validate_pruning_amount(amount=1, tensor_size=1)\n self.assertTrue(True)\n\n @unittest.skipIf(not TEST_NUMPY, \"numpy not found\")\n def test_compute_nparams_to_prune(self):\n r\"\"\"Test that requested pruning `amount` gets translated into the\n correct absolute number of units to prune.\n \"\"\"\n self.assertEqual(\n prune._compute_nparams_toprune(amount=0, tensor_size=15),\n 0\n )\n self.assertEqual(\n prune._compute_nparams_toprune(amount=10, tensor_size=15),\n 10\n )\n # if 1 is int, means 1 unit\n self.assertEqual(\n prune._compute_nparams_toprune(amount=1, tensor_size=15),\n 1\n )\n # if 1. is float, means 100% of units\n self.assertEqual(\n prune._compute_nparams_toprune(amount=1., tensor_size=15),\n 15\n )\n self.assertEqual(\n prune._compute_nparams_toprune(amount=0.4, tensor_size=17),\n 7\n )\n\n def test_random_pruning_sizes(self):\n r\"\"\"Test that the new parameters and buffers created by the pruning\n method have the same size as the input tensor to prune. These, in\n fact, correspond to the pruned version of the tensor itself, its\n mask, and its original copy, so the size must match.\n \"\"\"\n # fixturize test\n # TODO: add other modules\n modules = [nn.Linear(5, 7), nn.Conv3d(2, 2, 2)]\n names = ['weight', 'bias']\n\n for m in modules:\n for name in names:\n with self.subTest(m=m, name=name):\n original_tensor = getattr(m, name)\n\n prune.random_unstructured(m, name=name, amount=0.1)\n # mask has the same size as tensor being pruned\n self.assertEqual(\n original_tensor.size(),\n getattr(m, name + '_mask').size()\n )\n # 'orig' tensor has the same size as the original tensor\n self.assertEqual(\n original_tensor.size(),\n getattr(m, name + '_orig').size()\n )\n # new tensor has the same size as the original tensor\n self.assertEqual(\n original_tensor.size(),\n getattr(m, name).size()\n )\n\n def test_random_pruning_orig(self):\n r\"\"\"Test that original tensor is correctly stored in 'orig'\n after pruning is applied. Important to make sure we don't\n lose info about the original unpruned parameter.\n \"\"\"\n # fixturize test\n # TODO: add other modules\n modules = [nn.Linear(5, 7), nn.Conv3d(2, 2, 2)]\n names = ['weight', 'bias']\n\n for m in modules:\n for name in names:\n with self.subTest(m=m, name=name):\n\n # tensor prior to pruning\n original_tensor = getattr(m, name)\n prune.random_unstructured(m, name=name, amount=0.1)\n self.assertEqual(\n original_tensor,\n getattr(m, name + '_orig')\n )\n\n def test_random_pruning_new_weight(self):\n r\"\"\"Test that module.name now contains a pruned version of\n the original tensor obtained from multiplying it by the mask.\n \"\"\"\n # fixturize test\n # TODO: add other modules\n modules = [nn.Linear(5, 7), nn.Conv3d(2, 2, 2)]\n names = ['weight', 'bias']\n\n for m in modules:\n for name in names:\n with self.subTest(m=m, name=name):\n # tensor prior to pruning\n original_tensor = getattr(m, name)\n prune.random_unstructured(m, name=name, amount=0.1)\n # weight = weight_orig * weight_mask\n self.assertEqual(\n getattr(m, name),\n getattr(m, name + '_orig')\n * getattr(m, name + '_mask').to(\n dtype=original_tensor.dtype\n ),\n )\n\n def test_identity_pruning(self):\n r\"\"\"Test that a mask of 1s does not change forward or backward.\n \"\"\"\n input_ = torch.ones(1, 5)\n m = nn.Linear(5, 2)\n y_prepruning = m(input_) # output prior to pruning\n\n # compute grad pre-pruning and check it's equal to all ones\n y_prepruning.sum().backward()\n old_grad_weight = m.weight.grad.clone() # don't grab pointer!\n self.assertEqual(old_grad_weight, torch.ones_like(m.weight))\n old_grad_bias = m.bias.grad.clone()\n self.assertEqual(old_grad_bias, torch.ones_like(m.bias))\n\n # remove grads\n m.zero_grad()\n\n # force the mask to be made of all 1s\n prune.identity(m, name=\"weight\")\n\n # with mask of 1s, output should be identical to no mask\n y_postpruning = m(input_)\n self.assertEqual(y_prepruning, y_postpruning)\n\n # with mask of 1s, grad should be identical to no mask\n y_postpruning.sum().backward()\n self.assertEqual(old_grad_weight, m.weight_orig.grad)\n self.assertEqual(old_grad_bias, m.bias.grad)\n\n # calling forward twice in a row shouldn't change output\n y1 = m(input_)\n y2 = m(input_)\n self.assertEqual(y1, y2)\n\n def test_random_pruning_0perc(self):\n r\"\"\"Test that a mask of 1s does not change forward or backward.\n \"\"\"\n input_ = torch.ones(1, 5)\n m = nn.Linear(5, 2)\n y_prepruning = m(input_) # output prior to pruning\n\n # compute grad pre-pruning and check it's equal to all ones\n y_prepruning.sum().backward()\n old_grad_weight = m.weight.grad.clone() # don't grab pointer!\n self.assertEqual(old_grad_weight, torch.ones_like(m.weight))\n old_grad_bias = m.bias.grad.clone()\n self.assertEqual(old_grad_bias, torch.ones_like(m.bias))\n\n # remove grads\n m.zero_grad()\n\n # force the mask to be made of all 1s\n with mock.patch(\n \"torch.nn.utils.prune.RandomUnstructured.compute_mask\"\n ) as compute_mask:\n compute_mask.return_value = torch.ones_like(m.weight)\n prune.random_unstructured(m, name='weight', amount=0.9) # amount won't count\n\n # with mask of 1s, output should be identical to no mask\n y_postpruning = m(input_)\n self.assertEqual(y_prepruning, y_postpruning)\n\n # with mask of 1s, grad should be identical to no mask\n y_postpruning.sum().backward()\n self.assertEqual(old_grad_weight, m.weight_orig.grad)\n self.assertEqual(old_grad_bias, m.bias.grad)\n\n # calling forward twice in a row shouldn't change output\n y1 = m(input_)\n y2 = m(input_)\n self.assertEqual(y1, y2)\n\n def test_random_pruning(self):\n input_ = torch.ones(1, 5)\n m = nn.Linear(5, 2)\n\n # define custom mask to assign with mock\n mask = torch.ones_like(m.weight)\n mask[1, 0] = 0\n mask[0, 3] = 0\n\n # check grad is zero for masked weights\n with mock.patch(\n \"torch.nn.utils.prune.RandomUnstructured.compute_mask\"\n ) as compute_mask:\n compute_mask.return_value = mask\n prune.random_unstructured(m, name='weight', amount=0.9)\n\n y_postpruning = m(input_)\n y_postpruning.sum().backward()\n # weight_orig is the parameter, so it's the tensor that will accumulate the grad\n self.assertEqual(m.weight_orig.grad, mask) # all 1s, except for masked units\n self.assertEqual(m.bias.grad, torch.ones_like(m.bias))\n\n # make sure that weight_orig update doesn't modify [1, 0] and [0, 3]\n old_weight_orig = m.weight_orig.clone()\n # update weights\n learning_rate = 1.\n for p in m.parameters():\n p.data.sub_(p.grad.data * learning_rate)\n # since these are pruned, they should not be updated\n self.assertEqual(old_weight_orig[1, 0], m.weight_orig[1, 0])\n self.assertEqual(old_weight_orig[0, 3], m.weight_orig[0, 3])\n\n def test_random_pruning_forward(self):\n r\"\"\"check forward with mask (by hand).\n \"\"\"\n input_ = torch.ones(1, 5)\n m = nn.Linear(5, 2)\n\n # define custom mask to assign with mock\n mask = torch.zeros_like(m.weight)\n mask[1, 0] = 1\n mask[0, 3] = 1\n\n with mock.patch(\n \"torch.nn.utils.prune.RandomUnstructured.compute_mask\"\n ) as compute_mask:\n compute_mask.return_value = mask\n prune.random_unstructured(m, name='weight', amount=0.9)\n\n yhat = m(input_)\n self.assertEqual(yhat[0, 0], m.weight_orig[0, 3] + m.bias[0])\n self.assertEqual(yhat[0, 1], m.weight_orig[1, 0] + m.bias[1])\n\n def test_remove_pruning_forward(self):\n r\"\"\"Remove pruning and check forward is unchanged from previous\n pruned state.\n \"\"\"\n input_ = torch.ones(1, 5)\n m = nn.Linear(5, 2)\n\n # define custom mask to assign with mock\n mask = torch.ones_like(m.weight)\n mask[1, 0] = 0\n mask[0, 3] = 0\n\n # check grad is zero for masked weights\n with mock.patch(\n \"torch.nn.utils.prune.RandomUnstructured.compute_mask\"\n ) as compute_mask:\n compute_mask.return_value = mask\n prune.random_unstructured(m, name='weight', amount=0.9)\n\n y_postpruning = m(input_)\n\n prune.remove(m, 'weight')\n\n y_postremoval = m(input_)\n self.assertEqual(y_postpruning, y_postremoval)\n\n def test_pruning_id_consistency(self):\n r\"\"\"Test that pruning doesn't change the id of the parameters, which\n would otherwise introduce issues with pre-existing optimizers that\n point to old parameters.\n \"\"\"\n m = nn.Linear(5, 2, bias=False)\n\n tensor_id = id(list(m.parameters())[0])\n\n prune.random_unstructured(m, name=\"weight\", amount=0.9)\n self.assertEqual(tensor_id, id(list(m.parameters())[0]))\n\n prune.remove(m, \"weight\")\n self.assertEqual(tensor_id, id(list(m.parameters())[0]))\n\n def test_random_pruning_pickle(self):\n modules = [nn.Linear(5, 7), nn.Conv3d(2, 2, 2)]\n names = ['weight', 'bias']\n\n for m in modules:\n for name in names:\n with self.subTest(m=m, name=name):\n prune.random_unstructured(m, name=name, amount=0.1)\n m_new = pickle.loads(pickle.dumps(m))\n self.assertIsInstance(m_new, type(m))\n\n def test_multiple_pruning_calls(self):\n # if you call pruning twice, the hook becomes a PruningContainer\n m = nn.Conv3d(2, 2, 2)\n prune.l1_unstructured(m, name='weight', amount=0.1)\n weight_mask0 = m.weight_mask # save it for later sanity check\n\n # prune again\n prune.ln_structured(m, name='weight', amount=0.3, n=2, dim=0)\n hook = next(iter(m._forward_pre_hooks.values()))\n self.assertIsInstance(\n hook,\n torch.nn.utils.prune.PruningContainer\n )\n # check that container._tensor_name is correctly set no matter how\n # many pruning methods are in the container\n self.assertEqual(hook._tensor_name, 'weight')\n\n # check that the pruning container has the right length\n # equal to the number of pruning iters\n self.assertEqual(len(hook), 2) # m.weight has been pruned twice\n\n # check that the entries of the pruning container are of the expected\n # type and in the expected order\n self.assertIsInstance(hook[0], torch.nn.utils.prune.L1Unstructured)\n self.assertIsInstance(hook[1], torch.nn.utils.prune.LnStructured)\n\n # check that all entries that are 0 in the 1st mask are 0 in the\n # 2nd mask too\n self.assertTrue(torch.all(m.weight_mask[weight_mask0 == 0] == 0))\n\n # prune again\n prune.ln_structured(m, name='weight', amount=0.1, n=float('inf'), dim=1)\n # check that container._tensor_name is correctly set no matter how\n # many pruning methods are in the container\n hook = next(iter(m._forward_pre_hooks.values()))\n self.assertEqual(hook._tensor_name, 'weight')\n\n def test_pruning_container(self):\n # create an empty container\n container = prune.PruningContainer()\n container._tensor_name = 'test'\n self.assertEqual(len(container), 0)\n\n p = prune.L1Unstructured(amount=2)\n p._tensor_name = 'test'\n\n # test adding a pruning method to a container\n container.add_pruning_method(p)\n\n # test error raised if tensor name is different\n q = prune.L1Unstructured(amount=2)\n q._tensor_name = 'another_test'\n with self.assertRaises(ValueError):\n container.add_pruning_method(q)\n\n # test that adding a non-pruning method object to a pruning container\n # raises a TypeError\n with self.assertRaises(TypeError):\n container.add_pruning_method(10)\n with self.assertRaises(TypeError):\n container.add_pruning_method('ugh')\n\n def test_pruning_container_compute_mask(self):\n r\"\"\"Test `compute_mask` of pruning container with a known `t` and\n `default_mask`. Indirectly checks that Ln structured pruning is\n acting on the right axis.\n \"\"\"\n # create an empty container\n container = prune.PruningContainer()\n container._tensor_name = 'test'\n\n # 1) test unstructured pruning\n # create a new pruning method\n p = prune.L1Unstructured(amount=2)\n p._tensor_name = 'test'\n # add the pruning method to the container\n container.add_pruning_method(p)\n\n # create tensor to be pruned\n t = torch.tensor([[1, 2, 3, 4], [5, 6, 7, 8]]).to(dtype=torch.float32)\n # create prior mask by hand\n default_mask = torch.tensor([[1, 1, 1, 0], [1, 1, 0, 1]])\n # since we are pruning the two lowest magnitude units, the outcome of\n # the calculation should be this:\n expected_mask = torch.tensor([[0, 0, 1, 0], [1, 1, 0, 1]])\n computed_mask = container.compute_mask(t, default_mask)\n # TODO(#38095): Replace assertEqualIgnoreType. See issue #38095\n self.assertEqualIgnoreType(expected_mask, computed_mask)\n\n # 2) test structured pruning\n q = prune.LnStructured(amount=1, n=2, dim=0)\n q._tensor_name = 'test'\n container.add_pruning_method(q)\n # since we are pruning the lowest magnitude one of the two rows, the\n # outcome of the calculation should be this:\n expected_mask = torch.tensor([[0, 0, 0, 0], [1, 1, 0, 1]])\n computed_mask = container.compute_mask(t, default_mask)\n # TODO(#38095): Replace assertEqualIgnoreType. See issue #38095\n self.assertEqualIgnoreType(expected_mask, computed_mask)\n\n # 2) test structured pruning, along another axis\n r = prune.LnStructured(amount=1, n=2, dim=1)\n r._tensor_name = 'test'\n container.add_pruning_method(r)\n # since we are pruning the lowest magnitude of the four columns, the\n # outcome of the calculation should be this:\n expected_mask = torch.tensor([[0, 1, 1, 0], [0, 1, 0, 1]])\n computed_mask = container.compute_mask(t, default_mask)\n # TODO(#38095): Replace assertEqualIgnoreType. See issue #38095\n self.assertEqualIgnoreType(expected_mask, computed_mask)\n\n def test_l1_unstructured_pruning(self):\n r\"\"\"Test that l1 unstructured pruning actually removes the lowest\n entries by l1 norm (by hand). It also checks that applying l1\n unstructured pruning more than once respects the previous mask.\n \"\"\"\n m = nn.Linear(4, 2)\n # modify its weight matrix by hand\n m.weight = torch.nn.Parameter(\n torch.tensor(\n [[1, 2, 3, 4], [-4, -3, -2, -1]], dtype=torch.float32\n )\n )\n\n prune.l1_unstructured(m, 'weight', amount=2)\n expected_weight = torch.tensor([[0, 2, 3, 4], [-4, -3, -2, 0]])\n # TODO(#38095): Replace assertEqualIgnoreType. See issue #38095\n self.assertEqualIgnoreType(expected_weight, m.weight)\n\n # check that pruning again removes the next two smallest entries\n prune.l1_unstructured(m, 'weight', amount=2)\n expected_weight = torch.tensor([[0, 0, 3, 4], [-4, -3, 0, 0]])\n # TODO(#38095): Replace assertEqualIgnoreType. See issue #38095\n self.assertEqualIgnoreType(expected_weight, m.weight)\n\n def test_l1_unstructured_pruning_with_importance_scores(self):\n r\"\"\"Test that l1 unstructured pruning actually removes the lowest\n entries of importance scores and not the parameter by l1 norm (by hand).\n It also checks that applying l1 unstructured pruning more than once\n respects the previous mask.\n \"\"\"\n m = nn.Linear(4, 2)\n # modify its weight matrix by hand\n m.weight = torch.nn.Parameter(\n torch.tensor(\n [[1, 2, 3, 4], [-4, -3, -2, -1]], dtype=torch.float32\n )\n )\n importance_scores = torch.tensor(\n [[4, 2, 1, 3], [-3, -1, -2, -4]], dtype=torch.float32\n )\n\n prune.l1_unstructured(m, 'weight', amount=2, importance_scores=importance_scores)\n expected_weight = torch.tensor([[1, 2, 0, 4], [-4, 0, -2, -1]])\n # TODO(#38095): Replace assertEqualIgnoreType. See issue #38095\n self.assertEqualIgnoreType(expected_weight, m.weight)\n\n # check that pruning again removes two entries of m.weight that are colocated with\n # the next two smallest absolute values of importance scores.\n prune.l1_unstructured(m, 'weight', amount=2, importance_scores=importance_scores)\n expected_weight = torch.tensor([[1, 0, 0, 4], [-4, 0, 0, -1]])\n # TODO(#38095): Replace assertEqualIgnoreType. See issue #38095\n self.assertEqualIgnoreType(expected_weight, m.weight)\n\n def test_unstructured_pruning_same_magnitude(self):\n r\"\"\"Since it may happen that the tensor to prune has entries with the\n same exact magnitude, it is important to check that pruning happens\n consistenly based on the bottom % of weights, and not by threshold,\n which would instead kill off *all* units with magnitude = threshold.\n \"\"\"\n AMOUNT = 0.2\n p = prune.L1Unstructured(amount=AMOUNT)\n # create a random tensors with entries in {-2, 0, 2}\n t = 2 * torch.randint(low=-1, high=2, size=(10, 7))\n nparams_toprune = prune._compute_nparams_toprune(AMOUNT, t.nelement())\n\n computed_mask = p.compute_mask(t, default_mask=torch.ones_like(t))\n nparams_pruned = torch.sum(computed_mask == 0)\n self.assertEqual(nparams_toprune, nparams_pruned)\n\n def test_random_structured_pruning_amount(self):\n AMOUNT = 0.6\n AXIS = 2\n p = prune.RandomStructured(amount=AMOUNT, dim=AXIS)\n t = 2 * torch.randint(low=-1, high=2, size=(5, 4, 2)).to(\n dtype=torch.float32\n )\n nparams_toprune = prune._compute_nparams_toprune(AMOUNT, t.shape[AXIS])\n\n computed_mask = p.compute_mask(t, default_mask=torch.ones_like(t))\n # check that 1 column is fully prune, the others are left untouched\n remaining_axes = [_ for _ in range(len(t.shape)) if _ != AXIS]\n per_column_sums = sorted(\n torch.sum(computed_mask == 0, axis=remaining_axes)\n )\n assert per_column_sums == [0, 20]\n\n def test_ln_structured_pruning(self):\n r\"\"\"Check Ln structured pruning by hand.\n \"\"\"\n m = nn.Conv2d(3, 1, 2)\n m.weight.data = torch.Tensor(\n [[[[1., 2.], [1., 2.5]],\n [[0.5, 1.], [0.1, 0.1]],\n [[-3., -5.], [0.1, -1.]]]]\n )\n # expected effect of pruning 1 of the 3 channels by L2-norm\n expected_mask_axis1 = torch.ones_like(m.weight)\n expected_mask_axis1[:, 1] = 0.\n\n prune.ln_structured(m, 'weight', amount=1, n=2, dim=1)\n self.assertEqual(expected_mask_axis1, m.weight_mask)\n\n # expected effect of pruning 1 of the 2 columns along axis -1 by L1-norm\n expected_mask_axis3 = expected_mask_axis1\n expected_mask_axis3[:, :, :, 0] = 0.\n\n prune.ln_structured(m, 'weight', amount=1, n=1, dim=-1)\n self.assertEqual(expected_mask_axis3, m.weight_mask)\n\n def test_ln_structured_pruning_importance_scores(self):\n r\"\"\"Check Ln structured pruning by hand.\n \"\"\"\n m = nn.Conv2d(3, 1, 2)\n m.weight.data = torch.Tensor(\n [[[[1., 2.], [1., 2.5]],\n [[0.5, 1.], [0.1, 0.1]],\n [[-3., -5.], [0.1, -1.]]]]\n )\n importance_scores = torch.Tensor(\n [[[[10., 1.], [10., 1.]],\n [[30., 3.], [30., 3.]],\n [[-20., -2.], [-20., -2.]]]]\n )\n # expected effect of pruning 1 of the 3 channels by L2-norm\n expected_mask_axis1 = torch.ones_like(m.weight)\n expected_mask_axis1[:, 0] = 0.\n\n prune.ln_structured(m, 'weight', amount=1, n=2, dim=1, importance_scores=importance_scores)\n self.assertEqual(expected_mask_axis1, m.weight_mask)\n\n # expected effect of pruning 1 of the 2 columns along axis -1 by L1-norm\n expected_mask_axis3 = expected_mask_axis1\n expected_mask_axis3[:, :, :, 1] = 0.\n\n prune.ln_structured(m, 'weight', amount=1, n=1, dim=-1, importance_scores=importance_scores)\n self.assertEqual(expected_mask_axis3, m.weight_mask)\n\n def test_remove_pruning(self):\n r\"\"\"`prune.remove` removes the hook and the reparametrization\n and makes the pruning final in the original parameter.\n \"\"\"\n modules = [nn.Linear(5, 7), nn.Conv3d(2, 2, 2)]\n names = ['weight', 'bias']\n\n for m in modules:\n for name in names:\n with self.subTest(m=m, name=name):\n # first prune\n prune.random_unstructured(m, name, amount=0.5)\n self.assertIn(name + \"_orig\", dict(m.named_parameters()))\n self.assertIn(name + \"_mask\", dict(m.named_buffers()))\n self.assertNotIn(name, dict(m.named_parameters()))\n self.assertTrue(hasattr(m, name))\n pruned_t = getattr(m, name)\n\n # then remove pruning\n prune.remove(m, name)\n self.assertIn(name, dict(m.named_parameters()))\n self.assertNotIn(name + \"_orig\", dict(m.named_parameters()))\n self.assertNotIn(name + \"_mask\", dict(m.named_buffers()))\n final_t = getattr(m, name)\n\n self.assertEqual(pruned_t, final_t)\n\n def test_remove_pruning_exception(self):\n r\"\"\"Removing from an unpruned tensor throws an assertion error\n \"\"\"\n modules = [nn.Linear(5, 7), nn.Conv3d(2, 2, 2)]\n names = ['weight', 'bias']\n\n for m in modules:\n for name in names:\n with self.subTest(m=m, name=name):\n # check that the module isn't pruned\n self.assertFalse(prune.is_pruned(m))\n # since it isn't pruned, pruning can't be removed from it\n with self.assertRaises(ValueError):\n prune.remove(m, name)\n\n\n def test_global_pruning(self):\n r\"\"\"Test that global l1 unstructured pruning over 2 parameters removes\n the `amount=4` smallest global weights across the 2 parameters.\n \"\"\"\n m = nn.Linear(4, 2)\n n = nn.Linear(3, 1)\n # modify the weight matrices by hand\n m.weight = torch.nn.Parameter(\n torch.tensor([[1, 2, 3, 4], [-4, -3, -2, -1]]).to(\n dtype=torch.float32)\n )\n n.weight = torch.nn.Parameter(\n torch.tensor([[0, 0.1, -2]]).to(\n dtype=torch.float32)\n )\n\n params_to_prune = (\n (m, 'weight'),\n (n, 'weight'),\n )\n\n # prune the 4 smallest weights globally by L1 magnitude\n prune.global_unstructured(\n params_to_prune,\n pruning_method=prune.L1Unstructured,\n amount=4\n )\n\n expected_mweight = torch.tensor([[0, 2, 3, 4], [-4, -3, -2, 0]])\n # TODO(#38095): Replace assertEqualIgnoreType. See issue #38095\n self.assertEqualIgnoreType(expected_mweight, m.weight)\n\n expected_nweight = torch.tensor([[0, 0, -2]]).to(dtype=n.weight.dtype)\n self.assertEqual(expected_nweight, n.weight)\n\n def test_global_pruning_importance_scores(self):\n r\"\"\"Test that global l1 unstructured pruning over 2 parameters removes\n the `amount=4` smallest global weights across the 2 parameters.\n \"\"\"\n m = nn.Linear(4, 2)\n n = nn.Linear(3, 1)\n # modify the weight matrices by hand\n m.weight = torch.nn.Parameter(\n torch.tensor([[1, 2, 3, 4], [-4, -3, -2, -1]]).to(\n dtype=torch.float32)\n )\n m_importance_scores = torch.tensor(\n [[4, 2, 1, 3], [-3, -1, -2, -4]], dtype=torch.float32\n )\n n.weight = torch.nn.Parameter(\n torch.tensor([[0, 0.1, -2]]).to(\n dtype=torch.float32)\n )\n n_importance_scores = torch.tensor([[0, 10., -0.2]]).to(dtype=torch.float32)\n\n params_to_prune = (\n (m, 'weight'),\n (n, 'weight'),\n )\n importance_scores = {\n (m, 'weight'): m_importance_scores,\n (n, 'weight'): n_importance_scores,\n }\n\n # prune the 4 smallest weights globally by L1 magnitude\n prune.global_unstructured(\n params_to_prune,\n pruning_method=prune.L1Unstructured,\n amount=4,\n importance_scores=importance_scores,\n )\n\n expected_m_weight = torch.tensor([[1, 2, 0, 4], [-4, 0, -2, -1]])\n # TODO(#38095): Replace assertEqualIgnoreType. See issue #38095\n self.assertEqualIgnoreType(expected_m_weight, m.weight)\n\n expected_n_weight = torch.tensor([[0, 0.1, 0]]).to(dtype=n.weight.dtype)\n self.assertEqual(expected_n_weight, n.weight)\n\n def test_custom_from_mask_pruning(self):\n r\"\"\"Test that the CustomFromMask is capable of receiving\n as input at instantiation time a custom mask, and combining it with\n the previous default mask to generate the correct final mask.\n \"\"\"\n # new mask\n mask = torch.tensor([[0, 1, 1, 0], [0, 0, 1, 1]])\n # old mask\n default_mask = torch.tensor([[0, 0, 0, 0], [1, 1, 1, 1]])\n\n # some tensor (not actually used)\n t = torch.rand_like(mask.to(dtype=torch.float32))\n\n p = prune.CustomFromMask(mask=mask)\n\n computed_mask = p.compute_mask(t, default_mask)\n expected_mask = torch.tensor([[0, 0, 0, 0], [0, 0, 1, 1]]).to(\n dtype=t.dtype\n )\n\n # TODO(#38095): Replace assertEqualIgnoreType. See issue #38095\n self.assertEqualIgnoreType(computed_mask, expected_mask)\n\n def test_pruning_rollback(self):\n r\"\"\"Test that if something fails when the we try to compute the mask,\n then the model isn't left in some intermediate half-pruned state.\n The try/except statement in `apply` should handle rolling back\n to the previous state before pruning began.\n \"\"\"\n modules = [nn.Linear(5, 7), nn.Conv3d(2, 2, 2)]\n names = ['weight', 'bias']\n\n for m in modules:\n for name in names:\n with self.subTest(m=m, name=name):\n\n with mock.patch(\n \"torch.nn.utils.prune.L1Unstructured.compute_mask\"\n ) as compute_mask:\n compute_mask.side_effect = Exception('HA!')\n with self.assertRaises(Exception):\n prune.l1_unstructured(m, name=name, amount=0.9)\n\n self.assertTrue(\n name in dict(m.named_parameters())\n )\n self.assertFalse(\n name + '_mask' in dict(m.named_buffers())\n )\n self.assertFalse(\n name + '_orig' in dict(m.named_parameters())\n )\n\n def test_pruning_serialization_model(self):\n # create a model\n model = torch.nn.Sequential(\n torch.nn.Linear(10, 10),\n torch.nn.ReLU(),\n torch.nn.Linear(10, 1),\n )\n # check that everything looks normal before pruning\n self.assertNotIn('0.weight_orig', model.state_dict())\n self.assertNotIn('0.weight_mask', model.state_dict())\n self.assertIn('0.weight', model.state_dict())\n\n # prune one of its parameters\n prune.l1_unstructured(module=model[0], name='weight', amount=0.9)\n\n # check that the original weight and the new mask are present\n self.assertIn('0.weight_orig', model.state_dict())\n self.assertIn('0.weight_mask', model.state_dict())\n self.assertNotIn('0.weight', model.state_dict())\n self.assertTrue(hasattr(model[0], 'weight'))\n\n pruned_weight = model[0].weight\n\n with TemporaryFileName() as fname:\n torch.save(model, fname)\n new_model = torch.load(fname)\n\n # check that the original weight and the new mask are present\n self.assertIn('0.weight_orig', new_model.state_dict())\n self.assertIn('0.weight_mask', new_model.state_dict())\n self.assertNotIn('0.weight', new_model.state_dict())\n self.assertTrue(hasattr(new_model[0], 'weight'))\n\n self.assertEqual(pruned_weight, new_model[0].weight)\n\n def test_pruning_serialization_state_dict(self):\n # create a model\n model = torch.nn.Sequential(\n torch.nn.Linear(10, 10),\n torch.nn.ReLU(),\n torch.nn.Linear(10, 1),\n )\n # check that everything looks normal before pruning\n self.assertNotIn('0.weight_orig', model.state_dict())\n self.assertNotIn('0.weight_mask', model.state_dict())\n self.assertIn('0.weight', model.state_dict())\n\n # prune one of its parameters\n prune.l1_unstructured(module=model[0], name='weight', amount=0.9)\n\n # check that the original weight and the new mask are present\n self.assertIn('0.weight_orig', model.state_dict())\n self.assertIn('0.weight_mask', model.state_dict())\n self.assertNotIn('0.weight', model.state_dict())\n self.assertTrue(hasattr(model[0], 'weight'))\n\n pruned_weight = model[0].weight\n\n # make pruning permanent and restore parameter names as in base\n # architecture\n prune.remove(module=model[0], name='weight')\n\n # check that the original weight and the new mask are no longer present\n self.assertNotIn('0.weight_orig', model.state_dict())\n self.assertNotIn('0.weight_mask', model.state_dict())\n self.assertIn('0.weight', model.state_dict())\n\n # save the state dict of model and reload it into new_model\n new_model = torch.nn.Sequential(\n torch.nn.Linear(10, 10),\n torch.nn.ReLU(),\n torch.nn.Linear(10, 1),\n )\n with TemporaryFileName() as fname:\n torch.save(model.state_dict(), fname)\n new_model.load_state_dict(torch.load(fname))\n\n # check that the original weight and the new mask are not present in\n # new_model either.\n self.assertNotIn('0.weight_orig', new_model.state_dict())\n self.assertNotIn('0.weight_mask', new_model.state_dict())\n self.assertIn('0.weight', new_model.state_dict())\n\n self.assertEqual(pruned_weight, new_model[0].weight)\n\n def test_prune(self):\n # create a new pruning method\n p = prune.L1Unstructured(amount=2)\n # create tensor to be pruned\n t = torch.tensor([[1, 2, 3, 4], [5, 6, 7, 8]]).to(dtype=torch.float32)\n # create prior mask by hand\n default_mask = torch.tensor([[1, 1, 1, 0], [1, 1, 0, 1]])\n # since we are pruning the two lowest magnitude units, the outcome of\n # the calculation should be this:\n expected_mask = torch.tensor([[0, 0, 1, 0], [1, 1, 0, 1]])\n pruned_tensor = p.prune(t, default_mask)\n self.assertEqual(t * expected_mask, pruned_tensor)\n\n def test_prune_importance_scores(self):\n # create a new pruning method\n p = prune.L1Unstructured(amount=2)\n # create tensor to be pruned\n t = torch.tensor([[1, 2, 3, 4], [5, 6, 7, 8]]).to(dtype=torch.float32)\n importance_scores = torch.tensor(\n [[1, 2, 3, 4], [1.5, 1.6, 1.7, 1.8]]\n ).to(dtype=torch.float32)\n # create prior mask by hand\n default_mask = torch.tensor([[1, 1, 1, 0], [1, 1, 0, 1]])\n # since we are pruning the two lowest magnitude units, the outcome of\n # the calculation should be this:\n expected_mask = torch.tensor([[0, 1, 1, 0], [0, 1, 0, 1]])\n pruned_tensor = p.prune(t, default_mask, importance_scores=importance_scores)\n self.assertEqual(t * expected_mask, pruned_tensor)\n\n def test_prune_importance_scores_mimic_default(self):\n # create a new pruning method\n p = prune.L1Unstructured(amount=2)\n # create tensor to be pruned\n t = torch.tensor([[1, 2, 3, 4], [5, 6, 7, 8]]).to(dtype=torch.float32)\n # create prior mask by hand\n default_mask = torch.tensor([[1, 1, 1, 0], [1, 1, 0, 1]])\n # since we are pruning the two lowest magnitude units, the outcome of\n # the calculation should be this:\n expected_mask = torch.tensor([[0, 0, 1, 0], [1, 1, 0, 1]])\n pruned_tensor_without_importance_scores = p.prune(t, default_mask)\n pruned_tensor_with_importance_scores = p.prune(t, default_mask, importance_scores=t)\n self.assertEqual(pruned_tensor_without_importance_scores, pruned_tensor_with_importance_scores)\n self.assertEqual(t * expected_mask, pruned_tensor_without_importance_scores)\n\n def test_rnn_pruning(self):\n l = torch.nn.LSTM(32, 32)\n # This Module has 4 parameters called:\n # 'weight_ih_l0', 'weight_hh_l0', 'bias_ih_l0', 'bias_hh_l0'\n\n # Pruning one of them causes one of the weights to become a tensor\n prune.l1_unstructured(l, 'weight_ih_l0', 0.5)\n assert (\n sum([isinstance(p, torch.nn.Parameter) for p in l._flat_weights])\n == 3\n )\n\n # Removing the pruning reparametrization restores the Parameter\n prune.remove(l, 'weight_ih_l0')\n assert (\n sum([isinstance(p, torch.nn.Parameter) for p in l._flat_weights])\n == 4\n )\n\n # Make sure that, upon removal of the reparametrization, the\n # `._parameters` and `.named_parameters` contain the right params.\n # Specifically, the original weight ('weight_ih_l0') should be placed\n # back in the parameters, while the reparametrization component\n # ('weight_ih_l0_orig') should be removed.\n assert 'weight_ih_l0' in l._parameters\n assert l._parameters['weight_ih_l0'] is not None\n assert 'weight_ih_l0_orig' not in l._parameters\n assert 'weight_ih_l0' in dict(l.named_parameters())\n assert dict(l.named_parameters())['weight_ih_l0'] is not None\n assert 'weight_ih_l0_orig' not in dict(l.named_parameters())\n\n\n def test_rnn_weight_norm(self):\n def check_weight_norm(l, name, num_params):\n # This Module has 4 or 5 parameters called:\n # 'weight_ih_l0', 'weight_hh_l0', 'bias_ih_l0', 'bias_hh_l0', weight_hr_l0\n\n # Applying weight norm on one of them causes it to become a tensor\n l = torch.nn.utils.weight_norm(l, name=name)\n self.assertEqual(\n sum([isinstance(p, torch.nn.Parameter) for p in l._flat_weights]),\n num_params - 1,\n )\n\n # Removing the weight norm reparametrization restores the Parameter\n l = torch.nn.utils.remove_weight_norm(l, name=name)\n self.assertEqual(\n sum([isinstance(p, torch.nn.Parameter) for p in l._flat_weights]),\n num_params,\n )\n\n # Make sure that, upon removal of the reparametrization, the\n # `._parameters` and `.named_parameters` contain the right params.\n # Specifically, the original weight ('weight_ih_l0') should be placed\n # back in the parameters, while the reparametrization components\n # ('weight_ih_l0_v' and 'weight_ih_l0_g') should be removed.\n self.assertTrue(name in l._parameters)\n self.assertIsNotNone(l._parameters[name])\n self.assertTrue(name + '_v' not in l._parameters)\n self.assertTrue(name + '_g' not in l._parameters)\n self.assertTrue(name in dict(l.named_parameters()))\n self.assertIsNotNone(dict(l.named_parameters())[name])\n self.assertTrue(name + '_v' not in dict(l.named_parameters()))\n self.assertTrue(name + '_g' not in dict(l.named_parameters()))\n\n check_weight_norm(torch.nn.LSTM(32, 32), 'weight_ih_l0', 4)\n check_weight_norm(torch.nn.LSTM(32, 32, proj_size=16), 'weight_hr_l0', 5)\n\n\n def test_weight_norm(self):\n input = torch.randn(3, 5)\n m = nn.Linear(5, 7)\n expected_output = m(input)\n\n # add weight normalization\n m = torch.nn.utils.weight_norm(m)\n self.assertEqual(m.weight_v.size(), m.weight.size())\n self.assertEqual(m.weight_g.size(), (7, 1))\n self.assertEqual(m(input), expected_output)\n\n # remove weight norm\n m = torch.nn.utils.remove_weight_norm(m)\n self.assertFalse(hasattr(m, 'weight_g'))\n self.assertFalse(hasattr(m, 'weight_v'))\n self.assertEqual(m(input), expected_output)\n\n # test with dim=1\n m = torch.nn.utils.weight_norm(m, dim=1)\n self.assertEqual(m.weight_v.size(), m.weight.size())\n self.assertEqual(m.weight_g.size(), (1, 5))\n self.assertEqual(m(input), expected_output)\n\n # test with dim=None\n m = nn.Linear(5, 7)\n expected_output = m(input)\n m = torch.nn.utils.weight_norm(m, dim=None)\n self.assertEqual(m(input), expected_output)\n\n with self.assertRaisesRegex(RuntimeError, 'register two weight_norm hooks'):\n m = torch.nn.utils.weight_norm(m)\n m = torch.nn.utils.weight_norm(m)\n\n def test_parameterlistdict_setting_attributes(self):\n with warnings.catch_warnings(record=True) as w:\n mod = nn.ParameterList(map(nn.Parameter, [torch.rand(2), torch.rand(2)]))\n self.assertTrue(len(w) == 0)\n\n with warnings.catch_warnings(record=True) as w:\n mod.train()\n mod.eval()\n self.assertTrue(len(w) == 0)\n\n with self.assertWarnsRegex(UserWarning,\n r\"Setting attributes on ParameterList is not supported\"):\n torch.nn.utils.weight_norm(mod, \"0\")\n\n with warnings.catch_warnings(record=True) as w:\n mod = nn.ParameterDict({\"a\": nn.Parameter(torch.rand(2)), \"b\": nn.Parameter(torch.rand(2))})\n self.assertTrue(len(w) == 0)\n\n with warnings.catch_warnings(record=True) as w:\n mod.train()\n mod.eval()\n self.assertTrue(len(w) == 0)\n\n with self.assertWarnsRegex(UserWarning,\n r\"Setting attributes on ParameterDict is not supported\"):\n torch.nn.utils.weight_norm(mod, \"b\")\n\n def test_parameterlistdict_pickle(self):\n m = nn.ParameterList(map(nn.Parameter, [torch.rand(2), torch.rand(2)]))\n with warnings.catch_warnings(record=True) as w:\n m = pickle.loads(pickle.dumps(m))\n self.assertTrue(len(w) == 0)\n\n m = nn.ParameterList(map(nn.Parameter, [torch.rand(2), torch.rand(2)]))\n del m._initialized\n with warnings.catch_warnings(record=True) as w:\n m = pickle.loads(pickle.dumps(m))\n self.assertTrue(len(w) == 0)\n\n # Test whether loading from older checkpoints works without triggering warnings\n m = nn.ParameterList(map(nn.Parameter, [torch.rand(2), torch.rand(2)]))\n del m._forward_pre_hooks, m._state_dict_hooks, m._load_state_dict_pre_hooks, m._non_persistent_buffers_set\n with warnings.catch_warnings(record=True) as w:\n m = pickle.loads(pickle.dumps(m))\n self.assertTrue(len(w) == 0)\n\n m = nn.ParameterDict({\"a\": nn.Parameter(torch.rand(2)), \"b\": nn.Parameter(torch.rand(2))})\n with warnings.catch_warnings(record=True) as w:\n m = pickle.loads(pickle.dumps(m))\n self.assertTrue(len(w) == 0)\n\n m = nn.ParameterDict({\"a\": nn.Parameter(torch.rand(2)), \"b\": nn.Parameter(torch.rand(2))})\n del m._initialized\n with warnings.catch_warnings(record=True) as w:\n m = pickle.loads(pickle.dumps(m))\n self.assertTrue(len(w) == 0)\n\n # Test whether loading from older checkpoints works without triggering warnings\n m = nn.ParameterDict({\"a\": nn.Parameter(torch.rand(2)), \"b\": nn.Parameter(torch.rand(2))})\n del m._forward_pre_hooks, m._state_dict_hooks, m._load_state_dict_pre_hooks, m._non_persistent_buffers_set\n with warnings.catch_warnings(record=True) as w:\n m = pickle.loads(pickle.dumps(m))\n self.assertTrue(len(w) == 0)\n\n def test_weight_norm_pickle(self):\n m = torch.nn.utils.weight_norm(nn.Linear(5, 7))\n m = pickle.loads(pickle.dumps(m))\n self.assertIsInstance(m, nn.Linear)\n\n def test_spectral_norm(self):\n input = torch.randn(3, 5)\n m = nn.Linear(5, 7)\n m = torch.nn.utils.spectral_norm(m)\n\n self.assertEqual(m.weight_u.size(), torch.Size([m.weight.size(0)]))\n # weight_orig should be trainable\n self.assertTrue(hasattr(m, 'weight_orig'))\n self.assertTrue('weight_orig' in m._parameters)\n # weight_u should be just a reused buffer\n self.assertTrue(hasattr(m, 'weight_u'))\n self.assertTrue('weight_u' in m._buffers)\n self.assertTrue('weight_v' in m._buffers)\n # weight should be a plain attribute, not counted as a buffer or a param\n self.assertFalse('weight' in m._buffers)\n self.assertFalse('weight' in m._parameters)\n # it should also be sharing storage as `weight_orig`\n self.assertEqual(m.weight_orig.storage(), m.weight.storage())\n self.assertEqual(m.weight_orig.size(), m.weight.size())\n self.assertEqual(m.weight_orig.stride(), m.weight.stride())\n\n m = torch.nn.utils.remove_spectral_norm(m)\n self.assertFalse(hasattr(m, 'weight_orig'))\n self.assertFalse(hasattr(m, 'weight_u'))\n # weight should be converted back as a parameter\n self.assertTrue(hasattr(m, 'weight'))\n self.assertTrue('weight' in m._parameters)\n\n with self.assertRaisesRegex(RuntimeError, 'register two spectral_norm hooks'):\n m = torch.nn.utils.spectral_norm(m)\n m = torch.nn.utils.spectral_norm(m)\n\n # test correctness in training/eval modes and cpu/multi-gpu settings\n for apply_dp in (True, False):\n if apply_dp:\n if not TEST_MULTIGPU:\n continue\n device = torch.device('cuda:0')\n\n def maybe_wrap(m):\n return torch.nn.DataParallel(m, [0, 1])\n else:\n device = torch.device('cpu')\n\n def maybe_wrap(m):\n return m\n\n for requires_grad in (True, False):\n m = nn.Linear(3, 4).to(device)\n m.weight.requires_grad_(requires_grad)\n m = torch.nn.utils.spectral_norm(m)\n wrapped_m = maybe_wrap(m)\n self.assertTrue(hasattr(m, 'weight_u'))\n u0 = m.weight_u.clone()\n v0 = m.weight_v.clone()\n\n # TEST TRAINING BEHAVIOR\n\n # assert that u and v are updated\n input = torch.randn(2, 3, device=device)\n out = wrapped_m(input)\n self.assertNotEqual(u0, m.weight_u)\n self.assertNotEqual(v0, m.weight_v)\n\n # assert that backprop reaches weight_orig\n # can't use gradcheck because the function changes as we\n # activate through it in training mode\n if requires_grad:\n torch.autograd.grad(out.sum(), m.weight_orig)\n\n # test backward works with multiple forwards\n # it uses training mode so we need to reset `u` and `v` vectors\n # to same value at beginning for finite difference test to pass\n saved_u = m.weight_u.clone()\n saved_v = m.weight_v.clone()\n\n def fn(input):\n m.weight_u.data.copy_(saved_u)\n m.weight_v.data.copy_(saved_v)\n out0 = wrapped_m(input)\n out1 = wrapped_m(input)\n return out0 + out1\n\n gradcheck(fn, (input.clone().requires_grad_(),), check_batched_grad=False)\n\n # test removing\n pre_remove_out = wrapped_m(input)\n m = torch.nn.utils.remove_spectral_norm(m)\n self.assertEqual(wrapped_m(input), pre_remove_out)\n\n m = torch.nn.utils.spectral_norm(m)\n for _ in range(3):\n pre_remove_out = wrapped_m(input)\n m = torch.nn.utils.remove_spectral_norm(m)\n self.assertEqual(wrapped_m(input), pre_remove_out)\n\n # TEST EVAL BEHAVIOR\n\n m = torch.nn.utils.spectral_norm(m)\n wrapped_m(input)\n last_train_out = wrapped_m(input)\n last_train_u = m.weight_u.clone()\n last_train_v = m.weight_v.clone()\n wrapped_m.zero_grad()\n wrapped_m.eval()\n\n eval_out0 = wrapped_m(input)\n # assert eval gives same result as last training iteration\n self.assertEqual(eval_out0, last_train_out)\n # assert doing more iteartion in eval don't change things\n self.assertEqual(eval_out0, wrapped_m(input))\n self.assertEqual(last_train_u, m.weight_u)\n self.assertEqual(last_train_v, m.weight_v)\n\n # FIXME: the code below is flaky when executed with DataParallel\n # see https://github.com/pytorch/pytorch/issues/13818\n if apply_dp:\n continue\n\n # test backward works with multiple forwards in mixed training\n # and eval modes\n # it uses training mode so we need to reset `u` and `v` vectors\n # to same value at beginning for finite difference test to pass\n saved_u = m.weight_u.clone()\n saved_v = m.weight_v.clone()\n\n def fn(input):\n m.weight_u.data.copy_(saved_u)\n m.weight_v.data.copy_(saved_v)\n wrapped_m.train()\n out0 = wrapped_m(input)\n wrapped_m.eval()\n out1 = wrapped_m(input)\n wrapped_m.train()\n out2 = wrapped_m(input)\n wrapped_m.eval()\n out3 = wrapped_m(input)\n return out0 + out1 + out2 + out3\n\n gradcheck(fn, (input.clone().requires_grad_(),))\n\n # assert that backprop reaches weight_orig in eval\n if requires_grad:\n def fn(weight):\n return wrapped_m(input)\n\n gradcheck(fn, (m.weight_orig,))\n\n @skipIfNoLapack\n def test_spectral_norm_load_state_dict(self):\n inp = torch.randn(2, 3)\n for activate_times in (0, 3):\n # Test backward compatibility\n # At version None -> 1: weight becomes not a buffer and v vector becomes a buffer\n m = nn.Linear(3, 5)\n snm = torch.nn.utils.spectral_norm(m)\n snm.train()\n for _ in range(activate_times):\n snm(inp)\n\n version_latest_ref_state_dict = deepcopy(snm.state_dict())\n self.assertEqual({'weight_orig', 'bias', 'weight_u', 'weight_v'}, set(version_latest_ref_state_dict.keys()))\n\n # test that non-strict loading works\n non_strict_state_dict = deepcopy(version_latest_ref_state_dict)\n non_strict_state_dict['nonsense'] = 'nonsense'\n with self.assertRaisesRegex(RuntimeError, r'Unexpected key\\(s\\) in state_dict: \"nonsense\"'):\n snm.load_state_dict(non_strict_state_dict, strict=True)\n snm.load_state_dict(non_strict_state_dict, strict=False)\n del non_strict_state_dict['weight_orig']\n snm.load_state_dict(non_strict_state_dict, strict=False)\n del non_strict_state_dict['weight_u']\n snm.load_state_dict(non_strict_state_dict, strict=False)\n del non_strict_state_dict['weight_v']\n snm.load_state_dict(non_strict_state_dict, strict=False)\n non_strict_state_dict['weight'] = snm.weight.detach().clone() # set W as a buffer\n snm.load_state_dict(non_strict_state_dict, strict=False)\n del non_strict_state_dict._metadata['']['spectral_norm'] # remove metadata info\n snm.load_state_dict(non_strict_state_dict, strict=False)\n del non_strict_state_dict['weight'] # remove W buffer\n snm.load_state_dict(non_strict_state_dict, strict=False)\n del non_strict_state_dict['bias']\n snm.load_state_dict(non_strict_state_dict, strict=False)\n\n # craft a version None state_dict\n version_none_state_dict = deepcopy(version_latest_ref_state_dict)\n self.assertIn('spectral_norm', version_none_state_dict._metadata[''])\n del version_none_state_dict._metadata['']['spectral_norm'] # remove metadata info\n del version_none_state_dict['weight_v'] # remove v vector\n version_none_state_dict['weight'] = snm.weight.detach().clone() # set W as a buffer\n\n # normal state_dict\n for version_latest_with_metadata in [True, False]:\n version_latest_state_dict = deepcopy(version_latest_ref_state_dict)\n\n if not version_latest_with_metadata:\n # We want to still load a user-crafted state_dict, one without metadata\n del version_latest_state_dict._metadata['']['spectral_norm']\n\n # test that re-wrapping does not matter\n m = torch.nn.utils.remove_spectral_norm(snm)\n snm = torch.nn.utils.spectral_norm(m)\n\n snm.load_state_dict(version_latest_ref_state_dict)\n with torch.no_grad():\n snm.eval()\n out0_eval = snm(inp)\n snm.train()\n out1_train = snm(inp)\n out2_train = snm(inp)\n snm.eval()\n out3_eval = snm(inp)\n\n # test that re-wrapping does not matter\n m = torch.nn.utils.remove_spectral_norm(snm)\n snm = torch.nn.utils.spectral_norm(m)\n\n snm.load_state_dict(version_none_state_dict)\n if activate_times > 0:\n # since in loading version None state dict, we assume that the\n # values in the state dict have gone through at lease one\n # forward, we only test for equivalence when activate_times > 0.\n with torch.no_grad():\n snm.eval()\n self.assertEqual(out0_eval, snm(inp))\n snm.train()\n self.assertEqual(out1_train, snm(inp))\n self.assertEqual(out2_train, snm(inp))\n snm.eval()\n self.assertEqual(out3_eval, snm(inp))\n\n # test that re-wrapping does not matter\n m = torch.nn.utils.remove_spectral_norm(snm)\n snm = torch.nn.utils.spectral_norm(m)\n\n # Test normal loading\n snm.load_state_dict(version_latest_state_dict)\n with torch.no_grad():\n snm.eval()\n self.assertEqual(out0_eval, snm(inp))\n snm.train()\n self.assertEqual(out1_train, snm(inp))\n self.assertEqual(out2_train, snm(inp))\n snm.eval()\n self.assertEqual(out3_eval, snm(inp))\n\n def test_spectral_norm_dim(self):\n inp = torch.randn(2, 3, 10, 12)\n m = nn.ConvTranspose2d(3, 4, (5, 6))\n m = torch.nn.utils.spectral_norm(m)\n # this should not run into incompatible shapes\n x = m(inp)\n # check that u refers to the same dimension\n self.assertEqual(m.weight_u.shape, m.weight_orig[0, :, 0, 0].shape)\n\n def test_spectral_norm_forward(self):\n input = torch.randn(3, 5)\n m = nn.Linear(5, 7)\n m = torch.nn.utils.spectral_norm(m)\n # naive forward\n _weight, _bias, _u = m.weight_orig, m.bias, m.weight_u\n _weight_mat = _weight.view(_weight.size(0), -1)\n _v = torch.mv(_weight_mat.t(), _u)\n _v = F.normalize(_v, dim=0, eps=1e-12)\n _u = torch.mv(_weight_mat, _v)\n _u = F.normalize(_u, dim=0, eps=1e-12)\n _weight.data /= torch.dot(_u, torch.matmul(_weight_mat, _v))\n out_hat = torch.nn.functional.linear(input, _weight, _bias)\n expect_out = m(input)\n self.assertEqual(expect_out, out_hat)\n\n def test_spectral_norm_pickle(self):\n m = torch.nn.utils.spectral_norm(nn.Linear(5, 7))\n m = pickle.loads(pickle.dumps(m))\n self.assertIsInstance(m, nn.Linear)\n\n def test_threshold_int(self):\n x = torch.tensor([-3, -2, -1, 0, 1, 2, 3])\n expected = torch.tensor([99, 99, 99, 99, 1, 2, 3])\n self.assertEqual(F.threshold(x, 0, 99), expected)\n\n def test_threshold_bfloat16(self):\n x = torch.randn(100)\n for threshold in [0, -0.5, 0.5, float('inf'), float('-inf'), float('nan')]:\n expected = F.threshold(x, threshold, 0).bfloat16().float()\n res_bf16 = F.threshold(x.bfloat16(), threshold, 0).float()\n self.assertEqual(res_bf16, expected)\n\n @unittest.skipIf(not TEST_CUDA, \"CUDA unavailable\")\n def test_embedding_max_norm_unsorted_repeating_indices(self):\n def create_embedding(device):\n # Seed RNG so we get the same Embedding each time\n torch.manual_seed(0)\n return torch.nn.Embedding(\n num_embeddings=20,\n embedding_dim=64,\n max_norm=1.0).to(device)\n\n ix = torch.arange(2, device='cpu', dtype=torch.long).repeat(2000)\n out_cpu = create_embedding('cpu')(ix)\n\n ix = ix.to('cuda')\n out = create_embedding('cuda')(ix)\n self.assertEqual(out.cpu(), out_cpu)\n\n def test_embedding_sparse_basic(self):\n embedding = nn.Embedding(10, 20, sparse=True)\n input = torch.tensor([[0, 2, 4, 5], [4, 3, 0, 9]], dtype=torch.long)\n embedding(input).sum().backward()\n self.assertTrue(embedding.weight.grad.is_sparse)\n self.assertEqual(embedding.weight.grad.shape, embedding.weight.shape)\n\n def test_embedding_sparse_empty_tensor(self):\n embedding = nn.Embedding(0, 0, sparse=True)\n input = torch.tensor([], dtype=torch.int64)\n embedding(input).sum().backward()\n self.assertTrue(embedding.weight.grad.is_sparse)\n self.assertEqual(embedding.weight.grad.shape, embedding.weight.shape)\n\n embedding = nn.Embedding(10, 0, sparse=True)\n input = torch.LongTensor([[0, 2, 4, 5], [4, 3, 0, 9]])\n embedding(input).sum().backward()\n self.assertTrue(embedding.weight.grad.is_sparse)\n self.assertEqual(embedding.weight.grad.shape, embedding.weight.shape)\n\n def test_move_sparse_half_embedding(self):\n embedding = nn.Embedding(10, 3, sparse=True)\n self.assertEqual(embedding.weight.device.type, 'cpu')\n self.assertEqual(embedding.weight.dtype, torch.float64)\n embedding.to(torch.float16)\n self.assertEqual(embedding.weight.dtype, torch.float16)\n self.assertEqual(embedding.embedding_dim, 3)\n self.assertEqual(embedding.num_embeddings, 10)\n\n if torch.cuda.is_available():\n embedding.to('cuda')\n self.assertEqual(embedding.weight.device.type, 'cuda')\n embedding.to('cpu')\n self.assertEqual(embedding.weight.device.type, 'cpu')\n\n def test_embedding_max_norm(self):\n embedding = nn.Embedding(22, 5, max_norm=1.0)\n input = torch.tensor([2, 8, 8, 6], dtype=torch.long)\n output = embedding(input)\n self.assertEqual(output[1], output[2])\n self.assertTrue(output.data.norm(p=2, dim=1).le(1).all())\n\n def test_embedding_from_pretrained(self):\n a = torch.Tensor([[1, 2, 3], [4, 5, 6]])\n embedding = nn.Embedding.from_pretrained(a)\n self.assertEqual(a, embedding.weight.data)\n\n input = torch.LongTensor([0, 1])\n output = embedding(input)\n self.assertEqual(a, output)\n\n def test_embedding_from_pretrained_padding_idx(self):\n padding_idx = 2\n padding_vec = torch.ones(3) * 7\n embeddings = torch.rand(4, 3, requires_grad=True)\n with torch.no_grad():\n embeddings[padding_idx] = padding_vec\n embedding_nn = nn.Embedding.from_pretrained(embeddings, padding_idx=padding_idx)\n self.assertEqual(embedding_nn.weight[padding_idx], padding_vec)\n\n def test_embedding_from_pretrained_options(self):\n a = torch.Tensor([[1, 2, 3], [4, 5, 6]])\n opts = {\n \"max_norm\": 2.,\n \"norm_type\": .5,\n \"scale_grad_by_freq\": False,\n \"sparse\": True\n }\n embedding = nn.Embedding.from_pretrained(a, **opts)\n input = torch.LongTensor([0, 1])\n output = embedding(input)\n # test output and that weight matrix was renormalized\n self.assertEqual(a, output)\n self.assertTrue(a.ne(torch.arange(1, 7, dtype=a.dtype).view(2, 3)).all())\n self.assertTrue(output.data.norm(p=opts[\"norm_type\"], dim=1).le(opts[\"max_norm\"]).all())\n\n def test_embedding_functional(self):\n a = torch.tensor([\n [1, 3, 2],\n [0, 2, 1]\n ], dtype=torch.long)\n embeddings = torch.rand(4, 3, requires_grad=True)\n\n embed_old = torch.nn.Embedding(4, 3)\n embed_old.weight.data = embeddings.data\n res_old = embed_old(a)\n\n res_F = F.embedding(a, embeddings)\n self.assertEqual(res_old, res_F)\n\n embed_old = torch.nn.Embedding(4, 3)\n embed_old = embed_old.from_pretrained(embeddings, padding_idx=2)\n res_old = embed_old(a)\n res_F = F.embedding(a, embeddings, padding_idx=2)\n\n self.assertEqual(res_old, res_F)\n\n @unittest.skipUnless('fbgemm' in torch.backends.quantized.supported_engines,\n 'Linear_FP16_weight requires FBGEMM. FBGEMM is only optimized for CPUs'\n ' with instruction set support avx2 or newer.')\n def test_fb_fc_packed(self):\n X = np.random.rand(16, 16).astype(np.float32) - 0.5\n W = np.random.rand(16, 16).astype(np.float32) - 0.5\n b = np.random.rand(16).astype(np.float32) - 0.5\n\n def fc_op(X, W, b):\n return np.dot(X, W.T) + b\n\n x_tensor = torch.tensor(X)\n w_tensor = torch.tensor(W)\n b_tensor = torch.tensor(b)\n packed_w_tensor = torch.fbgemm_pack_gemm_matrix_fp16(w_tensor)\n actual_output = torch.fbgemm_linear_fp16_weight(x_tensor, packed_w_tensor, b_tensor)\n expected_output = fc_op(X, W, b)\n torch.testing.assert_allclose(expected_output, actual_output.cpu(), atol=1e-3, rtol=1e-3)\n\n def test_embeddingbag_from_pretrained(self):\n a = torch.Tensor([[1, 2, 3], [4, 5, 6]])\n embeddingbag = nn.EmbeddingBag.from_pretrained(a)\n self.assertEqual(a, embeddingbag.weight.data)\n\n input = torch.LongTensor([[0, 1]])\n output = embeddingbag(input)\n self.assertEqual(a.mean(0, keepdim=True), output)\n\n def test_embeddingbag_from_pretrained_options(self):\n a = torch.Tensor([[1, 2, 3], [4, 5, 6]])\n opts = {\n \"max_norm\": 2.,\n \"norm_type\": .5,\n \"scale_grad_by_freq\": False,\n \"mode\": \"max\",\n \"sparse\": False\n }\n embeddingbag = nn.EmbeddingBag.from_pretrained(a, **opts)\n\n input = torch.LongTensor([[0, 1]])\n output = embeddingbag(input)\n self.assertEqual(a.max(0, keepdim=True)[0], output)\n self.assertTrue(a.ne(torch.arange(1, 7, dtype=a.dtype).view(2, 3)).all())\n self.assertTrue(a.norm(p=opts[\"norm_type\"], dim=1).le(opts[\"max_norm\"]).all())\n\n def test_AlphaDropout(self):\n # generate random tensor with zero mean and unit std\n input = torch.randn(5000)\n self._test_alpha_dropout(nn.AlphaDropout, input)\n\n def test_FeatureAlphaDropout(self):\n b = random.randint(1, 5)\n w = random.randint(1, 5)\n h = random.randint(1, 5)\n d = random.randint(1, 2)\n num_features = 1000\n input = torch.randn(num_features, b, d, w, h)\n self._test_alpha_dropout(nn.FeatureAlphaDropout, input)\n\n def test_pad_scalar_error(self):\n inputs = torch.tensor(0., requires_grad=True)\n self.assertRaises(AssertionError, lambda: F.pad(inputs, (1, 1)))\n self.assertRaises(AssertionError, lambda: F.pad(inputs, (1,)))\n\n @unittest.skipIf(not TEST_NUMPY, \"numpy not found\")\n def test_multihead_attention(self):\n def _scaled_dot_attn_ref(Q, K, V, dims, unseen_mask=None, key_padding_mask=None):\n \"\"\" Numpy-based reference implementation of scaled dot attention\n for testing\"\"\"\n\n QKT = _batchmatmul(\n Q,\n np.transpose(K, axes=[0, 1, 3, 2])\n / np.sqrt(dims[3], dtype=np.float32), # divide by sqrt(d_head)\n )\n b1, b2, s1, s2 = QKT.shape\n if unseen_mask is not None or key_padding_mask is not None:\n # assert s1 == s2\n for i in range(b1):\n for j in range(b2):\n for m in range(s1):\n for n in range(s2):\n if unseen_mask is not None and unseen_mask[m][n] == 0:\n QKT[i, j, m, n] = -np.inf\n if key_padding_mask is not None and key_padding_mask[i][n]:\n QKT[i, j, m, n] = -np.inf\n\n reference = _softmax(QKT)\n ref_attn_weight = reference\n ref_attn_weight = np.sum(ref_attn_weight, axis=1) / b2\n reference = _batchmatmul(reference, V)\n return reference, ref_attn_weight\n\n def _batchmatmul(a, b): # batchmatmul over 4 dim matrix\n \"\"\" Numpy-based batch matrix multiply over 4 dim matrix\"\"\"\n assert a.shape[0] == b.shape[0]\n assert a.shape[1] == b.shape[1]\n retval = np.zeros(\n (a.shape[0], a.shape[1], a.shape[2], b.shape[3]), dtype=np.float32\n )\n for i in range(a.shape[0]):\n for j in range(a.shape[1]):\n retval[i, j, :, :] = np.matmul(a[i, j, :, :], b[i, j, :, :])\n return retval\n\n def _softmax(x): # softmax over 4 dim matrix\n \"\"\" Numpy-based reference softmax over 4 dim matrix\"\"\"\n np.seterr(invalid='ignore')\n output = np.zeros(x.shape, dtype=np.float64)\n for i in range(x.shape[0]):\n for j in range(x.shape[1]):\n for k in range(x.shape[2]):\n x_curr = x[i, j, k, :]\n e_x = np.exp(x_curr - np.amax(x_curr))\n output[i, j, k, :] = e_x / np.sum(e_x)\n return output\n\n def _split_heads_ref(X, dims, nheads, d_head):\n X_split = np.reshape(X, dims[:2] + [nheads, d_head])\n X_split_transposed = np.transpose(X_split, [0, 2, 1, 3])\n reference = np.reshape(X_split_transposed, [dims[0], nheads, dims[1], d_head])\n return reference\n\n def _combine_heads_ref(X, dims, nheads, d_head):\n X_transposed = np.transpose(X, [0, 2, 1, 3])\n reference = np.reshape(X_transposed, dims[:2] + [nheads * d_head])\n return reference\n\n def _fc(X, X_weight, X_bias):\n X_fc_b = X_bias.detach().numpy()\n X_fc_w = X_weight.detach().numpy()\n return np.matmul(X, np.transpose(X_fc_w)) + X_fc_b\n\n def _create_src_lengths_mask(batch_size, src_lengths):\n \"\"\"\n Generate boolean mask to prevent attention beyond the end of source\n Inputs:\n batch_size : int\n src_lengths : [batch_size] of sentence lengths\n Outputs:\n [batch_size, max_src_len]\n \"\"\"\n max_srclen = src_lengths.max()\n src_indices = torch.arange(0, max_srclen).unsqueeze(0).to(src_lengths)\n src_indices = src_indices.expand(batch_size, max_srclen)\n src_lengths = src_lengths.unsqueeze(dim=1).expand(batch_size, max_srclen)\n # returns [batch_size, max_seq_len]\n return (src_indices < src_lengths).int().detach()\n\n def _multihead_attn_test_helper(add_key_padding_mask=False, add_bias_kv=False, add_zero_attn=False,\n saved_kv=False, same_embed_dim=False, byte_mask=False):\n for _ in range(100):\n batch_sz, seq_len = [random.randint(2, 10) for r in range(2)]\n d_head = random.randint(3, 10)\n nheads = random.randint(3, 10)\n d_model = d_head * nheads\n if same_embed_dim:\n kv_dim = d_model\n else:\n kv_dim = random.randint(5, 20)\n dims = [batch_sz, seq_len, kv_dim]\n\n saved_k = None\n saved_k_tensor = None\n saved_v = None\n saved_v_tensor = None\n if saved_kv:\n saved_k = np.random.rand(batch_sz * nheads, seq_len, d_head)\n saved_k_tensor = torch.from_numpy(saved_k).to(torch.get_default_dtype())\n saved_v = np.random.rand(batch_sz * nheads, seq_len, d_head)\n saved_v_tensor = torch.from_numpy(saved_v).to(torch.get_default_dtype())\n\n key_padding_mask = None\n key_padding_mask_tensor = None\n if add_key_padding_mask:\n seq_mask = np.random.randint(0, 2, (1, seq_len))\n key_padding_mask = (np.repeat(seq_mask, batch_sz, axis=0) == 1)\n key_padding_mask_tensor = torch.from_numpy(key_padding_mask)\n if byte_mask:\n key_padding_mask_tensor = key_padding_mask_tensor.byte()\n decoder_state = np.random.rand(batch_sz, d_model)\n K = np.random.rand(*dims)\n V = K\n Q = np.expand_dims(decoder_state, 1)\n attn_mask = np.random.randint(0 , 2, size=(1, seq_len))\n attn_mask_tensor = torch.from_numpy(attn_mask).float()\n if byte_mask:\n attn_mask_tensor = (attn_mask_tensor == 0).byte()\n else:\n attn_mask_tensor.masked_fill_(attn_mask_tensor == 0, float('-inf'))\n attn_mask_tensor.masked_fill_(attn_mask_tensor > 0, float('0.0'))\n attn_mask_tensor = attn_mask_tensor.double()\n\n decoder_state_tensor = torch.from_numpy(decoder_state).to(torch.get_default_dtype())\n source_hid_tensor = torch.from_numpy(K).to(torch.get_default_dtype()).transpose(0, 1)\n\n multihead_attn_module = MultiheadAttention(d_model, nheads,\n add_bias_kv=add_bias_kv,\n add_zero_attn=add_zero_attn,\n kdim=kv_dim, vdim=kv_dim)\n\n if add_bias_kv:\n bias_k = multihead_attn_module.bias_k.detach().numpy()\n bias_v = multihead_attn_module.bias_v.detach().numpy()\n else:\n bias_k = None\n bias_v = None\n\n _Q = decoder_state_tensor.unsqueeze(1).transpose(0, 1)\n _V = source_hid_tensor\n _K = source_hid_tensor\n\n if multihead_attn_module._qkv_same_embed_dim:\n result, result_weight = torch.nn.functional.multi_head_attention_forward(\n _Q, _K, _V,\n d_model, nheads,\n multihead_attn_module.in_proj_weight, multihead_attn_module.in_proj_bias,\n multihead_attn_module.bias_k, multihead_attn_module.bias_v,\n multihead_attn_module.add_zero_attn, multihead_attn_module.dropout,\n multihead_attn_module.out_proj.weight, multihead_attn_module.out_proj.bias,\n multihead_attn_module.training, key_padding_mask_tensor, True, attn_mask_tensor,\n static_k=saved_k_tensor, static_v=saved_v_tensor)\n else:\n result, result_weight = torch.nn.functional.multi_head_attention_forward(\n _Q, _K, _V,\n d_model, nheads,\n None, multihead_attn_module.in_proj_bias,\n multihead_attn_module.bias_k, multihead_attn_module.bias_v,\n multihead_attn_module.add_zero_attn, multihead_attn_module.dropout,\n multihead_attn_module.out_proj.weight, multihead_attn_module.out_proj.bias,\n multihead_attn_module.training, key_padding_mask_tensor, True, attn_mask_tensor,\n True, multihead_attn_module.q_proj_weight,\n multihead_attn_module.k_proj_weight, multihead_attn_module.v_proj_weight,\n static_k=saved_k_tensor, static_v=saved_v_tensor)\n\n result = result.squeeze(0).detach().numpy()\n\n if multihead_attn_module._qkv_same_embed_dim:\n q_proj_weight = multihead_attn_module.in_proj_weight[:d_model]\n k_proj_weight = multihead_attn_module.in_proj_weight[d_model:(d_model * 2)]\n v_proj_weight = multihead_attn_module.in_proj_weight[(d_model * 2):]\n else:\n q_proj_weight = multihead_attn_module.q_proj_weight\n k_proj_weight = multihead_attn_module.k_proj_weight\n v_proj_weight = multihead_attn_module.v_proj_weight\n\n Q_fc = _fc(Q, q_proj_weight, multihead_attn_module.in_proj_bias[:d_model])\n K_fc = _fc(K, k_proj_weight, multihead_attn_module.in_proj_bias[d_model:(d_model * 2)])\n V_fc = _fc(V, v_proj_weight, multihead_attn_module.in_proj_bias[(d_model * 2):])\n\n if add_bias_kv:\n K_fc = np.concatenate((K_fc, np.repeat(bias_k, K_fc.shape[0], axis=0)), axis=1)\n V_fc = np.concatenate((V_fc, np.repeat(bias_v, V_fc.shape[0], axis=0)), axis=1)\n if attn_mask is not None:\n attn_mask = np.concatenate((attn_mask, np.ones([1, 1])), axis=1)\n if key_padding_mask is not None:\n key_padding_mask = np.concatenate((key_padding_mask, np.full((batch_sz, 1), False, dtype=bool)), axis=1)\n dims[1] += 1\n Q_split = _split_heads_ref(\n Q_fc, [batch_sz, 1, d_model], nheads, d_head\n )\n\n if saved_k is not None:\n K_split = np.reshape(saved_k, [dims[0], nheads, dims[1], d_head])\n else:\n K_split = _split_heads_ref(K_fc, dims, nheads, d_head)\n\n if saved_v is not None:\n V_split = np.reshape(saved_v, [dims[0], nheads, dims[1], d_head])\n else:\n V_split = _split_heads_ref(V_fc, dims, nheads, d_head)\n\n if add_zero_attn:\n dims[1] += 1\n K_split = np.concatenate((K_split, np.zeros([K_split.shape[0], K_split.shape[1], 1, K_split.shape[3]])), axis=2)\n V_split = np.concatenate((V_split, np.zeros([V_split.shape[0], V_split.shape[1], 1, V_split.shape[3]])), axis=2)\n\n if attn_mask is not None:\n attn_mask = np.concatenate((attn_mask, np.ones([1, 1])), axis=1)\n\n if key_padding_mask is not None:\n key_padding_mask = np.concatenate((key_padding_mask, np.full((batch_sz, 1), False, dtype=bool)), axis=1)\n attn_heads, ref_attn_weight = _scaled_dot_attn_ref(\n Q=Q_split,\n K=K_split,\n V=V_split,\n dims=Q_split.shape,\n unseen_mask=attn_mask,\n key_padding_mask=key_padding_mask\n )\n combined_attn_heads = _combine_heads_ref(\n X=attn_heads, dims=[batch_sz, 1], nheads=nheads, d_head=d_head\n )\n\n reference = _fc(combined_attn_heads, multihead_attn_module.out_proj.weight, multihead_attn_module.out_proj.bias)\n reference = np.squeeze(reference, axis=1)\n\n # result = reference\n self.assertEqual(tuple(result.shape), (batch_sz, d_model))\n np.testing.assert_allclose(result, reference, atol=1e-5)\n\n # result_weight = ref_attn_weight\n result_weight = result_weight.detach().numpy()\n self.assertEqual(tuple(result_weight.shape), tuple(ref_attn_weight.shape))\n np.testing.assert_allclose(result_weight, ref_attn_weight, atol=1e-5)\n\n def test_multihead_attn_add_bias_kv():\n _multihead_attn_test_helper(add_bias_kv=True)\n\n def test_multihead_attn_add_zero_attn():\n _multihead_attn_test_helper(add_zero_attn=True)\n\n def test_multihead_attn_no_masking():\n _multihead_attn_test_helper()\n\n def test_multihead_attn_key_padding_mask():\n _multihead_attn_test_helper(add_key_padding_mask=True)\n\n def test_multihead_attn_saved_kv():\n _multihead_attn_test_helper(saved_kv=True)\n\n def test_multihead_attn_add_bias_kv_zero_attn():\n _multihead_attn_test_helper(add_key_padding_mask=True, add_bias_kv=True,\n add_zero_attn=True)\n\n def test_multihead_attn_all_arguments1():\n _multihead_attn_test_helper(add_key_padding_mask=True, add_zero_attn=True, saved_kv=True)\n\n def test_multihead_attn_all_arguments2():\n _multihead_attn_test_helper(add_key_padding_mask=True, add_bias_kv=True,\n add_zero_attn=True, saved_kv=True)\n\n def test_multihead_attn_all_arguments3():\n _multihead_attn_test_helper(add_key_padding_mask=True, add_zero_attn=True,\n saved_kv=True, same_embed_dim=True)\n\n def test_multihead_attn_all_arguments4():\n _multihead_attn_test_helper(add_key_padding_mask=True, add_zero_attn=True,\n saved_kv=True, same_embed_dim=True, byte_mask=True)\n\n test_multihead_attn_add_zero_attn() # Test MultiheadAttention with add_zero_attn\n test_multihead_attn_add_bias_kv() # Test MultiheadAttention with add_bias_kv\n test_multihead_attn_no_masking() # Test MultiheadAttention without masking\n test_multihead_attn_key_padding_mask() # Test MultiheadAttention with src lengths\n test_multihead_attn_saved_kv() # Test MultiheadAttention with static kv.\n test_multihead_attn_add_bias_kv_zero_attn() # Test MultiheadAttention with bias_kv and zero_attn.\n test_multihead_attn_all_arguments1() # Test MultiheadAttention with all the argument.\n with self.assertRaisesRegex(AssertionError, \"bias cannot be added to static key.\"):\n test_multihead_attn_all_arguments2() # Test MultiheadAttention with all the argument.\n test_multihead_attn_all_arguments3() # Test MultiheadAttention with all the argument.\n test_multihead_attn_all_arguments4() # Test MultiheadAttention with all the argument.\n\n def test_multihead_attn_3d_attn_mask(self):\n embed_dim = 8\n num_heads = 4\n batch_size = 8\n src_len = 3\n tgt_len = 2\n\n query = torch.rand(batch_size, tgt_len, embed_dim) # [N, T, D]\n key = torch.rand(batch_size, src_len, embed_dim) # [N, S, D]\n value = key # [N, S, D]\n attn_mask = torch.randint(0, 2, (batch_size, tgt_len, src_len)).float() # [N, T, S]\n attn_mask = attn_mask.masked_fill(attn_mask == 0, float('-inf')).masked_fill(attn_mask == 1, float(0.0))\n\n mta_model = torch.nn.MultiheadAttention(embed_dim, num_heads)\n\n # Generate 3D results\n attn_mask_3d = torch.repeat_interleave(attn_mask, num_heads, dim=0) # [N * H, T, S]\n output_3d = mta_model(query.transpose(0, 1), key.transpose(0, 1), value.transpose(0, 1), attn_mask=attn_mask_3d)[0]\n output_3d = output_3d.transpose(0, 1) # [N, T, D]\n\n for i in range(0, batch_size):\n output_2d = mta_model(query[i].unsqueeze(0).transpose(0, 1),\n key[i].unsqueeze(0).transpose(0, 1),\n value[i].unsqueeze(0).transpose(0, 1),\n attn_mask=attn_mask[i])[0]\n\n # output_2d in shape of [T, 1, D]\n self.assertEqual(output_3d[i].unsqueeze(0).transpose(0, 1), output_2d)\n\n def test_multihead_attn_no_bias(self):\n embed_dim = 8\n num_heads = 4\n mha = torch.nn.MultiheadAttention(embed_dim, num_heads, bias=False)\n\n # Verify that bias=False applies to both in and out projection layers.\n self.assertIsNone(mha.in_proj_bias)\n self.assertIsNone(mha.out_proj.bias)\n\n def test_normalize(self):\n inputs = torch.randn(1, 3, 4, 4, requires_grad=True)\n self.assertTrue(gradcheck(lambda x: F.normalize(x, p=1, dim=-1), (inputs,)))\n self.assertTrue(gradcheck(lambda x: F.normalize(x, p=2, dim=-2), (inputs,)))\n\n inputs = torch.randn((), requires_grad=True)\n self.assertTrue(gradcheck(lambda x: F.normalize(x, p=1, dim=-1), (inputs,)))\n\n def test_adaptive_pooling_input_size(self):\n for numel in (2, 3):\n for pool_type in ('Max', 'Avg'):\n cls_name = 'Adaptive{}Pool{}d'.format(pool_type, numel)\n module_cls = getattr(nn, cls_name)\n output_size = (2,) * numel\n module = module_cls(output_size)\n\n input = torch.randn(output_size)\n self.assertRaises(ValueError, lambda: module(input))\n\n def test_adaptive_pooling_size_none(self):\n for numel in (2, 3):\n for pool_type in ('Max', 'Avg'):\n cls_name = 'Adaptive{}Pool{}d'.format(pool_type, numel)\n module_cls = getattr(nn, cls_name)\n output_size = (2,) * (numel - 1) + (None,)\n module = module_cls(output_size)\n\n input = torch.randn((4,) * (numel + 1))\n output = module(input)\n self.assertEqual(output.size(), (4,) + (2,) * (numel - 1) + (4,))\n\n @unittest.skipIf(TEST_WITH_UBSAN, \"signed integer overflow error with UBSAN\")\n def test_adaptive_pooling_size_overflow(self):\n # 0x0x3fffffffffffffff * 2 * 2 = 0xfffffffffffffffc = -4 as int64_t\n # Tensor::numel() return int64_t, so following check that negative allocs are correctly handled\n self.assertRaises(\n RuntimeError,\n lambda: torch.nn.AdaptiveMaxPool1d(0x3fffffffffffffff)(torch.empty([2, 2, 2])))\n\n def test_adaptive_pooling_avg_nhwc(self):\n device_list = ['cpu']\n if TEST_CUDA:\n device_list.append('cuda')\n\n for device in device_list:\n input = torch.randint(1, 10, (4, 8, 8, 8), dtype=torch.float32).to(device)\n input = input.contiguous(memory_format=torch.channels_last).requires_grad_()\n grad = torch.randint(1, 10, (4, 8, 7, 7), dtype=torch.float32).to(device)\n pool = torch.nn.AdaptiveAvgPool2d((7, 7)).to(device)\n\n ref_input = input.detach().clone().contiguous().requires_grad_(True)\n ref_grad = grad.detach().clone().contiguous()\n ref_pool = torch.nn.AdaptiveAvgPool2d((7, 7)).to(device)\n\n out = pool(input)\n out.backward(grad)\n ref_out = ref_pool(ref_input)\n ref_out.backward(ref_grad)\n\n self.assertTrue(out.is_contiguous(memory_format=torch.channels_last))\n self.assertTrue(ref_out.is_contiguous())\n self.assertEqual(out, ref_out)\n self.assertEqual(input.grad, ref_input.grad)\n\n def test_adaptive_pooling_avg_nhwc_non_contiguous(self):\n device_list = ['cpu']\n if TEST_CUDA:\n device_list.append('cuda')\n\n for device in device_list:\n input = torch.randint(1, 10, (4, 8, 8, 8), dtype=torch.float32).to(device)\n input = input.contiguous(memory_format=torch.channels_last)\n input = input[:, ::2, :, :].requires_grad_()\n grad = torch.randint(1, 10, (4, 8, 7, 7), dtype=torch.float32).to(device)\n grad = grad[:, ::2, :, :]\n pool = torch.nn.AdaptiveAvgPool2d((7, 7)).to(device)\n\n ref_input = input.detach().clone().contiguous().requires_grad_(True)\n ref_grad = grad.detach().clone().contiguous()\n ref_pool = torch.nn.AdaptiveAvgPool2d((7, 7)).to(device)\n\n out = pool(input)\n out.backward(grad)\n ref_out = ref_pool(ref_input)\n ref_out.backward(ref_grad)\n\n self.assertTrue(out.is_contiguous(memory_format=torch.channels_last))\n self.assertTrue(ref_out.is_contiguous())\n self.assertEqual(out, ref_out)\n self.assertEqual(input.grad, ref_input.grad)\n\n @unittest.skipIf(not TEST_CUDA, \"CUDA unavailable\")\n @largeTensorTest('12GB', device='cuda')\n def test_adaptive_pooling_avg_nhwc_launch_config_backward(self):\n input = torch.randint(1, 10, (1, 32, 2 ** 17 + 1, 32), dtype=torch.float32, device=\"cuda\")\n input = input.contiguous(memory_format=torch.channels_last).requires_grad_()\n grad = torch.randint(1, 10, (1, 32, 10, 32), dtype=torch.float32, device=\"cuda\")\n\n pool = torch.nn.AdaptiveAvgPool2d((10, 32)).cuda()\n\n ref_input = input.detach().clone().contiguous().requires_grad_(True)\n ref_grad = grad.detach().clone().contiguous()\n ref_pool = torch.nn.AdaptiveAvgPool2d((10, 32)).cuda()\n\n out = pool(input)\n out.backward(grad)\n ref_out = ref_pool(ref_input)\n ref_out.backward(ref_grad)\n\n self.assertTrue(out.is_contiguous(memory_format=torch.channels_last))\n self.assertTrue(ref_out.is_contiguous())\n self.assertEqual(out, ref_out)\n self.assertEqual(input.grad, ref_input.grad)\n\n @unittest.skipIf(not TEST_CUDA, \"CUDA unavailable\")\n @largeTensorTest('12GB', device='cuda')\n def test_adaptive_pooling_avg_nhwc_launch_config_forward(self):\n input = torch.randint(1, 10, (1, 32, 16, 16), dtype=torch.float32, device=\"cuda\")\n input = input.contiguous(memory_format=torch.channels_last).requires_grad_()\n pool = torch.nn.AdaptiveAvgPool2d((2 ** 17 + 1, 32)).cuda()\n\n ref_input = input.detach().clone().contiguous().requires_grad_(True)\n ref_pool = torch.nn.AdaptiveAvgPool2d((2 ** 17 + 1, 32)).cuda()\n\n out = pool(input)\n ref_out = ref_pool(ref_input)\n\n self.assertTrue(out.is_contiguous(memory_format=torch.channels_last))\n self.assertTrue(ref_out.is_contiguous())\n self.assertEqual(out, ref_out)\n\n @unittest.skipIf(not TEST_MULTIGPU, \"multi-GPU not supported\")\n # Skip the test for ROCm as per https://github.com/pytorch/pytorch/issues/53190\n @skipIfRocm\n def test_broadcast_double_backwards_gpu(self):\n tensors = (torch.randn(4, 4, device='cuda', requires_grad=True),\n torch.randn(4, 4, device='cuda', requires_grad=True),\n torch.randn(4, 4, device='cuda', requires_grad=True))\n # TODO(#50743): the following segfaults with check_batched_grad=True\n _assertGradAndGradgradChecks(self, lambda *i: Broadcast.apply((0, 1), *i), tensors,\n check_batched_grad=False)\n\n @unittest.skipIf(not TEST_MULTIGPU, \"multi-GPU not supported\")\n def test_broadcast_not_requiring_grad(self):\n variables = [\n torch.randn(1, 2, device='cuda', requires_grad=True),\n torch.randn(1, 2, device='cuda', requires_grad=False),\n torch.randn(1, 2, device='cuda', requires_grad=False),\n torch.randn(1, 2, device='cuda', requires_grad=True),\n torch.randn(1, 2, device='cuda', requires_grad=True),\n ]\n broadcasted_variables = Broadcast.apply((0, 1), *variables)\n for output_idx, broadcasted_var in enumerate(broadcasted_variables):\n input_var = variables[output_idx % len(variables)]\n self.assertEqual(input_var.requires_grad, broadcasted_var.requires_grad)\n\n @unittest.skipIf(not TEST_MULTIGPU, \"multi-GPU not supported\")\n def test_broadcast_no_grad(self):\n x = torch.randn(1, 2, dtype=torch.float32, requires_grad=True, device='cuda')\n with torch.no_grad():\n broadcasted = Broadcast.apply((0, 1), x)\n self.assertTrue(x.requires_grad)\n for output in broadcasted:\n self.assertFalse(output.requires_grad)\n\n def test_state_dict(self):\n l = nn.Linear(5, 5)\n block = nn.Module()\n block.conv = nn.Conv2d(3, 3, 3, bias=False)\n net = nn.Module()\n net.linear1 = l\n net.linear2 = l\n net.bn = nn.BatchNorm2d(2)\n net.block = block\n net.add_module('empty', None)\n\n state_dict = net.state_dict()\n self.assertEqual(len(state_dict), 10)\n self.assertEqual(len(state_dict._metadata), 6)\n self.assertIn('', state_dict._metadata)\n self.assertIn('linear1', state_dict._metadata)\n self.assertIn('linear1.weight', state_dict)\n self.assertIn('linear1.bias', state_dict)\n self.assertIn('linear2', state_dict._metadata)\n self.assertIn('linear2.weight', state_dict)\n self.assertIn('linear2.bias', state_dict)\n self.assertIn('block', state_dict._metadata)\n self.assertIn('block.conv', state_dict._metadata)\n self.assertIn('block.conv.weight', state_dict)\n self.assertIn('block.conv.weight', state_dict)\n self.assertNotIn('block.conv.bias', state_dict)\n self.assertIn('bn', state_dict._metadata)\n self.assertIn('bn.weight', state_dict)\n self.assertIn('bn.bias', state_dict)\n self.assertIn('bn.running_var', state_dict)\n self.assertIn('bn.running_mean', state_dict)\n self.assertIn('bn.num_batches_tracked', state_dict)\n self.assertFalse(any(k.startswith('empty') for k in state_dict.keys()))\n for k, v in state_dict.items():\n param = net\n for component in k.split('.'):\n param = getattr(param, component)\n if isinstance(param, Parameter):\n param = param.data\n self.assertEqual(v.data_ptr(), param.data_ptr())\n\n l = nn.Linear(5, 5)\n state_dict = l.state_dict()\n self.assertEqual(len(state_dict), 2)\n self.assertEqual(len(state_dict._metadata), 1)\n self.assertIn('', state_dict._metadata)\n self.assertTrue(state_dict._metadata['']['version'] >= 0)\n self.assertEqual(state_dict['weight'].data_ptr(), l.weight.data_ptr())\n self.assertEqual(state_dict['bias'].data_ptr(), l.bias.data_ptr())\n\n def test_load_state_dict(self):\n l = nn.Linear(5, 5)\n block = nn.Module()\n block.conv1 = nn.Conv2d(3, 3, 3, bias=True)\n block.conv2 = nn.Conv2d(3, 3, 3, bias=False)\n net = nn.Module()\n net.linear1 = l\n net.linear2 = l\n net.bn = nn.BatchNorm2d(2)\n net.block = block\n net.add_module('empty', None)\n\n state_dict = net.state_dict()\n state_dict.update({\n 'linear1.weight': torch.ones(5, 5),\n 'block.conv1.bias': torch.arange(1, 4),\n 'bn.running_mean': torch.randn(2),\n })\n # Also test if a DDP state_dict can be loaded from a local model.\n ddp_state_dict = net.state_dict()\n ddp_state_dict.update({\n 'module.linear1.weight': torch.ones(5, 5),\n 'module.block.conv1.bias': torch.arange(1, 4),\n 'module.bn.running_mean': torch.randn(2),\n })\n torch.nn.modules.utils.consume_prefix_in_state_dict_if_present(ddp_state_dict, 'module.')\n for sd in [state_dict, ddp_state_dict]:\n incompatible_keys = net.load_state_dict(sd)\n self.assertEqual(len(incompatible_keys.missing_keys), 0)\n self.assertEqual(len(incompatible_keys.unexpected_keys), 0)\n self.assertNotIn('Incompatible', str(incompatible_keys))\n self.assertEqual(net.linear1.weight, sd['linear1.weight'])\n # TODO(#38095): Replace assertEqualIgnoreType. See issue #38095\n self.assertEqualIgnoreType(net.block.conv1.bias, sd['block.conv1.bias'])\n self.assertEqual(net.bn.running_mean, sd['bn.running_mean'])\n\n state_dict = net.state_dict()\n state_dict.update({'extra': torch.ones(5)})\n self.assertRaises(RuntimeError, lambda: net.load_state_dict(state_dict))\n incompatible_keys = net.load_state_dict(state_dict, strict=False)\n self.assertEqual(len(incompatible_keys.missing_keys), 0)\n self.assertEqual(len(incompatible_keys.unexpected_keys), 1)\n self.assertIn('extra', incompatible_keys.unexpected_keys)\n self.assertIn('Incompatible', str(incompatible_keys))\n\n state_dict = net.state_dict()\n state_dict.update({'extra.param': torch.ones(5)})\n self.assertRaises(RuntimeError, lambda: net.load_state_dict(state_dict))\n incompatible_keys = net.load_state_dict(state_dict, strict=False)\n self.assertEqual(len(incompatible_keys.missing_keys), 0)\n self.assertEqual(len(incompatible_keys.unexpected_keys), 1)\n self.assertIn('extra.param', incompatible_keys.unexpected_keys)\n\n state_dict = net.state_dict()\n del state_dict['linear1.weight']\n self.assertRaises(RuntimeError, lambda: net.load_state_dict(state_dict))\n incompatible_keys = net.load_state_dict(state_dict, strict=False)\n self.assertEqual(len(incompatible_keys.missing_keys), 1)\n self.assertEqual(len(incompatible_keys.unexpected_keys), 0)\n self.assertIn('linear1.weight', incompatible_keys.missing_keys)\n state_dict.update({'extra.param': torch.ones(5)})\n self.assertRaises(RuntimeError, lambda: net.load_state_dict(state_dict))\n incompatible_keys = net.load_state_dict(state_dict, strict=False)\n self.assertEqual(len(incompatible_keys.missing_keys), 1)\n self.assertEqual(len(incompatible_keys.unexpected_keys), 1)\n self.assertIn('linear1.weight', incompatible_keys.missing_keys)\n self.assertIn('extra.param', incompatible_keys.unexpected_keys)\n\n state_dict = net.state_dict()\n state_dict.update({'bn.running_mean': torch.rand(14, 4)}) # wrong size\n self.assertRaises(RuntimeError, lambda: net.load_state_dict(state_dict))\n self.assertRaises(RuntimeError, lambda: net.load_state_dict(state_dict, strict=False))\n\n state_dict = net.state_dict()\n old_state_dict = deepcopy(state_dict)\n state_dict = {\n 'linear1.weight': torch.ones(5, 5),\n 'block.conv1.bias': torch.arange(1, 4),\n 'bn.running_mean': torch.randn(2),\n 'nonexistent_key': torch.rand(3)\n }\n net.load_state_dict(state_dict, strict=False)\n self.assertEqual(net.linear1.weight, state_dict['linear1.weight'])\n # TODO(#38095): Replace assertEqualIgnoreType. See issue #38095\n self.assertEqualIgnoreType(net.block.conv1.bias, state_dict['block.conv1.bias'])\n self.assertEqual(net.bn.running_mean, state_dict['bn.running_mean'])\n new_state_dict = net.state_dict()\n del old_state_dict['linear1.weight']\n del old_state_dict['block.conv1.bias']\n del old_state_dict['bn.running_mean']\n for k, v, in old_state_dict.items():\n self.assertTrue(v.equal(new_state_dict[k]))\n\n def test_load_state_dict_BC(self):\n # BatchNormNd\n # Added num_batches_tracked buffer at version 2. For state dict with\n # earlier versions or no versions, it should provide default value of 0.\n bn = nn.BatchNorm2d(3)\n state_dict = bn.state_dict()\n del state_dict['num_batches_tracked']\n state_dict._metadata['']['version'] = 1 # version 1\n bn.load_state_dict(state_dict)\n self.assertEqual(bn.num_batches_tracked.dtype, torch.long)\n self.assertEqual(bn.num_batches_tracked.item(), 0)\n del state_dict._metadata['']['version'] # no version\n bn.load_state_dict(state_dict)\n self.assertEqual(bn.num_batches_tracked.dtype, torch.long)\n self.assertEqual(bn.num_batches_tracked.item(), 0)\n\n def test_load_state_dict_ref_cycle(self):\n # load_state_dict shouldn't cause a reference cycle involving Tensors\n import gc\n\n m = torch.nn.LSTM(16, 16, bidirectional=True)\n\n gc.collect()\n m.load_state_dict(deepcopy(m).state_dict())\n refcycles = gc.collect()\n\n self.assertEqual(refcycles, 0)\n\n def test_load_state_dict_custom(self):\n\n class CustomState(nn.Module):\n def __init__(self):\n super(CustomState, self).__init__()\n self.param = torch.nn.Parameter(torch.ones(1))\n self.sub = torch.nn.Linear(5, 5)\n\n def _save_to_state_dict(self, destination, prefix, keep_vars):\n destination[prefix + \"serialized\"] = self.param.data + 1\n\n def _load_from_state_dict(self, state_dict, prefix, local_metadata,\n strict, missing_keys, unexpected_keys,\n error_msgs):\n # skip some of the error handling\n self.param.data.copy_(state_dict[prefix + \"serialized\"] - 1)\n\n # use sequential to verify nesting\n m = nn.Sequential(CustomState())\n with torch.no_grad():\n m[0].param[0] = 10\n m[0].sub.weight[0, 0] = 555\n state_dict = m.state_dict()\n self.assertEqual(state_dict[\"0.serialized\"].item(), 11)\n self.assertIn(\"0.sub.weight\", state_dict)\n self.assertNotIn(\"0.param\", state_dict)\n del m\n mm = nn.Sequential(CustomState())\n self.assertEqual(mm[0].param[0].item(), 1)\n mm.load_state_dict(state_dict)\n self.assertEqual(mm[0].param[0].item(), 10)\n self.assertEqual(mm[0].sub.weight[0, 0].item(), 555)\n\n def test_parameter_assignment(self):\n l = nn.Linear(5, 5)\n\n def num_params():\n return len(list(l.parameters()))\n\n self.assertEqual(num_params(), 2)\n\n new_param = Parameter(torch.randn(5, 5))\n l.param_name = new_param\n self.assertEqual(num_params(), 3)\n self.assertObjectIn(new_param, l.parameters())\n\n var = torch.randn(5, 5)\n l.var_name = var\n self.assertEqual(num_params(), 3)\n self.assertNotIn(id(var), map(id, l.parameters()))\n\n # Make sure Variables are not saved as parameters\n l.variable_attr = torch.empty(5, 5)\n self.assertEqual(num_params(), 3)\n l.param_attr = Parameter(torch.empty(5, 5))\n self.assertEqual(num_params(), 4)\n\n # It shouldn't be possible to replace a parameter with a Variable\n def assign_var():\n l.param_attr = torch.empty(5, 5)\n\n self.assertRaises(TypeError, assign_var)\n # But replacing it with None should be fine\n l.param_attr = None\n self.assertEqual(num_params(), 3)\n\n def test_assignment(self):\n l = nn.Module()\n a = nn.Parameter(torch.randn(2))\n b = nn.Parameter(torch.randn(3))\n c = nn.Parameter(torch.randn(4))\n q = nn.Linear(4, 4)\n r = nn.Linear(5, 5)\n w = nn.Linear(6, 6)\n\n def test_assignments(get_list, a, b, c):\n # Check that None can be shadowed\n l.a = None\n self.assertIsNone(l.a)\n self.assertIn('a', l.__dict__)\n l.a = a\n self.assertIs(l.a, a)\n self.assertEqual(get_list(), [a])\n self.assertNotIn('a', l.__dict__)\n\n # Assign second object\n l.b = None\n self.assertIsNone(l.b)\n self.assertIn('b', l.__dict__)\n l.b = b\n self.assertIs(l.b, b)\n self.assertEqual(get_list(), [a, b])\n self.assertNotIn('b', l.__dict__)\n\n # Remove and add the object back. Order should be unchanged.\n l.a = None\n self.assertIsNone(l.a)\n self.assertEqual(get_list(), [b])\n l.a = a\n self.assertIs(l.a, a)\n self.assertEqual(get_list(), [a, b])\n\n # Replace object with another one. Order should be unchanged.\n l.a = c\n self.assertIs(l.a, c)\n self.assertEqual(get_list(), [c, b])\n\n # Remove and reassign an attribute. It should appear at the end of the list now.\n del l.a\n self.assertFalse(hasattr(l, 'a'))\n l.a = a\n self.assertIs(l.a, a)\n self.assertEqual(get_list(), [b, a])\n\n test_assignments(lambda: list(l.parameters()), a, b, c)\n del l.a, l.b\n self.assertEqual(list(l.parameters()), [])\n\n test_assignments(lambda: list(l.children()), q, r, w)\n del l.a, l.b\n self.assertEqual(list(l.children()), [])\n\n buf = torch.randn(10)\n l.register_buffer('buf', buf)\n self.assertIs(l.buf, buf)\n l.buf = None\n self.assertIs(l.buf, None)\n self.assertNotIn('buf', l.__dict__) # should be stored in l._buffers\n l.buf = buf\n self.assertIn('buf', l.state_dict())\n self.assertEqual(l.state_dict()['buf'], buf)\n\n @unittest.skipIf(not TEST_CUDA, 'CUDA not available')\n def test_thnn_conv_strided_padded_dilated(self):\n for convfn, dims, transposed in (\n (torch.nn.functional.conv2d, 2, False),\n (torch.nn.functional.conv_transpose2d, 2, True),\n (torch.nn.functional.conv3d, 3, False),\n (torch.nn.functional.conv_transpose3d, 3, True)):\n for stride, padding, dilation in (\n (2, 0, 1), (1, 1, 1), (2, 1, 1), (1, 0, 2)):\n kwargs = {\"stride\": stride, \"padding\": padding, \"dilation\": dilation}\n inp_shape = (1, 2) + dims * (4,)\n weight_shape = (2, 2) + dims * (1,)\n inputs = torch.randn(inp_shape, dtype=torch.double, device=\"cuda\", requires_grad=True)\n weight = torch.randn(weight_shape, dtype=torch.double, device=\"cuda\", requires_grad=True)\n bias = torch.randn(2, dtype=torch.double, device=\"cuda\", requires_grad=True)\n with torch.backends.cudnn.flags(enabled=False):\n res = convfn(inputs, weight, bias, **kwargs)\n res_cpu = convfn(inputs.cpu(), weight.cpu(), bias.cpu(), **kwargs)\n self.assertEqual(res, res_cpu)\n with torch.backends.cudnn.flags(enabled=False):\n torch.autograd.gradcheck(\n lambda x, w, b: convfn(x, w, b, **kwargs),\n (inputs, weight, bias)\n )\n torch.autograd.gradcheck(\n lambda x, w, b: convfn(x, w, b, **kwargs),\n (inputs.cpu(), weight.cpu(), bias.cpu())\n )\n\n def test_Conv2d_inconsistent_types(self):\n inputs = torch.randn(4, 1, 7, 7, dtype=torch.float)\n weights = torch.randn(1, 1, 3, 3, dtype=torch.double)\n # inconsistent types should raise an exception\n self.assertRaises(RuntimeError, lambda: nn.functional.conv2d(inputs, weights))\n # but it should work with the same type\n nn.functional.conv2d(inputs.float(), weights.float())\n\n @unittest.skipIf(not TEST_CUDA, 'CUDA not available')\n def test_Conv2d_inconsistent_types_on_GPU_without_cudnn(self):\n inputs = torch.randn(4, 1, 7, 7, dtype=torch.float, device=\"cuda\")\n weights = torch.randn(1, 1, 3, 3, dtype=torch.double, device=\"cuda\")\n bias = torch.randn(1, dtype=torch.double, device=\"cuda\")\n\n with torch.backends.cudnn.flags(enabled=False):\n # inconsistent types should raise an exception\n self.assertRaises(RuntimeError, lambda: nn.functional.conv2d(inputs, weights))\n self.assertRaises(RuntimeError, lambda: nn.functional.conv2d(inputs, weights.float(), bias))\n\n # but it should work with the same type\n nn.functional.conv2d(inputs.float(), weights.float(), bias.float())\n\n def test_Conv2d_1x1(self):\n in_channels = 2\n out_channels = 2\n mod = torch.nn.Conv2d(2, 2, 1, bias=False).to(dtype=torch.double)\n input = torch.randn(1, in_channels, 5, 5, requires_grad=True, dtype=torch.double)\n for enabled in (False, True):\n with torch.backends.mkldnn.flags(enabled=enabled):\n gradcheck(F.conv2d, (input, mod.weight))\n\n def test_Conv2d_OneDNN(self):\n def run_once(group_val=24, dilation=1):\n ifm = torch.ones([1, group_val, 6, 6], dtype=torch.float32)\n weights = torch.ones([group_val, 1, 3, 3], dtype=torch.float32)\n op = torch.nn.Conv2d(\n in_channels=group_val,\n out_channels=group_val,\n kernel_size=[3, 3],\n stride=[2, 2],\n padding=[1, 1],\n dilation=[dilation, dilation],\n groups=group_val,\n bias=False,\n padding_mode='zeros'\n )\n\n op.weight.data = weights\n res = op(ifm)\n grad_in = torch.ones(res.shape, dtype=torch.float32)\n res.backward(grad_in)\n return op.weight.grad\n\n for gorup_val in (24, 48, 23, 25):\n for dilation in (1, 2):\n with torch.backends.mkldnn.flags(enabled=False):\n without_onednn = run_once(gorup_val, dilation)\n\n with torch.backends.mkldnn.flags(enabled=True):\n with_onednn = run_once(gorup_val, dilation)\n\n self.assertEqual(without_onednn, with_onednn)\n\n @unittest.skipIf(not TEST_CUDA, 'CUDA not available')\n @unittest.skipIf(not TEST_CUDNN, 'CUDNN not available')\n def test_cudnn_non_contiguous(self):\n x = torch.randn(192, 16, 50).cuda()\n x = x.permute(0, 2, 1).contiguous().permute(0, 2, 1)\n m = torch.nn.Conv1d(\n in_channels=16,\n out_channels=32,\n kernel_size=2,\n bias=True).cuda()\n result = m(x)\n\n @unittest.skipIf(not TEST_CUDA, 'CUDA not available')\n @unittest.skipIf(not TEST_CUDNN, 'CUDNN not available')\n def test_Conv2d_inconsistent_types_on_GPU_with_cudnn(self):\n inputs = torch.randn(4, 1, 7, 7, dtype=torch.float, device=\"cuda\")\n weights = torch.randn(1, 1, 3, 3, dtype=torch.double, device=\"cuda\")\n bias = torch.randn(1, dtype=torch.double, device=\"cuda\")\n\n with torch.backends.cudnn.flags(enabled=True):\n # inconsistent types should raise an exception\n self.assertRaises(RuntimeError, lambda: nn.functional.conv2d(inputs, weights))\n self.assertRaises(RuntimeError, lambda: nn.functional.conv2d(inputs, weights.float(), bias))\n\n # but it should work with the same type\n nn.functional.conv2d(inputs.float(), weights.float(), bias.float())\n\n @unittest.skipIf(not TEST_CUDA, 'CUDA not available')\n @unittest.skipIf(not TEST_CUDNN, 'CUDNN not available')\n @repeat_test_for_types(get_all_fp_dtypes(include_bfloat16=AMPERE_OR_ROCM))\n def test_Conv2d_deterministic_cudnn(self, dtype=torch.float):\n inputs = torch.randn(2, 3, 5, 5, device=\"cuda\", dtype=dtype, requires_grad=True)\n with cudnn.flags(enabled=True, benchmark=True, deterministic=True):\n conv1 = torch.nn.Conv2d(3, 3, 3).to(\"cuda\", dtype)\n conv2 = torch.nn.Conv2d(3, 3, 3).to(\"cuda\", dtype)\n conv2.bias.data.copy_(conv1.bias.data)\n conv2.weight.data.copy_(conv1.weight.data)\n out1 = conv1(inputs)\n out2 = conv2(inputs)\n self.assertEqual(out1, out2, atol=0.0, rtol=0)\n y = torch.randn(out1.size(), device=\"cuda\", dtype=dtype)\n out1.backward(y)\n out2.backward(y)\n self.assertEqual(conv1.bias.grad.data, conv2.bias.grad.data, atol=0.0, rtol=0)\n self.assertEqual(conv1.weight.grad.data, conv2.weight.grad.data, atol=0.0, rtol=0)\n\n def test_Conv2d_missing_argument(self):\n c = nn.Conv2d(3, 3, 3)\n self.assertRaises(TypeError, lambda: c(None))\n\n def test_Conv2d_backward_twice(self):\n input = torch.randn(2, 3, 5, 5)\n c = nn.Conv2d(3, 3, 3)\n o1 = c(input)\n o1.sum().backward()\n self.assertRaisesRegex(RuntimeError, 'Specify retain_graph=True',\n lambda: o1.sum().backward())\n\n @unittest.skipIf(not TEST_CUDA, 'CUDA not available')\n @repeat_test_for_types(get_all_fp_dtypes(include_bfloat16=AMPERE_OR_ROCM))\n def test_Conv2d_large_workspace(self, dtype=torch.float):\n # These sizes require huge cuDNN workspaces. Make sure we choose a\n # reasonable algorithm that does not run out of memory\n sizes = [\n (1, 256, 109, 175),\n (1, 256, 80, 128),\n (1, 256, 120, 192),\n ]\n\n def run_test(benchmark):\n with torch.backends.cudnn.flags(benchmark=benchmark):\n conv = torch.nn.Conv2d(256, 256, kernel_size=3, padding=1).to(\"cuda\", dtype)\n for size in sizes:\n x = torch.randn(size, device=\"cuda\", dtype=dtype)\n out = conv(x.detach().clone().requires_grad_())\n out.backward(torch.ones_like(out))\n\n run_test(benchmark=False)\n run_test(benchmark=True)\n\n def test_conv_modules_raise_error_on_incorrect_input_size(self):\n for dtype in [torch.bfloat16, torch.double, torch.float]:\n modules = [nn.Conv1d(3, 8, 3).to(dtype), nn.ConvTranspose1d(3, 8, 3).to(dtype),\n nn.Conv2d(3, 8, 3).to(dtype), nn.ConvTranspose2d(3, 8, 3).to(dtype),\n nn.Conv3d(3, 8, 3).to(dtype), nn.ConvTranspose3d(3, 8, 3).to(dtype)]\n\n invalid_input_dims = [(2, 4), (2, 4),\n (3, 5), (3, 5),\n (4, 6), (4, 6)]\n\n for invalid_dims, module in zip(invalid_input_dims, modules):\n for dims in invalid_dims:\n input = torch.empty(torch.Size((3, ) * dims))\n self.assertRaises(RuntimeError, lambda: module(input))\n\n def test_conv_shapecheck(self):\n def test(should_raise, module, input_size, dtype):\n input = torch.empty(3, *input_size).to(dtype)\n if should_raise:\n self.assertRaises(RuntimeError, lambda: module(input))\n else:\n # just run it to ensure no exception raised.\n module(input)\n\n for dtype in [torch.bfloat16, torch.float, torch.double]:\n # Conv1d\n test(True, nn.Conv1d(1, 1, 3).to(dtype), (1, 2), dtype)\n test(True, nn.Conv1d(1, 1, 3, stride=2).to(dtype), (1, 2), dtype)\n test(False, nn.Conv1d(1, 1, 2).to(dtype), (1, 2), dtype)\n test(False, nn.Conv1d(1, 1, 2, stride=2).to(dtype), (1, 2), dtype)\n test(False, nn.Conv1d(1, 1, 3, stride=2, padding=1).to(dtype), (1, 2), dtype)\n\n # Conv2d\n test(True, nn.Conv2d(1, 1, (3, 3)).to(dtype), (1, 2, 2), dtype)\n test(False, nn.Conv2d(1, 1, (3, 3)).to(dtype), (1, 3, 3), dtype)\n test(False, nn.Conv2d(1, 1, (3, 3), padding=1).to(dtype), (1, 2, 2), dtype)\n\n # Conv3D\n test(True, nn.Conv3d(1, 1, (3, 3, 3)).to(dtype), (1, 2, 2, 2), dtype)\n test(False, nn.Conv3d(1, 1, (3, 3, 3)).to(dtype), (1, 3, 3, 3), dtype)\n test(False, nn.Conv3d(1, 1, (3, 3, 3), padding=1).to(dtype), (1, 2, 2, 2), dtype)\n\n def test_ConvTranspose2d_output_size(self):\n m = nn.ConvTranspose2d(3, 4, 3, 3, 0, 2)\n i = torch.randn(2, 3, 6, 6)\n for h in range(15, 22):\n for w in range(15, 22):\n if 18 <= h <= 20 and 18 <= w <= 20:\n output = m(i, output_size=(h, w))\n self.assertEqual(output.size()[2:], (h, w))\n else:\n self.assertRaises(ValueError, lambda: m(i, (h, w)))\n\n def test_ConvTranspose2d_output_size_downsample_upsample(self):\n b, c, hid_c = 2, 3, 2\n for h in range(13, 24):\n for w in range(13, 17):\n for k in range(2, 5):\n for d in range(1, 5):\n for s in range(1, 4):\n for p in range(3):\n conv = nn.Conv2d(\n in_channels=c,\n out_channels=hid_c,\n kernel_size=k,\n stride=s,\n padding=p,\n dilation=d,\n )\n\n t_conv = nn.ConvTranspose2d(\n in_channels=hid_c,\n out_channels=c,\n kernel_size=k,\n stride=s,\n padding=p,\n dilation=d,\n )\n\n i = torch.randn(b, c, h, w)\n\n out = t_conv(conv(i), output_size=i.shape)\n\n self.assertEqual(out.size()[2:], i.size()[2:])\n\n def test_ConvTranspose3d_correct_output_size(self):\n # Check that ConvTranspose3d can take a 5d output_size.\n m = nn.ConvTranspose3d(2, 2, 2)\n i = torch.rand(1, 2, 1, 1, 1)\n out = m(i, output_size=(1, 2, 2, 2, 2))\n\n @unittest.skipIf(not TEST_CUDA, 'CUDA not available')\n def test_ConvTranspose2d_half_cublas_gemm(self):\n with torch.backends.cudnn.flags(enabled=False):\n inputs = torch.randn(1, 1, 16, 16, device='cuda', dtype=torch.half)\n deconv = nn.ConvTranspose2d(\n 1, 1, 3, stride=2, padding=1, output_padding=1).cuda().half()\n output = deconv(inputs)\n output.mean().backward()\n\n @unittest.skipIf(not TEST_CUDA, 'CUDA not available')\n @repeat_test_for_types([torch.half, torch.float])\n def test_ConvTranspose2d_large_output_padding(self, dtype=torch.half):\n net1 = torch.nn.ConvTranspose2d(128, 64, kernel_size=3, stride=2, padding=1, output_padding=1)\\\n .to(device='cuda', dtype=dtype)\n net2 = torch.nn.ConvTranspose2d(64, 32, kernel_size=3, stride=2, padding=1, output_padding=1)\\\n .to(device='cuda', dtype=dtype)\n net3 = torch.nn.ConvTranspose2d(32, 3, kernel_size=3, stride=2, padding=1, output_padding=1)\\\n .to(device='cuda', dtype=dtype)\n x = torch.rand(1, 128, 6, 6, device='cuda', dtype=dtype, requires_grad=True)\n x = net1(x)\n x = net2(x)\n x = net3(x)\n x.backward(torch.randn_like(x))\n torch.cuda.synchronize()\n\n # For https://github.com/pytorch/pytorch/pull/1273\n # Almost identical to the above `test_Conv2d_naive_groups`\n def test_Conv2d_groups_nobias(self):\n dev_dtypes = [(\"cpu\", torch.float)]\n if TEST_CUDA:\n dev_dtypes += [(\"cuda\", torch.float), (\"cuda\", torch.half)]\n if AMPERE_OR_ROCM:\n dev_dtypes += [(\"cuda\", torch.bfloat16)]\n for device, dtype in dev_dtypes:\n m = nn.Conv2d(4, 4, kernel_size=3, groups=2, bias=False).to(device, dtype)\n i = torch.randn(2, 4, 6, 6, device=device, dtype=dtype, requires_grad=True)\n output = m(i)\n grad_output = torch.randn(2, 4, 4, 4, device=device, dtype=dtype)\n output.backward(grad_output)\n\n m1 = nn.Conv2d(2, 2, kernel_size=3, bias=False).to(device, dtype)\n m1.weight.data.copy_(m.weight.data[:2])\n i1 = i.data[:, :2].contiguous().requires_grad_(True)\n output1 = m1(i1)\n output1.backward(grad_output[:, :2].contiguous())\n\n m2 = nn.Conv2d(2, 2, kernel_size=3, bias=False).to(device, dtype)\n m2.weight.data.copy_(m.weight.data[2:])\n i2 = i.data[:, 2:].contiguous().requires_grad_(True)\n output2 = m2(i2)\n output2.backward(grad_output[:, 2:].contiguous())\n\n self.assertEqual(output, torch.cat([output1, output2], 1))\n self.assertEqual(i.grad.data,\n torch.cat([i1.grad.data, i2.grad.data], 1),\n atol=dtype2prec_DONTUSE[dtype], rtol=0)\n self.assertEqual(m.weight.grad.data,\n torch.cat([m1.weight.grad.data, m2.weight.grad.data], 0),\n atol=1e-1 if dtype == torch.half else dtype2prec_DONTUSE[dtype], rtol=0)\n\n # Almost identical to the above `test_Conv2d_naive_groups`\n # Covering special case when group > 1, input-channel / group < 16 and output-channel is multiple of 16\n # See also https://github.com/pytorch/pytorch/pull/18463#issuecomment-476563686\n # and https://github.com/pytorch/pytorch/pull/18463#issuecomment-477001024\n def test_Conv2d_groups_nobias_v2(self):\n torch.manual_seed(123)\n dev_dtypes = [(\"cpu\", torch.float)]\n if TEST_CUDA:\n dev_dtypes += [(\"cuda\", torch.float), (\"cuda\", torch.half)]\n if AMPERE_OR_ROCM:\n dev_dtypes += [(\"cuda\", torch.bfloat16)]\n for device, dtype in dev_dtypes:\n m = nn.Conv2d(4, 16, kernel_size=3, groups=2, bias=False).to(device, dtype)\n i = torch.randn(2, 4, 6, 6, device=device, dtype=dtype, requires_grad=True)\n output = m(i)\n grad_output = torch.randn(2, 16, 4, 4, device=device, dtype=dtype)\n output.backward(grad_output)\n\n m1 = nn.Conv2d(2, 8, kernel_size=3, bias=False).to(device, dtype)\n m1.weight.data.copy_(m.weight.data[:8])\n i1 = i.data[:, :2].contiguous().requires_grad_(True)\n output1 = m1(i1)\n output1.backward(grad_output[:, :8].contiguous())\n\n m2 = nn.Conv2d(2, 8, kernel_size=3, bias=False).to(device, dtype)\n m2.weight.data.copy_(m.weight.data[8:])\n i2 = i.data[:, 2:].contiguous().requires_grad_(True)\n output2 = m2(i2)\n output2.backward(grad_output[:, 8:].contiguous())\n\n self.assertEqual(output, torch.cat([output1, output2], 1))\n self.assertEqual(i.grad.data,\n torch.cat([i1.grad.data, i2.grad.data], 1),\n atol=dtype2prec_DONTUSE[dtype], rtol=0)\n self.assertEqual(m.weight.grad.data,\n torch.cat([m1.weight.grad.data, m2.weight.grad.data], 0),\n atol=1e-1 if dtype == torch.half else dtype2prec_DONTUSE[dtype], rtol=0)\n\n # CPU-only test for group conv3d fast implementation using bmm\n # See: https://github.com/pytorch/pytorch/pull/36355\n def test_Conv3d_groups_nobias(self):\n torch.manual_seed(123)\n m = nn.Conv3d(4, 16, kernel_size=3, groups=2, bias=False).to(\"cpu\", torch.float)\n i = torch.randn(2, 4, 6, 6, 6, device=\"cpu\", dtype=torch.float, requires_grad=True)\n output = m(i)\n grad_output = torch.randn(2, 16, 4, 4, 4, device=\"cpu\", dtype=torch.float)\n output.backward(grad_output)\n\n m1 = nn.Conv3d(2, 8, kernel_size=3, bias=False).to(\"cpu\", torch.float)\n m1.weight.data.copy_(m.weight.data[:8])\n i1 = i.data[:, :2].contiguous().requires_grad_(True)\n output1 = m1(i1)\n output1.backward(grad_output[:, :8].contiguous())\n\n m2 = nn.Conv3d(2, 8, kernel_size=3, bias=False).to(\"cpu\", torch.float)\n m2.weight.data.copy_(m.weight.data[8:])\n i2 = i.data[:, 2:].contiguous().requires_grad_(True)\n output2 = m2(i2)\n output2.backward(grad_output[:, 8:].contiguous())\n\n self.assertEqual(output, torch.cat([output1, output2], 1))\n self.assertEqual(i.grad.data,\n torch.cat([i1.grad.data, i2.grad.data], 1),\n atol=dtype2prec_DONTUSE[torch.float], rtol=0)\n self.assertEqual(m.weight.grad.data,\n torch.cat([m1.weight.grad.data, m2.weight.grad.data], 0),\n atol=dtype2prec_DONTUSE[torch.float], rtol=dtype2prec_DONTUSE[torch.float])\n\n def test_Conv3d_groups_wbias(self):\n torch.manual_seed(123)\n m = nn.Conv3d(4, 16, kernel_size=3, groups=2, bias=True).to(\"cpu\", torch.float)\n i = torch.randn(2, 4, 6, 6, 6, device=\"cpu\", dtype=torch.float, requires_grad=True)\n output = m(i)\n grad_output = torch.randn(2, 16, 4, 4, 4, device=\"cpu\", dtype=torch.float)\n output.backward(grad_output)\n\n m1 = nn.Conv3d(2, 8, kernel_size=3, bias=True).to(\"cpu\", torch.float)\n m1.weight.data.copy_(m.weight.data[:8])\n m1.bias.data.copy_(m.bias.data[:8])\n i1 = i.data[:, :2].contiguous().requires_grad_(True)\n output1 = m1(i1)\n output1.backward(grad_output[:, :8].contiguous())\n\n m2 = nn.Conv3d(2, 8, kernel_size=3, bias=True).to(\"cpu\", torch.float)\n m2.weight.data.copy_(m.weight.data[8:])\n m2.bias.data.copy_(m.bias.data[8:])\n i2 = i.data[:, 2:].contiguous().requires_grad_(True)\n output2 = m2(i2)\n output2.backward(grad_output[:, 8:].contiguous())\n\n self.assertEqual(output, torch.cat([output1, output2], 1))\n self.assertEqual(i.grad.data,\n torch.cat([i1.grad.data, i2.grad.data], 1),\n atol=dtype2prec_DONTUSE[torch.float],\n rtol=dtype2prec_DONTUSE[torch.float])\n self.assertEqual(m.weight.grad.data,\n torch.cat([m1.weight.grad.data, m2.weight.grad.data], 0),\n atol=dtype2prec_DONTUSE[torch.float],\n rtol=dtype2prec_DONTUSE[torch.float])\n self.assertEqual(m.bias.grad.data,\n torch.cat([m1.bias.grad.data, m2.bias.grad.data], 0),\n atol=dtype2prec_DONTUSE[torch.float], rtol=dtype2prec_DONTUSE[torch.float])\n\n # Very similar to test_Conv2d_naive_groups but with special care to handle\n # the number of groups == number of input channels\n @unittest.skipIf(not TEST_CUDA, 'CUDA not available')\n @repeat_test_for_types(ALL_TENSORTYPES)\n @tf32_on_and_off(0.01)\n def test_Conv2d_depthwise_naive_groups_cuda(self, dtype=torch.float):\n for depth_multiplier in [1, 2]:\n m = nn.Conv2d(2, 2 * depth_multiplier, kernel_size=3, groups=2).to(\"cuda\", dtype)\n i = torch.randn(2, 2, 6, 6, device=\"cuda\", dtype=dtype).div_(2).requires_grad_()\n output = m(i)\n grad_output = torch.randn(2, 2 * depth_multiplier, 4, 4, device=\"cuda\", dtype=dtype) / 2\n output.backward(grad_output)\n\n offset = 1 * depth_multiplier\n\n m1 = nn.Conv2d(1, 1 * depth_multiplier, kernel_size=3).to(\"cuda\", dtype)\n m1.weight.data = m.weight.data[:offset].clone()\n m1.bias.data = m.bias.data[:offset].clone()\n i1 = i.detach()[:, :1].clone().requires_grad_()\n output1 = m1(i1)\n output1.backward(grad_output[:, :offset].contiguous())\n\n m2 = nn.Conv2d(1, 1 * depth_multiplier, kernel_size=3).to(\"cuda\", dtype)\n m2.weight.data.copy_(m.weight.data[offset:])\n m2.bias.data.copy_(m.bias.data[offset:])\n i2 = i.detach()[:, 1:].clone().requires_grad_()\n output2 = m2(i2)\n output2.backward(grad_output[:, offset:].contiguous())\n\n self.assertEqual(output, torch.cat([output1, output2], 1),\n atol=dtype2prec_DONTUSE[dtype], rtol=0)\n self.assertEqual(i.grad.data,\n torch.cat([i1.grad.data, i2.grad.data], 1),\n atol=dtype2prec_DONTUSE[dtype], rtol=0)\n self.assertEqual(m.bias.grad.data,\n torch.cat([m1.bias.grad.data,\n m2.bias.grad.data], 0),\n atol=dtype2prec_DONTUSE[dtype], rtol=0)\n self.assertEqual(m.weight.grad.data,\n torch.cat([m1.weight.grad.data,\n m2.weight.grad.data], 0),\n atol=dtype2prec_DONTUSE[dtype], rtol=0)\n\n @unittest.skipIf(not TEST_CUDA, 'CUDA not available')\n @repeat_test_for_types(ALL_TENSORTYPES)\n @tf32_on_and_off(0.001)\n def test_Conv3d_depthwise_naive_groups_cuda(self, dtype=torch.float):\n for depth_multiplier in [1, 2]:\n m = nn.Conv3d(2, 2 * depth_multiplier, kernel_size=3, groups=2).to(\"cuda\", dtype)\n i = torch.randn(2, 2, 6, 6, 6, device=\"cuda\", dtype=dtype).div_(2).requires_grad_()\n output = m(i)\n grad_output = torch.randn(2, 2 * depth_multiplier, 4, 4, 4, device=\"cuda\", dtype=dtype) / 2\n output.backward(grad_output)\n\n offset = 1 * depth_multiplier\n\n m1 = nn.Conv3d(1, 1 * depth_multiplier, kernel_size=3).to(\"cuda\", dtype)\n m1.weight.data = m.weight.data[:offset].clone()\n m1.bias.data = m.bias.data[:offset].clone()\n i1 = i.detach()[:, :1].clone().requires_grad_()\n output1 = m1(i1)\n output1.backward(grad_output[:, :offset].contiguous())\n\n m2 = nn.Conv3d(1, 1 * depth_multiplier, kernel_size=3).to(\"cuda\", dtype)\n m2.weight.data.copy_(m.weight.data[offset:])\n m2.bias.data.copy_(m.bias.data[offset:])\n i2 = i.detach()[:, 1:].clone().requires_grad_()\n output2 = m2(i2)\n output2.backward(grad_output[:, offset:].contiguous())\n\n self.assertEqual(output, torch.cat([output1, output2], 1),\n atol=dtype2prec_DONTUSE[dtype], rtol=0)\n self.assertEqual(i.grad.data,\n torch.cat([i1.grad.data, i2.grad.data], 1),\n atol=dtype2prec_DONTUSE[dtype], rtol=0)\n self.assertEqual(m.bias.grad.data,\n torch.cat([m1.bias.grad.data,\n m2.bias.grad.data], 0),\n atol=dtype2prec_DONTUSE[dtype], rtol=0)\n self.assertEqual(m.weight.grad.data,\n torch.cat([m1.weight.grad.data,\n m2.weight.grad.data], 0),\n atol=dtype2prec_DONTUSE[dtype], rtol=0)\n\n def test_MaxUnpool2d_output_size(self):\n m = nn.MaxPool2d(3, stride=2, return_indices=True)\n mu = nn.MaxUnpool2d(3, stride=2)\n big_t = torch.rand(1, 1, 6, 6)\n big_t[0][0][4][4] = 100\n output_big, indices_big = m(big_t)\n self.assertRaises(RuntimeError, lambda: mu(output_big, indices_big))\n\n small_t = torch.rand(1, 1, 5, 5)\n for i in range(0, 4, 2):\n for j in range(0, 4, 2):\n small_t[:, :, i, j] = 100\n output_small, indices_small = m(small_t)\n for h in range(3, 10):\n for w in range(3, 10):\n if 4 <= h <= 6 and 4 <= w <= 6:\n size = (h, w)\n if h == 6:\n size = (1, 1) + size\n\n mu(output_small, indices_small, output_size=size)\n else:\n self.assertRaises(ValueError, lambda: mu(output_small, indices_small, (h, w)))\n\n def test_container_copy(self):\n class Model(nn.Module):\n def __init__(self):\n super(Model, self).__init__()\n self.linear = nn.Linear(4, 5)\n\n def forward(self, input):\n return self.linear(input)\n\n input = torch.randn(2, 4)\n\n model = Model()\n model_cp = deepcopy(model)\n self.assertEqual(model(input).data, model_cp(input).data)\n\n model_cp.linear.weight.data[:] = 2\n self.assertNotEqual(model(input).data, model_cp(input).data)\n\n def test_RNN_cell(self):\n # this is just a smoke test; these modules are implemented through\n # autograd so no Jacobian test is needed\n for module in (nn.RNNCell, nn.GRUCell):\n for bias in (True, False):\n input = torch.randn(3, 10)\n hx = torch.randn(3, 20)\n cell = module(10, 20, bias=bias)\n for _ in range(6):\n hx = cell(input, hx)\n\n hx.sum().backward()\n\n def test_RNN_cell_forward_input_size(self):\n input = torch.randn(3, 11)\n hx = torch.randn(3, 20)\n for module in (nn.RNNCell, nn.GRUCell):\n cell = module(10, 20)\n self.assertRaises(Exception, lambda: cell(input, hx))\n\n def test_RNN_cell_forward_hidden_size(self):\n input = torch.randn(3, 10)\n hx = torch.randn(3, 21)\n cell_shared_param = (10, 20)\n for cell in (nn.RNNCell(*cell_shared_param, nonlinearity=\"relu\"),\n nn.RNNCell(*cell_shared_param, nonlinearity=\"tanh\"),\n nn.GRUCell(*cell_shared_param)):\n self.assertRaises(Exception, lambda: cell(input, hx))\n\n\n def _test_loss_equal_input_target_shape(self, cast):\n # Tests losses whose inputs should have the same size.\n losses = {\n 'mse_loss': lambda x, y: F.mse_loss(x, y),\n 'l1_loss': lambda x, y: F.l1_loss(x, y),\n 'smooth_l1_loss': lambda x, y: F.smooth_l1_loss(x, y),\n 'huber_loss': lambda x, y: F.huber_loss(x, y),\n 'kl_div': lambda x, y: F.kl_div(x, y),\n 'poisson_nll_loss': lambda x, y: F.poisson_nll_loss(x, y),\n }\n\n input = cast(torch.randn(3, 5))\n target = cast(torch.randn(5, 3))\n for _name, fn in losses.items():\n self.assertRaises(Exception, lambda: fn(input, target))\n\n def test_loss_equal_input_target_shape(self):\n self._test_loss_equal_input_target_shape(lambda x: x)\n\n def test_mse_loss_size_warning(self):\n i = torch.randn((10, 1), requires_grad=True)\n t = torch.randn((10,))\n with warnings.catch_warnings(record=True) as w:\n # Ensure warnings are being shown\n warnings.simplefilter(\"always\")\n # Trigger Warning\n F.mse_loss(i, t)\n # Check warning occurs\n self.assertEqual(len(w), 1)\n self.assertIn('Please ensure they have the same size.', str(w[0]))\n\n def test_poisson_nll_loss_reduction_modes(self):\n input = torch.tensor([0.5, 1.5, 2.5])\n target = torch.tensor([1., 2., 3.])\n component_wise_loss = torch.exp(input) - target * input\n self.assertEqual(component_wise_loss,\n F.poisson_nll_loss(input, target, reduction='none'))\n self.assertEqual(torch.sum(component_wise_loss),\n F.poisson_nll_loss(input, target, reduction='sum'))\n self.assertEqual(torch.mean(component_wise_loss),\n F.poisson_nll_loss(input, target, reduction='mean'))\n with self.assertRaisesRegex(ValueError, 'is not valid'):\n F.poisson_nll_loss(input, target, reduction='total')\n\n def test_gaussian_nll_loss_reduction_modes(self):\n input = torch.tensor([[0.5, 1.5, 2.5], [2., 4., 6.]])\n target = torch.tensor([[1., 2., 3.], [4., 5., 6.]])\n var = torch.tensor([[0.5, 1., 1.5], [1., 1.5, 2.]])\n component_wise_loss = 0.5 * (torch.sum(torch.log(var) + (input - target)**2 / var, dim=1))\n self.assertEqual(component_wise_loss,\n F.gaussian_nll_loss(input, target, var, reduction='none'))\n self.assertEqual(torch.sum(component_wise_loss),\n F.gaussian_nll_loss(input, target, var, reduction='sum'))\n self.assertEqual(torch.mean(component_wise_loss),\n F.gaussian_nll_loss(input, target, var, reduction='mean'))\n with self.assertRaisesRegex(ValueError, 'is not valid'):\n F.gaussian_nll_loss(input, target, var, reduction='total')\n\n def test_gaussian_nll_loss_args(self):\n input = torch.randn(3, 5)\n with self.assertRaisesRegex(ValueError, 'input and target must have same size'):\n target = torch.randn(3, 6)\n var = torch.ones(3, 5)\n torch.nn.functional.gaussian_nll_loss(input, target, var)\n with self.assertRaisesRegex(ValueError, 'var is of incorrect size'):\n target = torch.randn(3, 5)\n var = torch.ones(3, 3)\n torch.nn.functional.gaussian_nll_loss(input, target, var)\n with self.assertRaisesRegex(ValueError, 'var has negative entry/entries'):\n var = -1 * torch.ones(3, 5)\n torch.nn.functional.gaussian_nll_loss(input, target, var)\n\n def test_KLDivLoss_batch_mean(self):\n input_shape = (2, 5)\n log_prob1 = F.log_softmax(torch.randn(input_shape), 1)\n prob2 = F.softmax(torch.randn(input_shape), 1)\n\n loss = nn.KLDivLoss(reduction='batchmean')\n l = loss(log_prob1, prob2)\n\n loss_none_reduce = nn.KLDivLoss(reduction='sum')(log_prob1, prob2)\n expected = loss_none_reduce / input_shape[0]\n\n self.assertEqual(l, expected)\n\n def test_KLDivLoss_batch_mean_log_target(self):\n input_shape = (2, 5)\n log_prob1 = F.log_softmax(torch.randn(input_shape), 1)\n log_prob2 = F.log_softmax(torch.randn(input_shape), 1)\n\n loss = nn.KLDivLoss(reduction='batchmean', log_target=True)\n l = loss(log_prob1, log_prob2)\n\n loss_none_reduce = nn.KLDivLoss(reduction='sum', log_target=True)(log_prob1, log_prob2)\n expected = loss_none_reduce / input_shape[0]\n\n self.assertEqual(l, expected)\n\n def test_CTCLoss_typechecks(self):\n target_lengths = torch.tensor([30, 25, 20])\n input_lengths = torch.tensor([50, 50, 50])\n targets = torch.randint(1, 15, (sum(target_lengths),), dtype=torch.int)\n log_probs = torch.randn(50, 3, 15, dtype=torch.float).log_softmax(2)\n with self.assertRaises(RuntimeError):\n _input_lengths = input_lengths.to(dtype=torch.float)\n torch.nn.functional.ctc_loss(log_probs, targets, _input_lengths, target_lengths)\n with self.assertRaises(RuntimeError):\n target_lengths = target_lengths.to(dtype=torch.float)\n torch.nn.functional.ctc_loss(log_probs, targets, input_lengths, target_lengths)\n\n @unittest.skipIf(not TEST_CUDA, 'CUDA not available')\n def test_CTCLoss_lengthchecks_cuda(self):\n target_lengths = [30, 25, 20]\n input_lengths = [50, 50, 50]\n targets = torch.randint(1, 15, (3, 29), dtype=torch.long, device='cuda')\n log_probs = torch.randn(50, 3, 15, dtype=torch.float, device='cuda').log_softmax(2)\n with self.assertRaises(RuntimeError):\n torch.nn.functional.ctc_loss(log_probs, targets, input_lengths, target_lengths)\n\n def test_CTCLoss_lengthchecks_cpu(self):\n target_lengths = [30, 25, 20]\n input_lengths = [50, 50, 50]\n targets = torch.randint(1, 15, (3, 29), dtype=torch.int)\n log_probs = torch.randn(50, 3, 15, dtype=torch.float).log_softmax(2)\n with self.assertRaises(RuntimeError):\n torch.nn.functional.ctc_loss(log_probs, targets, input_lengths, target_lengths)\n\n @unittest.skipIf(not TEST_CUDA, 'CUDA not available')\n def test_CTCLoss_long_targets(self):\n input_length = 4000\n vocab_size = 3\n batch_size = 4\n target_length = 1200\n\n log_probs = torch.randn(input_length, batch_size, vocab_size).log_softmax(2).requires_grad_()\n targets = torch.randint(low=1, high=vocab_size - 1, size=(batch_size, target_length), dtype=torch.long)\n input_lengths = batch_size * [input_length]\n target_lengths = batch_size * [target_length]\n\n res_cpu = torch.nn.functional.ctc_loss(log_probs, targets, input_lengths, target_lengths,\n reduction='sum', zero_infinity=True)\n grad_out = torch.randn_like(res_cpu)\n grad_cpu, = torch.autograd.grad(res_cpu, log_probs, grad_out)\n\n with torch.backends.cudnn.flags(enabled=False):\n res_gpu = torch.nn.functional.ctc_loss(log_probs.cuda(), targets.cuda(), input_lengths, target_lengths,\n reduction='sum', zero_infinity=True)\n grad_gpu, = torch.autograd.grad(res_gpu, log_probs, grad_out.cuda())\n self.assertEqual(res_cpu, res_gpu, atol=1e-4, rtol=0)\n self.assertEqual(grad_cpu, grad_gpu, atol=1e-4, rtol=0)\n\n @unittest.skipIf(not TEST_CUDA, 'CUDA not available')\n def test_CTCLoss_critical_target_len(self):\n # cudnn has an unexpected problem with target length 256, see issue #53505\n N = 1\n S = 256\n C = 10\n T = 500\n target = torch.randint(low=1, high=C, size=(S,), dtype=torch.int)\n input_lengths = torch.full(size=(N,), fill_value=T, dtype=torch.int)\n target_lengths = torch.tensor(S, dtype=torch.int)\n inp = torch.randn(T, N, C, dtype=torch.float, device='cuda').log_softmax(2).requires_grad_()\n with cudnn.flags(enabled=True):\n res_gpu = torch.nn.functional.ctc_loss(inp, target, input_lengths, target_lengths, reduction='none')\n res_cpu = torch.nn.functional.ctc_loss(inp.cpu(), target, input_lengths, target_lengths, reduction='none')\n self.assertEqual(res_cpu, res_gpu, atol=1e-3, rtol=0)\n\n @unittest.skipIf(not TEST_CUDA, 'CUDA not available')\n def test_CTCLoss_zero_infinity(self):\n target_lengths = [60, 25, 20]\n input_lengths = [50, 50, 50]\n targets = torch.randint(1, 15, (sum(target_lengths),), dtype=torch.int, device='cuda')\n log_probs = torch.randn(50, 3, 15, dtype=torch.float, device='cuda').log_softmax(2).requires_grad_()\n res = torch.nn.functional.ctc_loss(log_probs, targets, input_lengths, target_lengths,\n reduction='sum', zero_infinity=True)\n with torch.backends.cudnn.flags(enabled=False):\n res2 = torch.nn.functional.ctc_loss(log_probs, targets.cuda().long(), input_lengths, target_lengths,\n reduction='sum', zero_infinity=True)\n res_cpu = torch.nn.functional.ctc_loss(log_probs.cpu(), targets.cpu(), input_lengths, target_lengths,\n reduction='sum', zero_infinity=True)\n\n self.assertEqual(res2, res, atol=1e-4, rtol=0)\n self.assertEqual(res_cpu, res.cpu(), atol=1e-4, rtol=0)\n g1, = torch.autograd.grad(res, log_probs)\n g2, = torch.autograd.grad(res2, log_probs)\n g3, = torch.autograd.grad(res_cpu, log_probs)\n self.assertEqual(g2, g3, atol=1e-4, rtol=0)\n self.assertEqual(g1, g2, atol=1e-4, rtol=0)\n self.assertTrue((g1 == g1).all().item()) # check that we don't have NaN\n\n def test_RNN_cell_no_broadcasting(self):\n def test(cell_module, input, hx, input_size, hidden_size):\n cell = cell_module(input_size, hidden_size)\n self.assertRaises(RuntimeError, lambda: cell(input, hx))\n\n def test_all(hidden_size, bad_hx, good_hx, input_size, input):\n test(nn.RNNCell, input, bad_hx, input_size, hidden_size)\n test(nn.GRUCell, input, bad_hx, input_size, hidden_size)\n test(nn.LSTMCell, input, (bad_hx, good_hx), input_size, hidden_size)\n test(nn.LSTMCell, input, (good_hx, bad_hx), input_size, hidden_size)\n\n hidden_size = 20\n input_size = 10\n input = torch.randn(3, input_size)\n bad_hx = torch.randn(1, hidden_size)\n good_hx = torch.randn(3, hidden_size)\n\n # Test hidden/input batch size broadcasting\n test_all(hidden_size, bad_hx, good_hx, input_size, input)\n\n # Test hx's hidden_size vs module's hidden_size broadcasting\n bad_hx = torch.randn(3, 1)\n test_all(hidden_size, bad_hx, good_hx, input_size, input)\n\n # Test input's input_size vs module's input_size broadcasting\n bad_input = torch.randn(3, 1)\n test_all(hidden_size, good_hx, good_hx, input_size, bad_input)\n\n def test_invalid_dropout_p(self):\n v = torch.ones(1)\n self.assertRaises(ValueError, lambda: nn.Dropout(-0.1))\n self.assertRaises(ValueError, lambda: nn.Dropout(1.1))\n self.assertRaises(ValueError, lambda: nn.Dropout2d(-0.1))\n self.assertRaises(ValueError, lambda: nn.Dropout2d(1.1))\n self.assertRaises(ValueError, lambda: nn.Dropout3d(-0.1))\n self.assertRaises(ValueError, lambda: nn.Dropout3d(1.1))\n self.assertRaises(ValueError, lambda: F.dropout(v, -0.1))\n self.assertRaises(ValueError, lambda: F.dropout(v, 1.1))\n\n def test_pad_sequence(self):\n def pad(tensor, length):\n return torch.cat(\n [tensor.data, tensor.data.new(\n length - tensor.size(0), *tensor.size()[1:]).zero_()])\n\n # single dimensional\n a = torch.tensor([1, 2, 3])\n b = torch.tensor([4, 5])\n c = torch.tensor([6])\n\n # batch_first = true\n expected = torch.tensor([[4, 5, 0], [1, 2, 3], [6, 0, 0]])\n padded = rnn_utils.pad_sequence([b, a, c], True)\n self.assertEqual(padded, expected)\n\n # batch_first = false\n padded = rnn_utils.pad_sequence([b, a, c])\n self.assertEqual(padded, expected.transpose(0, 1))\n\n # pad with non-zero value\n expected = torch.tensor([[4, 5, 1], [1, 2, 3], [6, 1, 1]])\n padded = rnn_utils.pad_sequence([b, a, c], True, 1)\n self.assertEqual(padded, expected)\n\n # Test pad sorted sequence\n expected = torch.tensor([[1, 2, 3], [4, 5, 0], [6, 0, 0]])\n padded = rnn_utils.pad_sequence([a, b, c], True)\n self.assertEqual(padded, expected)\n\n # more dimensions\n maxlen = 9\n for num_dim in (0, 1, 2, 3):\n sequences = []\n trailing_dims = [4] * num_dim\n for i in range(1, maxlen + 1):\n seq_len = i * i\n sequences.append(torch.rand(seq_len, 5, *trailing_dims))\n random.shuffle(sequences)\n expected = []\n for seq in sequences:\n expected.append(pad(seq, maxlen * maxlen))\n # batch first = true\n expected = torch.stack(expected)\n padded = rnn_utils.pad_sequence(sequences, True)\n self.assertEqual(padded, expected)\n\n # batch first = false\n padded = rnn_utils.pad_sequence(sequences)\n self.assertEqual(padded, expected.transpose(0, 1))\n\n def test_pack_sequence(self):\n def _compatibility_test(sequences, lengths, batch_first, enforce_sorted=False):\n padded = rnn_utils.pad_sequence(sequences, batch_first)\n packed = rnn_utils.pack_sequence(sequences, enforce_sorted)\n unpacked = rnn_utils.pad_packed_sequence(packed, batch_first)\n self.assertEqual(padded, unpacked[0])\n pack_padded = rnn_utils.pack_padded_sequence(\n padded, lengths, batch_first, enforce_sorted)\n self.assertEqual(packed, pack_padded)\n\n # single dimensional\n a = torch.tensor([1, 2, 3])\n b = torch.tensor([4, 5])\n c = torch.tensor([6])\n packed = rnn_utils.pack_sequence([a, b, c], enforce_sorted=False)\n expected = torch.tensor([1, 4, 6, 2, 5, 3])\n self.assertEqual(packed.batch_sizes, [3, 2, 1])\n self.assertEqual(packed.data.data, expected)\n self.assertEqual(packed.sorted_indices, [0, 1, 2])\n self.assertEqual(packed.unsorted_indices, [0, 1, 2])\n\n packed_unsorted = rnn_utils.pack_sequence([b, c, a], enforce_sorted=False)\n self.assertEqual(packed_unsorted.batch_sizes, [3, 2, 1])\n self.assertEqual(packed_unsorted.data.data, expected)\n self.assertEqual(packed_unsorted.sorted_indices, [2, 0, 1])\n self.assertEqual(packed_unsorted.unsorted_indices, [1, 2, 0])\n\n # single dimensional, enforce_sorted = True\n packed_enforce_sorted = rnn_utils.pack_sequence([a, b, c], enforce_sorted=True)\n self.assertEqual(packed_enforce_sorted.batch_sizes, [3, 2, 1])\n self.assertEqual(packed_enforce_sorted.data.data, expected)\n self.assertTrue(packed_enforce_sorted.sorted_indices is None)\n self.assertTrue(packed_enforce_sorted.unsorted_indices is None)\n\n with self.assertRaisesRegex(RuntimeError, 'must be sorted in decreasing order'):\n rnn_utils.pack_sequence([b, c, a], enforce_sorted=True)\n\n with self.assertRaisesRegex(RuntimeError, 'You can pass `enforce_sorted=False`'):\n rnn_utils.pack_sequence([b, c, a], enforce_sorted=True)\n\n # more dimensions\n maxlen = 9\n for num_dim in (0, 1, 2, 3):\n sequences = []\n lengths = []\n trailing_dims = [4] * num_dim\n for i in range(maxlen, 0, -1):\n seq_len = i * i\n lengths.append(seq_len)\n sequences.append(torch.rand(seq_len, 5, *trailing_dims))\n unsorted_sequences = [s.clone() for s in sequences]\n random.shuffle(unsorted_sequences)\n unsorted_sequences_lengths = [t.size(0) for t in unsorted_sequences]\n\n # compatibility with other utilities\n for batch_first in (True, False):\n for enforce_sorted in (True, False):\n _compatibility_test(sequences, lengths, batch_first, enforce_sorted)\n _compatibility_test(unsorted_sequences, unsorted_sequences_lengths,\n batch_first)\n\n def test_pack_padded_sequence(self):\n def generate_test_case(sorted_lengths, should_shuffle):\n def pad(tensor, length):\n return torch.cat([tensor, tensor.new(length - tensor.size(0), *tensor.size()[1:]).zero_()])\n\n max_length = sorted_lengths[0]\n batch_sizes = [sum(map(bool, filter(lambda x: x >= i, sorted_lengths)))\n for i in range(1, max_length + 1)]\n offset = 0\n padded = torch.cat([pad(i * 100 + torch.arange(1., 5 * l + 1).view(l, 1, 5), max_length)\n for i, l in enumerate(sorted_lengths, 1)], 1)\n expected_data = [[torch.arange(1., 6) + (i + 1) * 100 + 5 * n for i in range(batch_size)]\n for n, batch_size in enumerate(batch_sizes)]\n expected_data = list(itertools.chain.from_iterable(expected_data))\n expected_data = torch.stack(expected_data, dim=0)\n\n if should_shuffle:\n # Shuffle the padded sequence to create an unsorted sequence\n permutation = list(range(len(sorted_lengths)))\n random.shuffle(permutation)\n\n unsorted_indices = torch.tensor(permutation)\n padded = padded.index_select(1, unsorted_indices)\n lengths = torch.tensor(sorted_lengths).index_select(0, unsorted_indices)\n else:\n unsorted_indices = None\n lengths = sorted_lengths\n\n return padded.requires_grad_(), lengths, expected_data, batch_sizes, unsorted_indices\n\n test_cases = [\n # sorted_lengths, should_shuffle\n [[10, 8, 4, 2, 2, 2, 1], False],\n [[11, 10, 8, 6, 4, 3, 1], False],\n [[11, 10, 8, 6, 4, 3, 1], True],\n ]\n\n for test_case, batch_first in itertools.product(test_cases, (True, False)):\n sorted_lengths, should_shuffle = test_case\n padded, lengths, expected_data, batch_sizes, unsorted_indices = generate_test_case(\n sorted_lengths, should_shuffle)\n\n src = padded\n if batch_first:\n src = src.transpose(0, 1)\n\n # check output\n packed = rnn_utils.pack_padded_sequence(src, lengths, batch_first=batch_first,\n enforce_sorted=not should_shuffle)\n self.assertEqual(packed.data.data, expected_data)\n self.assertEqual(packed.batch_sizes, batch_sizes)\n self.assertEqual(packed.unsorted_indices, unsorted_indices)\n\n # test inverse\n unpacked, unpacked_len = rnn_utils.pad_packed_sequence(packed, batch_first=batch_first)\n self.assertEqual(unpacked, src)\n self.assertEqual(unpacked_len, lengths)\n\n # check grad\n if padded.grad is not None:\n padded.grad.data.zero_()\n grad_output = unpacked.data.clone().normal_()\n unpacked.backward(grad_output)\n if batch_first:\n grad_output.transpose_(0, 1)\n for i, l in enumerate(lengths):\n self.assertEqual(padded.grad.data[:l, i], grad_output[:l, i])\n if l < 10:\n self.assertEqual(padded.grad.data[l:, i].abs().sum(), 0)\n\n # test error messages\n with self.assertRaisesRegex(RuntimeError, 'You can pass `enforce_sorted=False`'):\n packed = rnn_utils.pack_padded_sequence(torch.randn(3, 3), [1, 3, 2])\n with self.assertRaisesRegex(RuntimeError, 'empty tensor'):\n packed = rnn_utils.pack_padded_sequence(torch.randn(0, 0), [])\n\n def test_LSTM_cell(self):\n # this is just a smoke test; these modules are implemented through\n # autograd so no Jacobian test is needed\n for bias in (True, False):\n input = torch.randn(3, 10)\n hx = torch.randn(3, 20)\n cx = torch.randn(3, 20)\n lstm = nn.LSTMCell(10, 20, bias=bias)\n for _ in range(6):\n hx, cx = lstm(input, (hx, cx))\n\n (hx + cx).sum().backward()\n\n def test_LSTM_cell_forward_input_size(self):\n input = torch.randn(3, 11)\n hx = torch.randn(3, 20)\n cx = torch.randn(3, 20)\n lstm = nn.LSTMCell(10, 20)\n self.assertRaises(Exception, lambda: lstm(input, (hx, cx)))\n\n def test_LSTM_cell_forward_hidden_size(self):\n input = torch.randn(3, 10)\n hx = torch.randn(3, 21)\n cx = torch.randn(3, 20)\n lstm = nn.LSTMCell(10, 20)\n self.assertRaises(Exception, lambda: lstm(input, (hx, cx)))\n self.assertRaises(Exception, lambda: lstm(input, (cx, hx)))\n\n\n @unittest.skipIf(not TEST_CUDA, 'CUDA not available')\n def test_pack_sequence_batch_sizes_throw(self):\n with self.assertRaisesRegex(ValueError, r\"batch_sizes should always be on CPU\"):\n m = nn.LSTM(3, 4, bidirectional=True, num_layers=2).to('cuda')\n a = torch.rand(5, 3, device='cuda')\n b = torch.tensor([1, 1, 1, 1, 1], device='cuda')\n input = nn.utils.rnn.PackedSequence(a, b)\n\n def test_Transformer_cell(self):\n # this is just a smoke test; these modules are implemented through\n # autograd so no Jacobian test is needed\n d_model = 512\n nhead = 16\n num_encoder_layers = 4\n num_decoder_layers = 3\n dim_feedforward = 256\n dropout = 0.3\n bsz = 8\n seq_length = 35\n tgt_length = 15\n\n transformer = nn.Transformer(d_model, nhead, num_encoder_layers, num_decoder_layers,\n dim_feedforward, dropout)\n src = torch.randn(seq_length, bsz, d_model)\n src_mask = transformer.generate_square_subsequent_mask(seq_length).double()\n tgt = torch.randn(tgt_length, bsz, d_model)\n tgt_mask = transformer.generate_square_subsequent_mask(tgt_length).double()\n memory_mask = torch.randn(tgt_length, seq_length).double()\n src_key_padding_mask = torch.rand(bsz, seq_length) >= 0.5\n tgt_key_padding_mask = torch.rand(bsz, tgt_length) >= 0.5\n memory_key_padding_mask = torch.rand(bsz, seq_length) >= 0.5\n\n output = transformer(src, tgt,\n src_mask=src_mask,\n tgt_mask=tgt_mask,\n memory_mask=memory_mask,\n src_key_padding_mask=src_key_padding_mask,\n tgt_key_padding_mask=tgt_key_padding_mask,\n memory_key_padding_mask=memory_key_padding_mask)\n output.sum().backward()\n\n def test_transformerencoderlayer(self):\n # this is a deterministic test for TransformerEncoderLayer\n d_model = 4\n nhead = 2\n dim_feedforward = 16\n dropout = 0.0\n bsz = 2\n\n model = nn.TransformerEncoderLayer(d_model, nhead, dim_feedforward, dropout)\n\n # set constant weights of the model\n for idx, p in enumerate(model.parameters()):\n x = p.data\n sz = x.view(-1).size(0)\n shape = x.shape\n x = torch.cos(torch.arange(0, sz).float().view(shape))\n p.data.copy_(x)\n\n # deterministic input\n encoder_input = torch.Tensor([[[20, 30, 40, 50]]])\n result = model(encoder_input)\n ref_output = torch.Tensor([[[2.258703, 0.127985, -0.697881, 0.170862]]])\n result = result.detach().numpy()\n ref_output = ref_output.detach().numpy()\n self.assertEqual(tuple(result.shape), tuple(ref_output.shape))\n np.testing.assert_allclose(result, ref_output, atol=1e-5)\n # 0 values are NOT masked. This shouldn't mask anything.\n mask = torch.Tensor([[0]]) == 1\n result = model(encoder_input, src_key_padding_mask=mask)\n result = result.detach().numpy()\n self.assertEqual(tuple(result.shape), tuple(ref_output.shape))\n np.testing.assert_allclose(result, ref_output, atol=1e-5)\n # 1 values are masked. Since there is only 1 input embedding this\n # will result in nan.\n mask = torch.Tensor([[1]]) == 1\n result = model(encoder_input, src_key_padding_mask=mask)\n result = result.detach().numpy()\n self.assertTrue(np.isnan(result).all())\n\n # deterministic input\n encoder_input = torch.Tensor([[[1, 2, 3, 4]],\n [[5, 6, 7, 8]]])\n result = model(encoder_input)\n ref_output = torch.Tensor([[[2.272644, 0.119035, -0.691669, 0.153486]],\n [[2.272644, 0.119035, -0.691669, 0.153486]]])\n result = result.detach().numpy()\n ref_output = ref_output.detach().numpy()\n self.assertEqual(tuple(result.shape), tuple(ref_output.shape))\n np.testing.assert_allclose(result, ref_output, atol=1e-5)\n # all 0 which is no masking\n mask = torch.Tensor([[0, 0]]) == 1\n result = model(encoder_input, src_key_padding_mask=mask)\n result = result.detach().numpy()\n self.assertEqual(tuple(result.shape), tuple(ref_output.shape))\n np.testing.assert_allclose(result, ref_output, atol=1e-5)\n mask = torch.Tensor([[1, 0]]) == 1\n result = model(encoder_input, src_key_padding_mask=mask)\n ref_output = torch.Tensor([[[2.301516, 0.092249, -0.679101, 0.103088]],\n [[2.301516, 0.092249, -0.679101, 0.103088]]])\n result = result.detach().numpy()\n ref_output = ref_output.detach().numpy()\n self.assertEqual(tuple(result.shape), tuple(ref_output.shape))\n np.testing.assert_allclose(result, ref_output, atol=1e-5)\n\n # deterministic input\n encoder_input = torch.Tensor([[[0.7462, 0.6653, 0.5679, 0.4891],\n [0.5387, 0.1655, 0.3565, 0.0471]],\n [[0.8335, 0.2799, 0.5031, 0.2947],\n [0.1402, 0.0318, 0.7636, 0.1346]],\n [[0.6333, 0.9344, 0.1376, 0.9938],\n [0.8924, 0.2872, 0.6692, 0.2944]],\n [[0.9897, 0.6915, 0.3154, 0.1733],\n [0.8645, 0.3513, 0.3064, 0.0767]],\n [[0.8117, 0.2366, 0.4838, 0.7881],\n [0.3718, 0.4945, 0.9511, 0.0864]]])\n result = model(encoder_input)\n ref_output = torch.Tensor([[[2.428589, 0.020835, -0.602055, -0.085249],\n [2.427987, 0.021213, -0.602496, -0.084103]],\n [[2.424689, 0.019155, -0.604793, -0.085672],\n [2.413863, 0.022211, -0.612486, -0.072490]],\n [[2.433774, 0.021598, -0.598343, -0.087548],\n [2.425104, 0.019748, -0.604515, -0.084839]],\n [[2.436185, 0.022682, -0.596625, -0.087261],\n [2.433556, 0.021891, -0.598509, -0.086832]],\n [[2.416246, 0.017512, -0.610712, -0.082961],\n [2.422901, 0.024187, -0.606178, -0.074929]]])\n result = result.detach().numpy()\n ref_output = ref_output.detach().numpy()\n self.assertEqual(tuple(result.shape), tuple(ref_output.shape))\n np.testing.assert_allclose(result, ref_output, atol=1e-5)\n # all 0\n mask = torch.zeros([2, 5]) == 1\n result = model(encoder_input, src_key_padding_mask=mask)\n result = result.detach().numpy()\n self.assertEqual(tuple(result.shape), tuple(ref_output.shape))\n np.testing.assert_allclose(result, ref_output, atol=1e-5)\n mask[0, 1] = 1\n mask[1, 3] = 1\n mask[1, 4] = 1\n result = model(encoder_input, src_key_padding_mask=mask)\n ref_output = torch.Tensor([[[2.429026, 0.020793, -0.601741, -0.085642],\n [2.428811, 0.021445, -0.601912, -0.084252]],\n [[2.425009, 0.019155, -0.604566, -0.085899],\n [2.415408, 0.02249 , -0.611415, -0.073]],\n [[2.434199, 0.021682, -0.598039, -0.087699],\n [2.42598, 0.019941, -0.603896, -0.085091]],\n [[2.436457, 0.022736, -0.59643 , -0.08736],\n [2.434021, 0.022093, -0.598179, -0.08679]],\n [[2.416531, 0.017498, -0.610513, -0.083181],\n [2.4242, 0.024653, -0.605266, -0.074959]]])\n result = result.detach().numpy()\n ref_output = ref_output.detach().numpy()\n self.assertEqual(tuple(result.shape), tuple(ref_output.shape))\n np.testing.assert_allclose(result, ref_output, atol=1e-5)\n\n def test_transformerencoderlayer_gelu(self):\n # this is a deterministic test for TransformerEncoderLayer with gelu activation\n d_model = 4\n nhead = 2\n dim_feedforward = 16\n dropout = 0.0\n bsz = 2\n activation = \"gelu\"\n\n model = nn.TransformerEncoderLayer(d_model, nhead, dim_feedforward, dropout, activation)\n\n # set constant weights of the model\n for idx, p in enumerate(model.parameters()):\n x = p.data\n sz = x.view(-1).size(0)\n shape = x.shape\n x = torch.cos(torch.arange(0, sz).float().view(shape))\n p.data.copy_(x)\n\n # deterministic input\n encoder_input = torch.Tensor([[[20, 30, 40, 50]]])\n result = model(encoder_input)\n ref_output = torch.Tensor([[[2.249815, 0.131006, -0.702199, 0.177868]]])\n self.assertEqual(tuple(result.shape), tuple(ref_output.shape))\n torch.testing.assert_allclose(result, ref_output)\n\n # deterministic input\n encoder_input = torch.Tensor([[[1, 2, 3, 4]],\n [[5, 6, 7, 8]]])\n result = model(encoder_input)\n ref_output = torch.Tensor([[[2.264103, 0.121417, -0.696012, 0.159724]],\n [[2.264103, 0.121417, -0.696012, 0.159724]]])\n self.assertEqual(tuple(result.shape), tuple(ref_output.shape))\n torch.testing.assert_allclose(result, ref_output)\n\n # deterministic input\n encoder_input = torch.Tensor([[[0.7462, 0.6653, 0.5679, 0.4891],\n [0.5387, 0.1655, 0.3565, 0.0471]],\n [[0.8335, 0.2799, 0.5031, 0.2947],\n [0.1402, 0.0318, 0.7636, 0.1346]],\n [[0.6333, 0.9344, 0.1376, 0.9938],\n [0.8924, 0.2872, 0.6692, 0.2944]],\n [[0.9897, 0.6915, 0.3154, 0.1733],\n [0.8645, 0.3513, 0.3064, 0.0767]],\n [[0.8117, 0.2366, 0.4838, 0.7881],\n [0.3718, 0.4945, 0.9511, 0.0864]]])\n result = model(encoder_input)\n ref_output = torch.Tensor([[[2.42163188, 0.03227153, -0.60714219, -0.05908082],\n [2.42151276, 0.03302179, -0.60722523, -0.05762651]],\n [[2.41926761, 0.02974034, -0.60879519, -0.0621269],\n [2.41626395, 0.03539356, -0.61087842, -0.04978623]],\n [[2.42382808, 0.03218872, -0.6055963, -0.06073591],\n [2.41983477, 0.03085259, -0.60840145, -0.06046414]],\n [[2.42500749, 0.03328855, -0.60476388, -0.0595334],\n [2.4237977, 0.03290575, -0.60561789, -0.05940082]],\n [[2.41383916, 0.02686345, -0.61256377, -0.06380707],\n [2.42000277, 0.03800944, -0.60824798, -0.04754947]]])\n self.assertEqual(tuple(result.shape), tuple(ref_output.shape))\n torch.testing.assert_allclose(result, ref_output)\n\n def test_transformerdecoderlayer(self):\n # this is a deterministic test for TransformerDecoderLayer\n d_model = 4\n nhead = 2\n dim_feedforward = 16\n dropout = 0.0\n bsz = 2\n seq_length = 5\n tgt_length = 3\n\n model = nn.TransformerDecoderLayer(d_model, nhead, dim_feedforward, dropout)\n\n # set constant weights of the model\n for idx, p in enumerate(model.parameters()):\n x = p.data\n sz = x.view(-1).size(0)\n shape = x.shape\n x = torch.cos(torch.arange(0, sz).float().view(shape))\n p.data.copy_(x)\n\n # deterministic input\n decoder_input = torch.Tensor([[[20, 30, 40, 50]]])\n memory_input = torch.Tensor([[[60, 70, 80, 90]]])\n result = model(decoder_input, memory_input)\n ref_output = torch.Tensor([[[2.314351, 0.094805, -0.671322, 0.101977]]])\n result = result.detach().numpy()\n ref_output = ref_output.detach().numpy()\n self.assertEqual(tuple(result.shape), tuple(ref_output.shape))\n np.testing.assert_allclose(result, ref_output, atol=1e-5)\n\n # deterministic input\n decoder_input = torch.Tensor([[[9, 10, 11, 12]],\n [[11, 12, 13, 14]]])\n memory_input = torch.Tensor([[[1, 2, 3, 4]]])\n result = model(decoder_input, memory_input)\n result = result.detach().numpy()\n ref_output = torch.Tensor([[[2.422245, 0.051716, -0.606338, -0.024756]],\n [[2.422245, 0.051716, -0.606338, -0.024756]]])\n ref_output = ref_output.detach().numpy()\n self.assertEqual(tuple(result.shape), tuple(ref_output.shape))\n np.testing.assert_allclose(result, ref_output, atol=1e-5)\n\n # deterministic input\n decoder_input = torch.Tensor([[[1, 2, 3, 4]],\n [[5, 6, 7, 8]]])\n memory_input = torch.Tensor([[[9, 10, 11, 12]],\n [[11, 12, 13, 14]]])\n result = model(decoder_input, memory_input)\n ref_output = torch.Tensor([[[2.343536, 0.085561, -0.654954, 0.074991]],\n [[2.343536, 0.085561, -0.654954, 0.074991]]])\n result = result.detach().numpy()\n ref_output = ref_output.detach().numpy()\n self.assertEqual(tuple(result.shape), tuple(ref_output.shape))\n np.testing.assert_allclose(result, ref_output, atol=1e-5)\n\n # deterministic input\n decoder_input = torch.Tensor([[[0.4517, 0.6793, 0.5313, 0.0034],\n [0.2678, 0.3677, 0.4459, 0.7166]],\n [[0.8100, 0.3716, 0.4096, 0.1976],\n [0.6958, 0.8844, 0.6081, 0.8315]],\n [[0.0494, 0.9343, 0.5955, 0.3830],\n [0.5404, 0.3464, 0.9378, 0.6200]]])\n memory_input = torch.Tensor([[[0.7462, 0.6653, 0.5679, 0.4891],\n [0.5387, 0.1655, 0.3565, 0.0471]],\n [[0.8335, 0.2799, 0.5031, 0.2947],\n [0.1402, 0.0318, 0.7636, 0.1346]],\n [[0.6333, 0.9344, 0.1376, 0.9938],\n [0.8924, 0.2872, 0.6692, 0.2944]],\n [[0.9897, 0.6915, 0.3154, 0.1733],\n [0.8645, 0.3513, 0.3064, 0.0767]],\n [[0.8117, 0.2366, 0.4838, 0.7881],\n [0.3718, 0.4945, 0.9511, 0.0864]]])\n result = model(decoder_input, memory_input)\n ref_output = torch.Tensor([[[2.430065, 0.027862, -0.601136, -0.073096],\n [2.431935, 0.028907, -0.599809, -0.072488]],\n [[2.428457, 0.027053, -0.602275, -0.073462],\n [2.431970, 0.029387, -0.599789, -0.071621]],\n [[2.431934, 0.028196, -0.599802, -0.073809],\n [2.432306, 0.028858, -0.599542, -0.072846]]])\n result = result.detach().numpy()\n ref_output = ref_output.detach().numpy()\n self.assertEqual(tuple(result.shape), tuple(ref_output.shape))\n np.testing.assert_allclose(result, ref_output, atol=1e-5)\n\n # key_padding_mask\n key_padding_mask = torch.zeros(2, 3) == 1\n result = model(decoder_input, memory_input, tgt_key_padding_mask=key_padding_mask)\n ref_output = torch.Tensor([[[2.430065, 0.027862, -0.601136, -0.073096],\n [2.431935, 0.028907, -0.599809, -0.072488]],\n [[2.428457, 0.027053, -0.602275, -0.073462],\n [2.431970, 0.029387, -0.599789, -0.071621]],\n [[2.431934, 0.028196, -0.599802, -0.073809],\n [2.432306, 0.028858, -0.599542, -0.072846]]])\n result = result.detach().numpy()\n ref_output = ref_output.detach().numpy()\n self.assertEqual(tuple(result.shape), tuple(ref_output.shape))\n np.testing.assert_allclose(result, ref_output, atol=1e-5)\n\n # key_padding_mask\n key_padding_mask[0, 2] = 1\n key_padding_mask[1, 1] = 1\n key_padding_mask[1, 2] = 1\n result = model(decoder_input, memory_input, tgt_key_padding_mask=key_padding_mask)\n ref_output = torch.Tensor([[[2.430025, 0.027643, -0.601164, -0.073476],\n [2.4323, 0.029375, -0.599553, -0.071881]],\n [[2.428523, 0.026838, -0.602226, -0.07391],\n [2.432634, 0.029842, -0.599318, -0.071253]],\n [[2.432278, 0.028152, -0.599555, -0.074139],\n [2.432659, 0.029244, -0.599294, -0.072382]]])\n result = result.detach().numpy()\n ref_output = ref_output.detach().numpy()\n self.assertEqual(tuple(result.shape), tuple(ref_output.shape))\n np.testing.assert_allclose(result, ref_output, atol=1e-5)\n\n # memory_key_padding_mask\n key_padding_mask = torch.zeros(2, 5) == 1\n result = model(decoder_input, memory_input, memory_key_padding_mask=key_padding_mask)\n ref_output = torch.Tensor([[[2.430065, 0.027862, -0.601136, -0.073096],\n [2.431935, 0.028907, -0.599809, -0.072488]],\n [[2.428457, 0.027053, -0.602275, -0.073462],\n [2.431970, 0.029387, -0.599789, -0.071621]],\n [[2.431934, 0.028196, -0.599802, -0.073809],\n [2.432306, 0.028858, -0.599542, -0.072846]]])\n result = result.detach().numpy()\n ref_output = ref_output.detach().numpy()\n self.assertEqual(tuple(result.shape), tuple(ref_output.shape))\n np.testing.assert_allclose(result, ref_output, atol=1e-5)\n\n # memory_key_padding_mask\n key_padding_mask[0, 4] = 1\n key_padding_mask[1, 3] = 1\n key_padding_mask[1, 4] = 1\n result = model(decoder_input, memory_input, memory_key_padding_mask=key_padding_mask)\n ref_output = torch.Tensor([[[2.429757, 0.027358, -0.601351, -0.073816],\n [2.432692, 0.028583, -0.599263, -0.073634]],\n [[2.428247, 0.02662, -0.602419, -0.074123],\n [2.432657, 0.029055, -0.599293, -0.072732]],\n [[2.431515, 0.027687, -0.600096, -0.074459],\n [2.433075, 0.028543, -0.598987, -0.073985]]])\n result = result.detach().numpy()\n ref_output = ref_output.detach().numpy()\n self.assertEqual(tuple(result.shape), tuple(ref_output.shape))\n np.testing.assert_allclose(result, ref_output, atol=1e-5)\n\n def test_transformerdecoderlayer_gelu(self):\n # this is a deterministic test for TransformerDecoderLayer with gelu activation\n d_model = 4\n nhead = 2\n dim_feedforward = 16\n dropout = 0.0\n bsz = 2\n seq_length = 5\n tgt_length = 3\n activation = \"gelu\"\n\n model = nn.TransformerDecoderLayer(d_model, nhead, dim_feedforward, dropout, activation)\n\n # set constant weights of the model\n for idx, p in enumerate(model.parameters()):\n x = p.data\n sz = x.view(-1).size(0)\n shape = x.shape\n x = torch.cos(torch.arange(0, sz).float().view(shape))\n p.data.copy_(x)\n\n # deterministic input\n decoder_input = torch.Tensor([[[20, 30, 40, 50]]])\n memory_input = torch.Tensor([[[60, 70, 80, 90]]])\n result = model(decoder_input, memory_input)\n ref_output = torch.Tensor([[[2.306435, 0.095946, -0.675796, 0.10687]]])\n self.assertEqual(tuple(result.shape), tuple(ref_output.shape))\n torch.testing.assert_allclose(result, ref_output)\n\n # deterministic input\n decoder_input = torch.Tensor([[[9, 10, 11, 12]],\n [[11, 12, 13, 14]]])\n memory_input = torch.Tensor([[[1, 2, 3, 4]]])\n result = model(decoder_input, memory_input)\n ref_output = torch.Tensor([[[2.415448, 0.054389, -0.610932, -0.0156613]],\n [[2.415448, 0.054389, -0.610932, -0.0156613]]])\n self.assertEqual(tuple(result.shape), tuple(ref_output.shape))\n torch.testing.assert_allclose(result, ref_output)\n\n # deterministic input\n decoder_input = torch.Tensor([[[1, 2, 3, 4]],\n [[5, 6, 7, 8]]])\n memory_input = torch.Tensor([[[9, 10, 11, 12]],\n [[11, 12, 13, 14]]])\n result = model(decoder_input, memory_input)\n ref_output = torch.Tensor([[[2.338531, 0.087709, -0.65776, 0.080646]],\n [[2.338531, 0.087709, -0.65776, 0.080646]]])\n self.assertEqual(tuple(result.shape), tuple(ref_output.shape))\n torch.testing.assert_allclose(result, ref_output)\n\n # deterministic input\n decoder_input = torch.Tensor([[[0.4517, 0.6793, 0.5313, 0.0034],\n [0.2678, 0.3677, 0.4459, 0.7166]],\n [[0.8100, 0.3716, 0.4096, 0.1976],\n [0.6958, 0.8844, 0.6081, 0.8315]],\n [[0.0494, 0.9343, 0.5955, 0.3830],\n [0.5404, 0.3464, 0.9378, 0.6200]]])\n memory_input = torch.Tensor([[[0.7462, 0.6653, 0.5679, 0.4891],\n [0.5387, 0.1655, 0.3565, 0.0471]],\n [[0.8335, 0.2799, 0.5031, 0.2947],\n [0.1402, 0.0318, 0.7636, 0.1346]],\n [[0.6333, 0.9344, 0.1376, 0.9938],\n [0.8924, 0.2872, 0.6692, 0.2944]],\n [[0.9897, 0.6915, 0.3154, 0.1733],\n [0.8645, 0.3513, 0.3064, 0.0767]],\n [[0.8117, 0.2366, 0.4838, 0.7881],\n [0.3718, 0.4945, 0.9511, 0.0864]]])\n result = model(decoder_input, memory_input)\n ref_output = torch.Tensor([[[2.42049104, 0.03443088, -0.60793706, -0.05436271],\n [2.42210631, 0.03546578, -0.60679895, -0.05357488]],\n [[2.41907674, 0.0336104, -0.60892977, -0.05490462],\n [2.42216881, 0.03586554, -0.6067524, -0.05289126]],\n [[2.42205716, 0.03488046, -0.60683681, -0.05460596],\n [2.42240309, 0.0354595, -0.60659063, -0.05378816]]])\n self.assertEqual(tuple(result.shape), tuple(ref_output.shape))\n torch.testing.assert_allclose(result, ref_output)\n\n def test_transformerencoder(self):\n def get_a_test_layer(use_cuda, activation):\n d_model = 4\n nhead = 2\n dim_feedforward = 16\n dropout = 0.0\n device = torch.device(\"cuda\" if use_cuda else \"cpu\")\n\n layer = nn.TransformerEncoderLayer(\n d_model,\n nhead,\n dim_feedforward=dim_feedforward,\n dropout=dropout,\n activation=activation).to(device)\n\n with torch.no_grad():\n # set constant weights of the model\n for idx, p in enumerate(layer.parameters()):\n x = p.data\n sz = x.view(-1).size(0)\n shape = x.shape\n x = torch.cos(torch.arange(0, sz).float().view(shape))\n p.data.copy_(x)\n\n return layer\n\n # this is a deterministic test for TransformerEncoder\n activation = \"relu\"\n use_cuda = torch.cuda.is_available()\n device = torch.device(\"cuda\" if use_cuda else \"cpu\")\n\n encoder_layer = get_a_test_layer(use_cuda=use_cuda, activation=activation)\n\n model = nn.TransformerEncoder(encoder_layer, 1).to(device)\n\n # deterministic input\n encoder_input = torch.Tensor([[[0.7462, 0.6653, 0.5679, 0.4891],\n [0.5387, 0.1655, 0.3565, 0.0471]],\n [[0.8335, 0.2799, 0.5031, 0.2947],\n [0.1402, 0.0318, 0.7636, 0.1346]],\n [[0.6333, 0.9344, 0.1376, 0.9938],\n [0.8924, 0.2872, 0.6692, 0.2944]],\n [[0.9897, 0.6915, 0.3154, 0.1733],\n [0.8645, 0.3513, 0.3064, 0.0767]],\n [[0.8117, 0.2366, 0.4838, 0.7881],\n [0.3718, 0.4945, 0.9511, 0.0864]]]\n ).to(device)\n result = model(encoder_input)\n ref_output = torch.Tensor([[[2.428589, 0.020835, -0.602055, -0.085249],\n [2.427987, 0.021213, -0.602496, -0.084103]],\n [[2.424689, 0.019155, -0.604793, -0.085672],\n [2.413863, 0.022211, -0.612486, -0.072490]],\n [[2.433774, 0.021598, -0.598343, -0.087548],\n [2.425104, 0.019748, -0.604515, -0.084839]],\n [[2.436185, 0.022682, -0.596625, -0.087261],\n [2.433556, 0.021891, -0.598509, -0.086832]],\n [[2.416246, 0.017512, -0.610712, -0.082961],\n [2.422901, 0.024187, -0.606178, -0.074929]]]\n ).to(device)\n self.assertEqual(tuple(result.shape), tuple(ref_output.shape))\n torch.testing.assert_allclose(result, ref_output, rtol=1e-7, atol=1e-5)\n\n # all 0\n mask = torch.zeros([2, 5]).to(device) == 1\n result = model(encoder_input, src_key_padding_mask=mask)\n self.assertEqual(tuple(result.shape), tuple(ref_output.shape))\n torch.testing.assert_allclose(result, ref_output, rtol=1e-7, atol=1e-5)\n mask[0, 1] = 1\n mask[1, 3] = 1\n mask[1, 4] = 1\n result = model(encoder_input, src_key_padding_mask=mask)\n ref_output = torch.Tensor([[[2.429026, 0.020793, -0.601741, -0.085642],\n [2.428811, 0.021445, -0.601912, -0.084252]],\n [[2.425009, 0.019155, -0.604566, -0.085899],\n [2.415408, 0.02249, -0.611415, -0.073]],\n [[2.434199, 0.021682, -0.598039, -0.087699],\n [2.42598, 0.019941, -0.603896, -0.085091]],\n [[2.436457, 0.022736, -0.59643, -0.08736],\n [2.434021, 0.022093, -0.598179, -0.08679]],\n [[2.416531, 0.017498, -0.610513, -0.083181],\n [2.4242, 0.024653, -0.605266, -0.074959]]]\n ).to(device)\n self.assertEqual(tuple(result.shape), tuple(ref_output.shape))\n torch.testing.assert_allclose(result, ref_output, rtol=1e-7, atol=1e-5)\n\n # test case 2, multiple layers no norm\n model = nn.TransformerEncoder(encoder_layer, 2).to(device)\n result = model(encoder_input, src_key_padding_mask=mask)\n ref_output = torch.Tensor(\n [[[2.419051, 0.017446, -0.608738, -0.085003],\n [2.419102, 0.017452, -0.608703, -0.085026]],\n [[2.419043, 0.017445, -0.608744, -0.084999],\n [2.419052, 0.017446, -0.608738, -0.085004]],\n [[2.419067, 0.017448, -0.608727, -0.085010],\n [2.419098, 0.017452, -0.608706, -0.085024]],\n [[2.419072, 0.017449, -0.608724, -0.085012],\n [2.419119, 0.017455, -0.608691, -0.085034]],\n [[2.419019, 0.017442, -0.608761, -0.084989],\n [2.419075, 0.017449, -0.608722, -0.085014]]]\n ).to(device)\n self.assertEqual(tuple(result.shape), tuple(ref_output.shape))\n torch.testing.assert_allclose(result, ref_output, rtol=1e-7, atol=1e-5)\n\n model = nn.TransformerEncoder(encoder_layer, 6).to(device)\n result = model(encoder_input, src_key_padding_mask=mask)\n ref_output = torch.Tensor(\n [[[2.419101, 0.017453, -0.608703, -0.085025],\n [2.419101, 0.017453, -0.608704, -0.085025]],\n [[2.419101, 0.017453, -0.608703, -0.085025],\n [2.419101, 0.017453, -0.608704, -0.085025]],\n [[2.419101, 0.017453, -0.608703, -0.085025],\n [2.419101, 0.017453, -0.608704, -0.085025]],\n [[2.419101, 0.017453, -0.608703, -0.085025],\n [2.419101, 0.017453, -0.608704, -0.085025]],\n [[2.419101, 0.017453, -0.608703, -0.085025],\n [2.419101, 0.017453, -0.608704, -0.085025]]]\n ).to(device)\n self.assertEqual(tuple(result.shape), tuple(ref_output.shape))\n torch.testing.assert_allclose(result, ref_output, rtol=1e-7, atol=1e-5)\n\n # test case 3, multiple layers with norm\n # d_model = 4\n norm = nn.LayerNorm(4)\n model = nn.TransformerEncoder(encoder_layer, 2, norm=norm).to(device)\n result = model(encoder_input, src_key_padding_mask=mask)\n ref_output = torch.Tensor(\n [[[1.695949, -0.357635, -0.893077, -0.445238],\n [1.695955, -0.357639, -0.893050, -0.445266]],\n [[1.695948, -0.357634, -0.893082, -0.445233],\n [1.695950, -0.357635, -0.893077, -0.445238]],\n [[1.695951, -0.357636, -0.893069, -0.445246],\n [1.695955, -0.357639, -0.893052, -0.445264]],\n [[1.695952, -0.357636, -0.893066, -0.445249],\n [1.695957, -0.357641, -0.893041, -0.445276]],\n [[1.695946, -0.357632, -0.893095, -0.445220],\n [1.695952, -0.357637, -0.893065, -0.445251]]]\n ).to(device)\n self.assertEqual(tuple(result.shape), tuple(ref_output.shape))\n torch.testing.assert_allclose(result, ref_output, rtol=1e-7, atol=1e-5)\n\n model = nn.TransformerEncoder(encoder_layer, 6, norm=norm).to(device)\n result = model(encoder_input, src_key_padding_mask=mask)\n ref_output = torch.Tensor(\n [[[1.695955, -0.357639, -0.893051, -0.445265],\n [1.695955, -0.357639, -0.893051, -0.445265]],\n [[1.695955, -0.357639, -0.893051, -0.445265],\n [1.695955, -0.357639, -0.893051, -0.445265]],\n [[1.695955, -0.357639, -0.893051, -0.445265],\n [1.695955, -0.357639, -0.893051, -0.445265]],\n [[1.695955, -0.357639, -0.893051, -0.445265],\n [1.695955, -0.357639, -0.893051, -0.445265]],\n [[1.695955, -0.357639, -0.893051, -0.445265],\n [1.695955, -0.357639, -0.893051, -0.445265]]]\n ).to(device)\n self.assertEqual(tuple(result.shape), tuple(ref_output.shape))\n torch.testing.assert_allclose(result, ref_output, rtol=1e-7, atol=1e-5)\n\n\n def test_transformerdecoder(self):\n def get_a_test_layer(use_cuda, activation):\n d_model = 4\n nhead = 2\n dim_feedforward = 16\n dropout = 0.0\n device = torch.device(\"cuda\" if use_cuda else \"cpu\")\n\n layer = nn.TransformerDecoderLayer(\n d_model,\n nhead,\n dim_feedforward=dim_feedforward,\n dropout=dropout,\n activation=activation).to(device)\n\n with torch.no_grad():\n # set constant weights of the model\n for idx, p in enumerate(layer.parameters()):\n x = p.data\n sz = x.view(-1).size(0)\n shape = x.shape\n x = torch.cos(torch.arange(0, sz).float().view(shape))\n p.data.copy_(x)\n\n return layer\n\n # this is a deterministic test for TransformerDecoder\n activation = \"relu\"\n use_cuda = torch.cuda.is_available()\n device = torch.device(\"cuda\" if use_cuda else \"cpu\")\n\n decoder_layer = get_a_test_layer(use_cuda=use_cuda, activation=activation)\n\n model = nn.TransformerDecoder(decoder_layer, 1).to(device)\n\n # deterministic input\n decoder_input = torch.Tensor([[[20, 30, 40, 50]]]).to(device)\n memory_input = torch.Tensor([[[60, 70, 80, 90]]]).to(device)\n result = model(decoder_input, memory_input)\n ref_output = torch.Tensor(\n [[[2.314351, 0.094805, -0.671322, 0.101977]]]).to(device)\n self.assertEqual(tuple(result.shape), tuple(ref_output.shape))\n torch.testing.assert_allclose(result, ref_output, rtol=1e-7, atol=1e-5)\n\n # deterministic input\n decoder_input = torch.Tensor([[[9, 10, 11, 12]],\n [[11, 12, 13, 14]]]).to(device)\n memory_input = torch.Tensor([[[1, 2, 3, 4]]]).to(device)\n result = model(decoder_input, memory_input)\n ref_output = torch.Tensor(\n [[[2.422245, 0.051716, -0.606338, -0.024756]],\n [[2.422245, 0.051716, -0.606338, -0.024756]]]\n ).to(device)\n self.assertEqual(tuple(result.shape), tuple(ref_output.shape))\n torch.testing.assert_allclose(result, ref_output, rtol=1e-7, atol=1e-5)\n\n # deterministic input\n decoder_input = torch.Tensor([[[1, 2, 3, 4]],\n [[5, 6, 7, 8]]]).to(device)\n memory_input = torch.Tensor([[[9, 10, 11, 12]],\n [[11, 12, 13, 14]]]).to(device)\n result = model(decoder_input, memory_input)\n ref_output = torch.Tensor(\n [[[2.343536, 0.085561, -0.654954, 0.074991]],\n [[2.343536, 0.085561, -0.654954, 0.074991]]]\n ).to(device)\n self.assertEqual(tuple(result.shape), tuple(ref_output.shape))\n torch.testing.assert_allclose(result, ref_output, rtol=1e-7, atol=1e-5)\n\n # deterministic input\n decoder_input = torch.Tensor([[[0.4517, 0.6793, 0.5313, 0.0034],\n [0.2678, 0.3677, 0.4459, 0.7166]],\n [[0.8100, 0.3716, 0.4096, 0.1976],\n [0.6958, 0.8844, 0.6081, 0.8315]],\n [[0.0494, 0.9343, 0.5955, 0.3830],\n [0.5404, 0.3464, 0.9378, 0.6200]]]\n ).to(device)\n memory_input = torch.Tensor([[[0.7462, 0.6653, 0.5679, 0.4891],\n [0.5387, 0.1655, 0.3565, 0.0471]],\n [[0.8335, 0.2799, 0.5031, 0.2947],\n [0.1402, 0.0318, 0.7636, 0.1346]],\n [[0.6333, 0.9344, 0.1376, 0.9938],\n [0.8924, 0.2872, 0.6692, 0.2944]],\n [[0.9897, 0.6915, 0.3154, 0.1733],\n [0.8645, 0.3513, 0.3064, 0.0767]],\n [[0.8117, 0.2366, 0.4838, 0.7881],\n [0.3718, 0.4945, 0.9511, 0.0864]]]\n ).to(device)\n result = model(decoder_input, memory_input)\n ref_output = torch.Tensor([[[2.430065, 0.027862, -0.601136, -0.073096],\n [2.431935, 0.028907, -0.599809, -0.072488]],\n [[2.428457, 0.027053, -0.602275, -0.073462],\n [2.431970, 0.029387, -0.599789, -0.071621]],\n [[2.431934, 0.028196, -0.599802, -0.073809],\n [2.432306, 0.028858, -0.599542, -0.072846]]]\n ).to(device)\n self.assertEqual(tuple(result.shape), tuple(ref_output.shape))\n torch.testing.assert_allclose(result, ref_output, rtol=1e-7, atol=1e-5)\n\n # key_padding_mask\n key_padding_mask = torch.zeros(2, 3).to(device) == 1\n result = model(decoder_input,\n memory_input,\n tgt_key_padding_mask=key_padding_mask)\n ref_output = torch.Tensor([[[2.430065, 0.027862, -0.601136, -0.073096],\n [2.431935, 0.028907, -0.599809, -0.072488]],\n [[2.428457, 0.027053, -0.602275, -0.073462],\n [2.431970, 0.029387, -0.599789, -0.071621]],\n [[2.431934, 0.028196, -0.599802, -0.073809],\n [2.432306, 0.028858, -0.599542, -0.072846]]]\n ).to(device)\n self.assertEqual(tuple(result.shape), tuple(ref_output.shape))\n torch.testing.assert_allclose(result, ref_output, rtol=1e-7, atol=1e-5)\n\n # key_padding_mask\n key_padding_mask[0, 2] = 1\n key_padding_mask[1, 1] = 1\n key_padding_mask[1, 2] = 1\n result = model(decoder_input,\n memory_input,\n tgt_key_padding_mask=key_padding_mask)\n ref_output = torch.Tensor([[[2.430025, 0.027643, -0.601164, -0.073476],\n [2.4323, 0.029375, -0.599553, -0.071881]],\n [[2.428523, 0.026838, -0.602226, -0.07391],\n [2.432634, 0.029842, -0.599318, -0.071253]],\n [[2.432278, 0.028152, -0.599555, -0.074139],\n [2.432659, 0.029244, -0.599294, -0.072382]]]\n ).to(device)\n self.assertEqual(tuple(result.shape), tuple(ref_output.shape))\n torch.testing.assert_allclose(result, ref_output, rtol=1e-7, atol=1e-5)\n\n # memory_key_padding_mask\n key_padding_mask = torch.zeros(2, 5).to(device) == 1\n result = model(decoder_input,\n memory_input,\n memory_key_padding_mask=key_padding_mask)\n ref_output = torch.Tensor([[[2.430065, 0.027862, -0.601136, -0.073096],\n [2.431935, 0.028907, -0.599809, -0.072488]],\n [[2.428457, 0.027053, -0.602275, -0.073462],\n [2.431970, 0.029387, -0.599789, -0.071621]],\n [[2.431934, 0.028196, -0.599802, -0.073809],\n [2.432306, 0.028858, -0.599542, -0.072846]]]\n ).to(device)\n self.assertEqual(tuple(result.shape), tuple(ref_output.shape))\n torch.testing.assert_allclose(result, ref_output, rtol=1e-7, atol=1e-5)\n\n # memory_key_padding_mask\n key_padding_mask[0, 4] = 1\n key_padding_mask[1, 3] = 1\n key_padding_mask[1, 4] = 1\n result = model(decoder_input,\n memory_input,\n memory_key_padding_mask=key_padding_mask)\n ref_output = torch.Tensor([[[2.429757, 0.027358, -0.601351, -0.073816],\n [2.432692, 0.028583, -0.599263, -0.073634]],\n [[2.428247, 0.02662, -0.602419, -0.074123],\n [2.432657, 0.029055, -0.599293, -0.072732]],\n [[2.431515, 0.027687, -0.600096, -0.074459],\n [2.433075, 0.028543, -0.598987, -0.073985]]]\n ).to(device)\n self.assertEqual(tuple(result.shape), tuple(ref_output.shape))\n torch.testing.assert_allclose(result, ref_output, rtol=1e-7, atol=1e-5)\n\n # multiple layers no norm\n model = nn.TransformerDecoder(decoder_layer, 2).to(device)\n\n # deterministic input\n decoder_input = torch.Tensor([[[20, 30, 40, 50]]]).to(device)\n memory_input = torch.Tensor([[[60, 70, 80, 90]]]).to(device)\n result = model(decoder_input, memory_input)\n ref_output = torch.Tensor(\n [[[2.31316, 0.0950293, -0.671995, 0.102802]]]).to(device)\n self.assertEqual(tuple(result.shape), tuple(ref_output.shape))\n torch.testing.assert_allclose(result, ref_output, rtol=1e-7, atol=1e-5)\n\n # multiple layers no norm\n model = nn.TransformerDecoder(decoder_layer, 6).to(device)\n\n # deterministic input\n decoder_input = torch.Tensor([[[0.4517, 0.6793, 0.5313, 0.0034],\n [0.2678, 0.3677, 0.4459, 0.7166]],\n [[0.8100, 0.3716, 0.4096, 0.1976],\n [0.6958, 0.8844, 0.6081, 0.8315]],\n [[0.0494, 0.9343, 0.5955, 0.3830],\n [0.5404, 0.3464, 0.9378, 0.6200]]]\n ).to(device)\n memory_input = torch.Tensor([[[0.7462, 0.6653, 0.5679, 0.4891],\n [0.5387, 0.1655, 0.3565, 0.0471]],\n [[0.8335, 0.2799, 0.5031, 0.2947],\n [0.1402, 0.0318, 0.7636, 0.1346]],\n [[0.6333, 0.9344, 0.1376, 0.9938],\n [0.8924, 0.2872, 0.6692, 0.2944]],\n [[0.9897, 0.6915, 0.3154, 0.1733],\n [0.8645, 0.3513, 0.3064, 0.0767]],\n [[0.8117, 0.2366, 0.4838, 0.7881],\n [0.3718, 0.4945, 0.9511, 0.0864]]]\n ).to(device)\n result = model(decoder_input, memory_input)\n ref_output = torch.Tensor(\n [[[2.42794, 0.026164, -0.60263, -0.0747591],\n [2.43113, 0.0279516, -0.600376, -0.0736896]],\n [[2.42794, 0.026164, -0.60263, -0.0747591],\n [2.43113, 0.0279516, -0.600376, -0.0736896]],\n [[2.42794, 0.026164, -0.60263, -0.0747591],\n [2.43113, 0.0279516, -0.600376, -0.0736896]]]\n ).to(device)\n self.assertEqual(tuple(result.shape), tuple(ref_output.shape))\n torch.testing.assert_allclose(result, ref_output, rtol=1e-7, atol=1e-5)\n\n # multiple layers with norm\n # d_model = 4\n norm = nn.LayerNorm(4)\n model = nn.TransformerDecoder(decoder_layer, 2, norm=norm).to(device)\n\n # deterministic input\n decoder_input = torch.Tensor([[[20, 30, 40, 50]]]).to(device)\n memory_input = torch.Tensor([[[60, 70, 80, 90]]]).to(device)\n result = model(decoder_input, memory_input)\n ref_output = torch.Tensor(\n [[[1.66166, -0.326986, -1.01466, -0.320017]]]).to(device)\n self.assertEqual(tuple(result.shape), tuple(ref_output.shape))\n torch.testing.assert_allclose(result, ref_output, rtol=1e-7, atol=1e-5)\n\n # multiple layers with norm\n model = nn.TransformerDecoder(decoder_layer, 6, norm=norm).to(device)\n\n # deterministic input\n decoder_input = torch.Tensor([[[0.4517, 0.6793, 0.5313, 0.0034],\n [0.2678, 0.3677, 0.4459, 0.7166]],\n [[0.8100, 0.3716, 0.4096, 0.1976],\n [0.6958, 0.8844, 0.6081, 0.8315]],\n [[0.0494, 0.9343, 0.5955, 0.3830],\n [0.5404, 0.3464, 0.9378, 0.6200]]]\n ).to(device)\n memory_input = torch.Tensor([[[0.7462, 0.6653, 0.5679, 0.4891],\n [0.5387, 0.1655, 0.3565, 0.0471]],\n [[0.8335, 0.2799, 0.5031, 0.2947],\n [0.1402, 0.0318, 0.7636, 0.1346]],\n [[0.6333, 0.9344, 0.1376, 0.9938],\n [0.8924, 0.2872, 0.6692, 0.2944]],\n [[0.9897, 0.6915, 0.3154, 0.1733],\n [0.8645, 0.3513, 0.3064, 0.0767]],\n [[0.8117, 0.2366, 0.4838, 0.7881],\n [0.3718, 0.4945, 0.9511, 0.0864]]]\n ).to(device)\n result = model(decoder_input, memory_input)\n ref_output = torch.Tensor(\n [[[1.69559, -0.357291, -0.894741, -0.443553],\n [1.69571, -0.357363, -0.894154, -0.444196]],\n [[1.69559, -0.357291, -0.894741, -0.443553],\n [1.69571, -0.357363, -0.894154, -0.444196]],\n [[1.69559, -0.357291, -0.894741, -0.443553],\n [1.69571, -0.357363, -0.894154, -0.444196]]]\n ).to(device)\n self.assertEqual(tuple(result.shape), tuple(ref_output.shape))\n torch.testing.assert_allclose(result, ref_output, rtol=1e-7, atol=1e-5)\n\n # gelu activation test cases\n activation = \"gelu\"\n use_cuda = torch.cuda.is_available()\n device = torch.device(\"cuda\" if use_cuda else \"cpu\")\n\n decoder_layer = get_a_test_layer(use_cuda=use_cuda, activation=activation)\n\n model = nn.TransformerDecoder(decoder_layer, 1).to(device)\n\n # deterministic input\n decoder_input = torch.Tensor([[[20, 30, 40, 50]]]).to(device)\n memory_input = torch.Tensor([[[60, 70, 80, 90]]]).to(device)\n result = model(decoder_input, memory_input)\n ref_output = torch.Tensor([[[2.306435, 0.095946, -0.675796, 0.10687]]]\n ).to(device)\n self.assertEqual(tuple(result.shape), tuple(ref_output.shape))\n torch.testing.assert_allclose(result, ref_output)\n\n # deterministic input\n decoder_input = torch.Tensor([[[9, 10, 11, 12]],\n [[11, 12, 13, 14]]]).to(device)\n memory_input = torch.Tensor([[[1, 2, 3, 4]]]).to(device)\n result = model(decoder_input, memory_input)\n ref_output = torch.Tensor(\n [[[2.415448, 0.054389, -0.610932, -0.0156613]],\n [[2.415448, 0.054389, -0.610932, -0.0156613]]]).to(device)\n self.assertEqual(tuple(result.shape), tuple(ref_output.shape))\n torch.testing.assert_allclose(result, ref_output)\n\n # deterministic input\n decoder_input = torch.Tensor([[[1, 2, 3, 4]],\n [[5, 6, 7, 8]]]).to(device)\n memory_input = torch.Tensor([[[9, 10, 11, 12]],\n [[11, 12, 13, 14]]]).to(device)\n result = model(decoder_input, memory_input)\n ref_output = torch.Tensor(\n [[[2.338531, 0.087709, -0.65776, 0.080646]],\n [[2.338531, 0.087709, -0.65776, 0.080646]]]).to(device)\n self.assertEqual(tuple(result.shape), tuple(ref_output.shape))\n torch.testing.assert_allclose(result, ref_output)\n\n # deterministic input\n decoder_input = torch.Tensor([[[0.4517, 0.6793, 0.5313, 0.0034],\n [0.2678, 0.3677, 0.4459, 0.7166]],\n [[0.8100, 0.3716, 0.4096, 0.1976],\n [0.6958, 0.8844, 0.6081, 0.8315]],\n [[0.0494, 0.9343, 0.5955, 0.3830],\n [0.5404, 0.3464, 0.9378, 0.6200]]]\n ).to(device)\n memory_input = torch.Tensor([[[0.7462, 0.6653, 0.5679, 0.4891],\n [0.5387, 0.1655, 0.3565, 0.0471]],\n [[0.8335, 0.2799, 0.5031, 0.2947],\n [0.1402, 0.0318, 0.7636, 0.1346]],\n [[0.6333, 0.9344, 0.1376, 0.9938],\n [0.8924, 0.2872, 0.6692, 0.2944]],\n [[0.9897, 0.6915, 0.3154, 0.1733],\n [0.8645, 0.3513, 0.3064, 0.0767]],\n [[0.8117, 0.2366, 0.4838, 0.7881],\n [0.3718, 0.4945, 0.9511, 0.0864]]]\n ).to(device)\n result = model(decoder_input, memory_input)\n ref_output = torch.Tensor(\n [[[2.42049104, 0.03443088, -0.60793706, -0.05436271],\n [2.42210631, 0.03546578, -0.60679895, -0.05357488]],\n [[2.41907674, 0.0336104, -0.60892977, -0.05490462],\n [2.42216881, 0.03586554, -0.6067524, -0.05289126]],\n [[2.42205716, 0.03488046, -0.60683681, -0.05460596],\n [2.42240309, 0.0354595, -0.60659063, -0.05378816]]]).to(device)\n self.assertEqual(tuple(result.shape), tuple(ref_output.shape))\n torch.testing.assert_allclose(result, ref_output)\n\n\n @unittest.skipIf(not (TEST_CUDNN and TEST_MULTIGPU), 'CUDNN or multi-gpu not available')\n def test_cudnn_rnn_dropout_states_device(self):\n rnn = nn.RNN(10, 20, num_layers=2, dropout=.5)\n device = 1\n input = torch.randn(5, 4, 10).cuda(device)\n rnn.cuda(device)\n hx = torch.randn(2, 4, 20).cuda(device)\n output = rnn(input, hx)\n\n @unittest.skipIf(not TEST_CUDNN, 'CUDNN not available')\n @skipIfRocm\n def test_cudnn_weight_format(self):\n rnns = [\n nn.LSTM(10, 20, batch_first=True),\n nn.LSTM(10, 20, batch_first=True, proj_size=10),\n nn.GRU(10, 20, batch_first=True),\n nn.RNN(10, 20, batch_first=True)\n ]\n first_warn = True\n for rnn in rnns:\n rnn.cuda()\n input = torch.randn(5, 4, 10, requires_grad=True, device=\"cuda\")\n hx = torch.randn(1, 5, 20, requires_grad=True, device=\"cuda\")\n all_vars = [input, hx] + list(rnn.parameters())\n if isinstance(rnn, nn.LSTM):\n # LSTM with projections has different hx size\n if rnn.proj_size > 0:\n hx = torch.randn(1, 5, 10, requires_grad=True, device=\"cuda\")\n all_vars[1] = hx\n cx = torch.randn(1, 5, 20, requires_grad=True, device=\"cuda\")\n all_vars[2:2] = [cx]\n hx = (hx, cx)\n\n output = rnn(input, hx)\n output[0].sum().backward()\n grads = [v.grad.data.clone() for v in all_vars]\n for v in all_vars:\n v.grad.data.zero_()\n\n # Weights will no longer view onto the same chunk of memory\n weight = all_vars[4]\n weight_data = weight.data.clone()\n with torch.no_grad():\n weight.set_(weight_data)\n\n for _ in range(2):\n with warnings.catch_warnings(record=True) as w:\n output_noncontig = rnn(input, hx)\n if first_warn:\n self.assertEqual(len(w), 1)\n self.assertIn('weights are not part of single contiguous chunk of memory', w[0].message.args[0])\n first_warn = False\n warnings.resetwarnings()\n output_noncontig[0].sum().backward()\n grads_noncontig = [v.grad.data.clone() for v in all_vars]\n for v in all_vars:\n v.grad.data.zero_()\n self.assertEqual(output, output_noncontig)\n self.assertEqual(grads_noncontig, grads)\n\n # Make sure these still share storage\n weight_data[:] = 4\n self.assertEqual(weight_data, all_vars[4].data)\n\n @unittest.skipIf(not TEST_CUDNN, 'CUDNN not available')\n def test_cudnn_weight_tying(self):\n rnns = [\n nn.LSTM(10, 20, batch_first=True, bidirectional=True),\n nn.LSTM(10, 20, batch_first=True, bidirectional=True, proj_size=10),\n nn.GRU(10, 20, batch_first=True, bidirectional=True),\n nn.RNN(10, 20, batch_first=True, bidirectional=True)\n ]\n for rnn in rnns:\n rnn.bias_ih_l0_reverse = rnn.bias_ih_l0\n rnn.cuda()\n input = torch.randn(5, 4, 10, requires_grad=True, device=\"cuda\")\n hx = torch.randn(2, 5, 20, requires_grad=True, device=\"cuda\")\n all_vars = [input, hx] + list(rnn.parameters())\n opt = torch.optim.SGD(rnn.parameters(), lr=0.1)\n opt.zero_grad()\n if isinstance(rnn, nn.LSTM):\n # LSTM with projections has different hx size\n if rnn.proj_size > 0:\n hx = torch.randn(2, 5, 10, requires_grad=True, device=\"cuda\")\n all_vars[1] = hx\n cx = torch.randn(2, 5, 20, requires_grad=True, device=\"cuda\")\n all_vars[2:2] = [cx]\n hx = (hx, cx)\n\n with warnings.catch_warnings(record=True) as w:\n output = rnn(input, hx)\n output[0].sum().backward()\n\n opt.step()\n with warnings.catch_warnings(record=True) as w:\n output_cuda = rnn(input, hx)\n rnn.cpu()\n hx = (hx[0].cpu(), hx[1].cpu()) if isinstance(rnn, nn.LSTM) else hx.cpu()\n output_cpu = rnn(input.cpu(), hx)\n self.assertEqual(output_cuda, output_cpu)\n\n def test_transformer_args_check(self):\n model_name = 'Transformer'\n d_model = 128\n nhead = 4\n num_encoder_layers = 2\n num_decoder_layers = 3\n dim_feedforward = 65\n dropout = 0.3\n bsz = 3\n seq_len = 35\n tgt_len = 15\n activations = [\"relu\", \"gelu\"]\n\n wrong_bsz = 7\n wrong_d_model = 63\n wrong_nhead = 5\n wrong_activation = \"abc\"\n\n def test(encoder_input_shape, decoder_input_shape,\n src_mask_len=None, tgt_mask_len=None, memory_mask_size=None,\n src_key_padding_mask_size=None, tgt_key_padding_mask_size=None,\n memory_key_padding_mask_size=None):\n encoder_input = torch.randn(encoder_input_shape)\n decoder_input = torch.randn(decoder_input_shape)\n model = getattr(nn, model_name)(d_model, nhead, num_encoder_layers,\n num_decoder_layers, dim_feedforward, dropout)\n\n if src_mask_len is not None:\n src_mask = model.generate_square_subsequent_mask(src_mask_len)\n else:\n src_mask = None\n\n if tgt_mask_len is not None:\n tgt_mask = model.generate_square_subsequent_mask(tgt_mask_len)\n else:\n tgt_mask = None\n\n if memory_mask_size is not None:\n memory_task = torch.rand(memory_mask_size)\n else:\n memory_task = None\n\n if src_key_padding_mask_size is not None:\n src_key_padding_mask = torch.rand(src_key_padding_mask_size) >= 0.5\n else:\n src_key_padding_mask = None\n\n if tgt_key_padding_mask_size is not None:\n tgt_key_padding_mask = torch.rand(tgt_key_padding_mask_size) >= 0.5\n else:\n tgt_key_padding_mask = None\n\n if memory_key_padding_mask_size is not None:\n memory_key_padding_mask = torch.rand(memory_key_padding_mask_size) >= 0.5\n else:\n memory_key_padding_mask = None\n\n with self.assertRaises(RuntimeError):\n model(encoder_input, decoder_input,\n src_mask=src_mask,\n tgt_mask=tgt_mask,\n memory_mask=memory_task,\n src_key_padding_mask=src_key_padding_mask,\n tgt_key_padding_mask=tgt_key_padding_mask,\n memory_key_padding_mask=memory_key_padding_mask)\n\n\n correct_encoder_input_shape = (seq_len, bsz, d_model)\n correct_decoder_input_shape = (tgt_len, bsz, d_model)\n\n def update_shape(shape, dim, new_dim_size):\n new_shape = list(shape)\n new_shape[dim] = new_dim_size\n return tuple(new_shape)\n\n # Incorrect encoder_input batch size\n encoder_input_shape = update_shape(correct_encoder_input_shape, 1, wrong_bsz)\n decoder_input_shape = correct_decoder_input_shape\n test(encoder_input_shape, decoder_input_shape)\n\n # Incorrect decoder_input batch size\n encoder_input_shape = correct_encoder_input_shape\n decoder_input_shape = update_shape(correct_decoder_input_shape, 1, wrong_bsz)\n test(encoder_input_shape, decoder_input_shape)\n\n # Incorrect encoder_input input size\n encoder_input_shape = update_shape(correct_encoder_input_shape, 2, wrong_d_model)\n decoder_input_shape = correct_decoder_input_shape\n test(encoder_input_shape, decoder_input_shape)\n\n # Incorrect decoder_input input size\n encoder_input_shape = correct_encoder_input_shape\n decoder_input_shape = update_shape(correct_decoder_input_shape, 2, wrong_d_model)\n test(encoder_input_shape, decoder_input_shape)\n\n # Incorrect nhead\n encoder_input_shape = correct_encoder_input_shape\n decoder_input_shape = correct_decoder_input_shape\n with self.assertRaises(AssertionError):\n model = getattr(nn, model_name)(d_model, wrong_nhead, num_encoder_layers,\n num_decoder_layers, dim_feedforward, dropout)\n\n # Incorrect src_mask\n encoder_input_shape = correct_encoder_input_shape\n decoder_input_shape = correct_decoder_input_shape\n wrong_src_mask_size = seq_len + 1\n test(encoder_input_shape, decoder_input_shape, src_mask_len=wrong_src_mask_size)\n\n # Incorrect tgt_mask\n encoder_input_shape = correct_encoder_input_shape\n decoder_input_shape = correct_decoder_input_shape\n wrong_tgt_mask_size = tgt_len + 1\n test(encoder_input_shape, decoder_input_shape, tgt_mask_len=wrong_tgt_mask_size)\n\n # Incorrect memory_mask\n encoder_input_shape = correct_encoder_input_shape\n decoder_input_shape = correct_decoder_input_shape\n wrong_tgt_mask_size = tgt_len + 1\n test(encoder_input_shape, decoder_input_shape,\n memory_mask_size=(wrong_tgt_mask_size, wrong_src_mask_size))\n\n # Incorrect src_key_padding_mask\n encoder_input_shape = correct_encoder_input_shape\n decoder_input_shape = correct_decoder_input_shape\n with self.assertRaises(AssertionError):\n test(encoder_input_shape, decoder_input_shape,\n src_key_padding_mask_size=(wrong_bsz, wrong_src_mask_size))\n\n # Incorrect tgt_key_padding_mask\n encoder_input_shape = correct_encoder_input_shape\n decoder_input_shape = correct_decoder_input_shape\n with self.assertRaises(AssertionError):\n test(encoder_input_shape, decoder_input_shape,\n tgt_key_padding_mask_size=(wrong_bsz, wrong_tgt_mask_size))\n\n # Incorrect memory_key_padding_mask\n encoder_input_shape = correct_encoder_input_shape\n decoder_input_shape = correct_decoder_input_shape\n with self.assertRaises(AssertionError):\n test(encoder_input_shape, decoder_input_shape,\n memory_key_padding_mask_size=(wrong_bsz, wrong_src_mask_size))\n\n # Correct activations\n for activation in activations:\n model = getattr(nn, model_name)(d_model, nhead, num_encoder_layers, num_decoder_layers,\n dim_feedforward, dropout, activation)\n # Incorrect activation\n with self.assertRaises(RuntimeError):\n model = getattr(nn, model_name)(d_model, nhead, num_encoder_layers, num_decoder_layers,\n dim_feedforward, dropout, wrong_activation)\n\n def test_transformer_layer_args_check(self):\n model_names = ['TransformerEncoderLayer', 'TransformerDecoderLayer']\n d_model = 128\n nhead = 4\n dim_feedforward = 65\n dropout = 0.3\n bsz = 3\n seq_len = 35\n tgt_len = 15\n activations = [\"relu\", \"gelu\"]\n\n wrong_activation = \"abc\"\n\n encoder_input_shape = (seq_len, bsz, d_model)\n decoder_input_shape = (tgt_len, bsz, d_model)\n\n encoder_input = torch.randn(encoder_input_shape)\n decoder_input = torch.randn(decoder_input_shape)\n\n for model_name in model_names:\n for activation in activations:\n model = getattr(nn, model_name)(d_model, nhead, dim_feedforward,\n dropout, activation)\n # Incorrect activation\n for model_name in model_names:\n with self.assertRaises(RuntimeError):\n model = getattr(nn, model_name)(d_model, nhead, dim_feedforward,\n dropout, wrong_activation)\n\n def test_rnn_args_check(self):\n input_size = 3\n hidden_size = 5\n num_layers = 2\n batch_size = 4\n seq_len = 6\n num_directions = 1\n bad_size = 7 # prime number so that no size can divide it.\n\n def test(input_shape, hidden_shape, mode):\n for input, hidden in get_inputs(input_shape, hidden_shape, mode):\n model = getattr(nn, mode)(input_size, hidden_size, num_layers)\n self.assertRaises(RuntimeError, lambda: model(input, hidden))\n\n correct_input_shape = (seq_len, batch_size, input_size)\n correct_hidden_shape = (num_layers * num_directions, batch_size, hidden_size)\n\n def update_shape(shape, dim, new_dim_size):\n new_shape = list(shape)\n new_shape[dim] = new_dim_size\n return tuple(new_shape)\n\n def get_inputs(input_shape, hidden_shape, mode):\n '''returns list( tuple(input, hidden) )\n where input, hidden are inputs to a model'''\n input = torch.randn(input_shape)\n hidden = torch.randn(hidden_shape)\n if mode != 'LSTM':\n return [(input, hidden)]\n if hidden_shape == correct_hidden_shape:\n return [(input, (hidden, hidden))]\n good_hidden = torch.randn(correct_hidden_shape)\n return [\n (input, (hidden, good_hidden)),\n (input, (good_hidden, hidden)),\n ]\n\n rnn_modes = ['RNN', 'GRU', 'LSTM']\n for mode in rnn_modes:\n # Incorrect input batch size\n input_shape = update_shape(correct_input_shape, 1, bad_size)\n hidden_shape = correct_hidden_shape\n test(input_shape, hidden_shape, mode)\n\n # Incorrect hidden batch size\n input_shape = correct_input_shape\n hidden_shape = update_shape(correct_hidden_shape, 1, bad_size)\n test(input_shape, hidden_shape, mode)\n\n # Incorrect input size\n input_shape = update_shape(correct_input_shape, 2, bad_size)\n hidden_shape = correct_hidden_shape\n test(input_shape, hidden_shape, mode)\n\n # Incorrect hidden size\n input_shape = correct_input_shape\n hidden_shape = update_shape(correct_hidden_shape, 2, bad_size)\n test(input_shape, hidden_shape, mode)\n\n # Incorrect hidden[0]\n input_shape = correct_input_shape\n hidden_shape = update_shape(correct_hidden_shape, 0, bad_size)\n test(input_shape, hidden_shape, mode)\n\n def test_projections_lstm_args_check(self):\n input_size = 3\n hidden_size = 5\n proj_size = 2\n num_layers = 2\n batch_size = 4\n seq_len = 6\n num_directions = 1\n bad_size = 7 # prime number so that no size can divide it.\n\n def test(input_shape, hidden_h_shape, hidden_c_shape):\n for input, hidden in get_inputs(input_shape, hidden_h_shape, hidden_c_shape):\n model = nn.LSTM(input_size, hidden_size, num_layers, proj_size=proj_size)\n self.assertRaises(RuntimeError, lambda: model(input, hidden))\n\n correct_input_shape = (seq_len, batch_size, input_size)\n correct_hidden_h_shape = (num_layers * num_directions, batch_size, proj_size)\n correct_hidden_c_shape = (num_layers * num_directions, batch_size, hidden_size)\n\n def update_shape(shape, dim, new_dim_size):\n new_shape = list(shape)\n new_shape[dim] = new_dim_size\n return tuple(new_shape)\n\n def get_inputs(input_shape, hidden_h_shape, hidden_c_shape):\n '''returns list( tuple(input, hidden) )\n where input, hidden are inputs to a model'''\n input = torch.randn(input_shape)\n hidden_h = torch.randn(hidden_h_shape)\n hidden_c = torch.randn(hidden_c_shape)\n return [(input, (hidden_h, hidden_c))]\n\n # Incorrect input batch size\n input_shape = update_shape(correct_input_shape, 1, bad_size)\n test(input_shape, correct_hidden_h_shape, correct_hidden_c_shape)\n\n # Incorrect hidden batch size\n input_shape = correct_input_shape\n hidden_h_shape = update_shape(correct_hidden_h_shape, 1, bad_size)\n hidden_c_shape = update_shape(correct_hidden_c_shape, 1, bad_size)\n test(input_shape, hidden_h_shape, hidden_c_shape)\n\n # Incorrect input size\n input_shape = update_shape(correct_input_shape, 2, bad_size)\n test(input_shape, correct_hidden_h_shape, correct_hidden_c_shape)\n\n # Incorrect hidden size\n input_shape = correct_input_shape\n hidden_h_shape = update_shape(correct_hidden_h_shape, 2, bad_size)\n hidden_c_shape = update_shape(correct_hidden_c_shape, 2, bad_size)\n test(input_shape, hidden_h_shape, hidden_c_shape)\n\n # Incorrect hidden[0]\n input_shape = correct_input_shape\n hidden_h_shape = update_shape(correct_hidden_h_shape, 0, bad_size)\n hidden_c_shape = update_shape(correct_hidden_c_shape, 0, bad_size)\n test(input_shape, hidden_h_shape, hidden_c_shape)\n\n # Incorrect proj size = hidden size\n input_shape = correct_input_shape\n hidden_h_shape = update_shape(correct_hidden_h_shape, 0, hidden_size)\n hidden_c_shape = correct_hidden_c_shape\n test(input_shape, hidden_h_shape, hidden_c_shape)\n\n # Incorrect proj size != hidden size\n input_shape = correct_input_shape\n hidden_h_shape = update_shape(correct_hidden_h_shape, 0, bad_size)\n hidden_c_shape = correct_hidden_c_shape\n test(input_shape, hidden_h_shape, hidden_c_shape)\n\n # Incorrect cell size != hidden size\n input_shape = correct_input_shape\n hidden_h_shape = correct_hidden_h_shape\n hidden_c_shape = update_shape(correct_hidden_c_shape, 0, bad_size)\n test(input_shape, hidden_h_shape, hidden_c_shape)\n\n @unittest.skipIf(not TEST_MULTIGPU, \"multi-GPU not supported\")\n def test_rnn_check_device(self):\n input_size = 3\n hidden_size = 5\n num_layers = 2\n batch_size = 4\n seq_len = 6\n num_directions = 1\n\n correct_input_shape = (seq_len, batch_size, input_size)\n correct_hidden_shape = (num_layers * num_directions, batch_size, hidden_size)\n rnn_modes = ['RNN', 'GRU', 'LSTM']\n\n for mode in rnn_modes:\n model = getattr(nn, mode)(input_size, hidden_size, num_layers)\n input = torch.randn(correct_input_shape)\n hidden = torch.randn(correct_hidden_shape)\n\n # input and weights are not at the same device\n with self.assertRaisesRegex(RuntimeError,\n \"Input and parameter tensors are not at the same device\"):\n model(input.to('cuda:0'))\n\n # input and hiddens are not at the same device\n with self.assertRaisesRegex(RuntimeError,\n r\"Input and hidden tensors are not at the same device\"):\n if mode == 'LSTM':\n model(input, (hidden.to('cuda:0'), hidden.to('cuda:0')))\n else:\n model(input, (hidden.to('cuda:0')))\n\n # hidden tensors are not at the same CUDA device\n if mode == 'LSTM':\n with self.assertRaisesRegex(RuntimeError,\n \"Input and hidden tensors are not at the same device\"):\n model(input.to('cuda:0'), (hidden.to('cuda:0'), hidden.to('cuda:1')))\n\n @unittest.skipIf(not TEST_MULTIGPU, \"multi-GPU not supported\")\n def test_projections_lstm_check_device(self):\n input_size = 3\n hidden_size = 5\n proj_size = 2\n num_layers = 2\n batch_size = 4\n seq_len = 6\n num_directions = 1\n\n correct_input_shape = (seq_len, batch_size, input_size)\n correct_hidden_h_shape = (num_layers * num_directions, batch_size, proj_size)\n correct_hidden_c_shape = (num_layers * num_directions, batch_size, hidden_size)\n\n model = nn.LSTM(input_size, hidden_size, num_layers, proj_size=proj_size)\n input = torch.randn(correct_input_shape)\n hidden_h = torch.randn(correct_hidden_h_shape)\n hidden_c = torch.randn(correct_hidden_c_shape)\n\n # input and weights are not at the same device\n with self.assertRaisesRegex(RuntimeError,\n \"Input and parameter tensors are not at the same device\"):\n model(input.to('cuda:0'))\n\n # input and hiddens are not at the same device\n with self.assertRaisesRegex(RuntimeError,\n r\"Input and hidden tensors are not at the same device\"):\n model(input, (hidden_h.to('cuda:0'), hidden_c.to('cuda:0')))\n\n # hidden tensors are not at the same CUDA device\n with self.assertRaisesRegex(RuntimeError,\n \"Input and hidden tensors are not at the same device\"):\n model(input.to('cuda:0'), (hidden_h.to('cuda:0'), hidden_c.to('cuda:1')))\n\n def test_rnn_initial_hidden_state(self):\n rnn_modes = ['RNN', 'GRU', 'LSTM']\n for mode in rnn_modes:\n rnn = getattr(nn, mode)(30, 20, 2)\n input = torch.randn(10, 32, 30)\n hidden = torch.zeros(2, 32, 20)\n\n if mode == 'LSTM':\n hidden = (hidden, hidden)\n output1, hidden1 = rnn(input, hidden)\n output2, hidden2 = rnn(input)\n self.assertEqual(output1, output2)\n self.assertEqual(hidden1, hidden2)\n\n def test_projections_lstm_initial_hidden_state(self):\n for bidir in [False, True]:\n rnn = nn.LSTM(30, 20, 2, bidirectional=bidir, proj_size=10)\n num_dirs = 2 if bidir else 1\n input = torch.randn(10, 32, 30)\n hidden_h = torch.zeros(2 * num_dirs, 32, 10)\n hidden_c = torch.zeros(2 * num_dirs, 32, 20)\n hidden = (hidden_h, hidden_c)\n output1, hidden1 = rnn(input, hidden)\n output2, hidden2 = rnn(input)\n self.assertEqual(output1, output2)\n self.assertEqual(hidden1, hidden2)\n\n def test_projections_errors_on_gru_and_rnn(self):\n error_msg = \"proj_size argument is only supported for LSTM, not RNN or GRU\"\n for mode in ['RNN', 'GRU']:\n with self.assertRaisesRegex(ValueError, error_msg):\n rnn = getattr(nn, mode)(30, 20, 2, proj_size=10)\n\n def _test_RNN_cpu_vs_cudnn(self, dropout, dtype=torch.double):\n\n def forward_backward(cuda, rnn, input_val, grad_output, weights_val, hx_val, grad_hy,\n cx_val=None, grad_cy=None):\n is_lstm = isinstance(rnn, nn.LSTM)\n\n for x_layer, y_layer in zip(rnn.all_weights, weights_val):\n for x, y in zip(x_layer, y_layer):\n x.data.copy_(y.data)\n\n if isinstance(input_val, rnn_utils.PackedSequence):\n input = rnn_utils.PackedSequence(\n input_val.data.data.requires_grad_(True), input_val.batch_sizes)\n input_var = input.data\n else:\n input = input_val.clone().requires_grad_(True)\n input_var = input\n if is_lstm:\n if cx_val is None:\n hx = (hx_val.clone().requires_grad_(True),\n hx_val.add(1).requires_grad_(True))\n else:\n hx = (hx_val.clone().requires_grad_(True),\n cx_val.add(1).requires_grad_(True))\n else:\n hx = hx_val.clone().requires_grad_(True)\n\n if cuda:\n rnn.cuda()\n input_var.data = input_var.data.cuda()\n if is_lstm:\n hx[0].data = hx[0].data.cuda()\n hx[1].data = hx[1].data.cuda()\n else:\n hx.data = hx.data.cuda()\n grad_hy = grad_hy.cuda()\n if grad_cy is not None:\n grad_cy = grad_cy.cuda()\n grad_output = grad_output.cuda()\n\n output, hy = rnn(input, hx)\n\n if isinstance(output, rnn_utils.PackedSequence):\n output = output.data\n\n if is_lstm:\n if grad_cy is None:\n torch.autograd.backward([output, hy[0], hy[1]], [grad_output, grad_hy, grad_hy + 1])\n else:\n torch.autograd.backward([output, hy[0], hy[1]], [grad_output, grad_hy, grad_cy + 1])\n else:\n torch.autograd.backward([output, hy], [grad_output, grad_hy])\n\n return {'output': output.data,\n 'hy': hy[0].data if is_lstm else hy.data,\n 'weights': rnn.all_weights,\n 'grad_input': input_var.grad.data,\n 'grad_hx': hx[0].grad.data if is_lstm else hx.grad.data,\n 'cy': hy[1].data if is_lstm else None,\n 'grad_cx': hx[1].grad.data if is_lstm else None}\n\n input_size = 10\n hidden_size = 6\n proj_size = 3\n num_layers = 2\n seq_length = 7\n batch = 6\n\n def make_noncontig(tensor):\n ndim = tensor.dim()\n return torch.stack([tensor.clone().zero_(), tensor], ndim).select(ndim, 1)\n\n def compare_cpu_gpu(outputs_cpu, outputs_gpu):\n self.assertEqual(list(outputs_cpu.keys()), list(outputs_gpu.keys()))\n for key in outputs_cpu.keys():\n if key != 'weights':\n self.assertEqual(outputs_cpu[key], outputs_gpu[key], atol=5e-5, rtol=0, msg=key)\n\n # check grad weights separately, as nested dict\n for cpu_layer_weight, gpu_layer_weight in zip(outputs_cpu['weights'], outputs_gpu['weights']):\n for (cpu_weight, gpu_weight) in zip(cpu_layer_weight, gpu_layer_weight):\n self.assertEqual(cpu_weight.grad.data, gpu_weight.grad.data, atol=5e-5, rtol=0)\n\n for module in (nn.RNN, nn.LSTM, nn.GRU):\n for bias, bidirectional, batch_first, contig, variable_len, lens_as_tensor \\\n in product((True, False), repeat=6):\n\n num_directions = 2 if bidirectional else 1\n if batch_first:\n input_val = torch.randn(batch, seq_length, input_size, dtype=dtype)\n grad_output = torch.randn(batch, seq_length, hidden_size * num_directions, dtype=dtype)\n else:\n input_val = torch.randn(seq_length, batch, input_size, dtype=dtype)\n grad_output = torch.randn(seq_length, batch, hidden_size * num_directions, dtype=dtype)\n\n hx_val = torch.randn(num_layers * num_directions, batch, hidden_size, dtype=dtype)\n grad_hy = torch.randn(num_layers * num_directions, batch, hidden_size, dtype=dtype)\n\n if not contig:\n grad_output = make_noncontig(grad_output)\n grad_hy = make_noncontig(grad_hy)\n input_var = make_noncontig(input_val)\n hx_val = make_noncontig(hx_val)\n\n if variable_len:\n lengths = [7, 5, 5, 2, 1, 1]\n if lens_as_tensor:\n lengths = torch.tensor(lengths, dtype=torch.long)\n input_val = rnn_utils.pack_padded_sequence(input_val, lengths, batch_first=batch_first)\n grad_output = rnn_utils.pack_padded_sequence(grad_output, lengths, batch_first=batch_first).data\n\n rnn = module(input_size,\n hidden_size,\n num_layers,\n bias=bias,\n dropout=dropout,\n bidirectional=bidirectional,\n batch_first=batch_first).to(dtype)\n\n outputs_cpu = forward_backward(\n False, rnn, input_val, grad_output, rnn.all_weights, hx_val, grad_hy)\n\n rnn_gpu = module(input_size,\n hidden_size,\n num_layers,\n bias=bias,\n dropout=dropout,\n bidirectional=bidirectional,\n batch_first=batch_first).to(dtype)\n\n outputs_gpu = forward_backward(\n True, rnn_gpu, input_val, grad_output, rnn.all_weights, hx_val, grad_hy)\n\n compare_cpu_gpu(outputs_cpu, outputs_gpu)\n\n for nonlinearity in ('tanh', 'relu'):\n hx_val = torch.randn(num_layers, batch, hidden_size, dtype=dtype)\n input_val = torch.randn(seq_length, batch, input_size, dtype=dtype)\n grad_output = torch.randn(\n seq_length, batch, hidden_size * num_directions, dtype=dtype)\n grad_hy = torch.randn(\n num_layers * num_directions, batch, hidden_size, dtype=dtype)\n\n rnn = nn.RNN(input_size, hidden_size, num_layers, bias=bias, nonlinearity=nonlinearity).to(dtype)\n outputs_cpu = forward_backward(False, rnn, input_val, grad_output, rnn.all_weights, hx_val, grad_hy)\n\n rnn_gpu = nn.RNN(input_size, hidden_size, num_layers, bias=bias, nonlinearity=nonlinearity).to(dtype)\n outputs_gpu = forward_backward(True, rnn_gpu, input_val, grad_output, rnn.all_weights, hx_val, grad_hy)\n\n compare_cpu_gpu(outputs_cpu, outputs_gpu)\n\n # checking LSTM with projections\n for bias, bidirectional, batch_first, contig, variable_len, lens_as_tensor \\\n in product((True, False), repeat=6):\n num_directions = 2 if bidirectional else 1\n if batch_first:\n input_val = torch.randn(batch, seq_length, input_size, dtype=dtype)\n grad_output = torch.randn(batch, seq_length, proj_size * num_directions, dtype=dtype)\n else:\n input_val = torch.randn(seq_length, batch, input_size, dtype=dtype)\n grad_output = torch.randn(seq_length, batch, proj_size * num_directions, dtype=dtype)\n\n hx_val = torch.randn(num_layers * num_directions, batch, proj_size, dtype=dtype)\n cx_val = torch.randn(num_layers * num_directions, batch, hidden_size, dtype=dtype)\n grad_hy = torch.randn(num_layers * num_directions, batch, proj_size, dtype=dtype)\n grad_cy = torch.randn(num_layers * num_directions, batch, hidden_size, dtype=dtype)\n\n if not contig:\n grad_output = make_noncontig(grad_output)\n grad_hy = make_noncontig(grad_hy)\n grad_cy = make_noncontig(grad_cy)\n input_var = make_noncontig(input_val)\n hx_val = make_noncontig(hx_val)\n cx_val = make_noncontig(cx_val)\n\n if variable_len:\n lengths = [7, 5, 5, 2, 1, 1]\n if lens_as_tensor:\n lengths = torch.tensor(lengths, dtype=torch.long)\n input_val = rnn_utils.pack_padded_sequence(input_val, lengths, batch_first=batch_first)\n grad_output = rnn_utils.pack_padded_sequence(grad_output, lengths, batch_first=batch_first).data\n\n rnn = nn.LSTM(input_size,\n hidden_size,\n num_layers,\n bias=bias,\n dropout=dropout,\n bidirectional=bidirectional,\n batch_first=batch_first,\n proj_size=proj_size).to(dtype)\n\n outputs_cpu = forward_backward(\n False, rnn, input_val, grad_output, rnn.all_weights,\n hx_val, grad_hy, cx_val, grad_cy)\n\n rnn_gpu = nn.LSTM(input_size,\n hidden_size,\n num_layers,\n bias=bias,\n dropout=dropout,\n bidirectional=bidirectional,\n batch_first=batch_first,\n proj_size=proj_size).to(dtype)\n\n outputs_gpu = forward_backward(\n True, rnn_gpu, input_val, grad_output, rnn.all_weights,\n hx_val, grad_hy, cx_val, grad_cy)\n compare_cpu_gpu(outputs_cpu, outputs_gpu)\n\n @unittest.skipIf(not TEST_CUDNN, \"needs cudnn\")\n def test_RNN_cpu_vs_cudnn_no_dropout(self):\n dtype = torch.double\n self._test_RNN_cpu_vs_cudnn(0, dtype)\n\n @unittest.skipIf(not (TEST_CUDNN and (TEST_CUDNN_VERSION if TEST_CUDNN_VERSION else 0) >= 5103), \"needs cudnn >= 5.1\")\n def test_RNN_cpu_vs_cudnn_with_dropout(self):\n # Because of dropout randomness, can only compare dropout=0 and dropout=1\n self._test_RNN_cpu_vs_cudnn(1)\n\n @unittest.skipIf(not TEST_CUDNN, \"needs cudnn\")\n def test_RNN_cudnn_weight_norm(self):\n input_size = 10\n hidden_size = 6\n num_layers = 2\n seq_length = 7\n batch = 6\n\n # runs on CPU to acquire expected output\n def check_weight_norm(m, name):\n input = torch.randn(seq_length, batch, input_size)\n expected_output = m(input)\n\n # adds weight normalization\n m = torch.nn.utils.weight_norm(m, name=name)\n\n # moves to CUDA\n m = m.cuda()\n input = input.cuda()\n\n # otherwise, subsequent warnings will be hidden, and further tests rely on them\n warnings.simplefilter(\"always\")\n self.assertEqual(m(input), expected_output)\n\n # remove weight norm\n m = torch.nn.utils.remove_weight_norm(m, name=name)\n self.assertEqual(m(input), expected_output)\n\n check_weight_norm(nn.LSTM(input_size, hidden_size, num_layers), 'weight_hh_l0')\n check_weight_norm(nn.LSTM(input_size, hidden_size, num_layers, proj_size=3), 'weight_hr_l0')\n\n @unittest.skipIf(not TEST_CUDA, 'CUDA not available')\n def test_partial_flat_weights(self):\n input_size = 10\n hidden_size = 6\n num_layers = 2\n\n m = nn.LSTM(input_size, hidden_size, num_layers)\n inp = torch.randn(3, 2, 10)\n out_expected = m(inp)\n # deletes an attribute of original LSTM\n weight_orig = m.weight_hh_l0\n del m.weight_hh_l0\n self.assertFalse(hasattr(m, \"weight_hh_l0\"))\n # verifies that moving to CUDA with only some attributes defined\n # does not throw an error\n m.cuda()\n # recompute the weight and make sure that module can be used\n m.weight_hh_l0 = weight_orig.cuda()\n inp = inp.cuda()\n # otherwise, subsequent warnings will be hidden, and further tests rely on them\n warnings.simplefilter(\"always\")\n self.assertEqual(m(inp)[0].cpu(), out_expected[0])\n\n\n @unittest.skipIf(not (TEST_CUDNN and (TEST_CUDNN_VERSION if TEST_CUDNN_VERSION else 0) >= 5103), \"needs cudnn >= 5.1\")\n def test_RNN_dropout(self):\n # checking the assumption that cuDNN sticks dropout in between\n # RNN layers\n for p in (0, 0.276, 0.731, 1):\n for train in (True, False):\n for cuda in (True, False):\n rnn = nn.RNN(10, 1000, 2, bias=False, dropout=p, nonlinearity='relu')\n if cuda:\n rnn.cuda()\n\n if train:\n rnn.train()\n else:\n rnn.eval()\n rnn.weight_ih_l0.data.fill_(1)\n rnn.weight_hh_l0.data.fill_(1)\n rnn.weight_ih_l1.data.fill_(1)\n rnn.weight_hh_l1.data.fill_(1)\n input = torch.ones(1, 1, 10)\n hx = torch.zeros(2, 1, 1000)\n if cuda:\n input = input.cuda()\n hx = hx.cuda()\n\n output, hy = rnn(input, hx)\n self.assertEqual(output.data.min(), output.data.max())\n output_val = output.data[0][0][0]\n if p == 0 or not train:\n self.assertEqual(output_val, 10000)\n elif p == 1:\n self.assertEqual(output_val, 0)\n else:\n self.assertGreater(output_val, 8000)\n self.assertLess(output_val, 12000)\n denorm_mod = (output_val * (1 - p)) % 10\n self.assertLess(min(denorm_mod, 10 - denorm_mod), 1e-2)\n\n self.assertEqual(hy[0].data.min(), hy[0].data.max())\n self.assertEqual(hy[1].data.min(), hy[1].data.max())\n self.assertEqual(hy.data[0][0][0], 10)\n self.assertEqual(hy.data[1][0][0], output_val)\n\n @unittest.skipIf(not (TEST_CUDNN and (TEST_CUDNN_VERSION if TEST_CUDNN_VERSION else 0) >= 5103), \"needs cudnn >= 5.1\")\n def test_RNN_dropout_state(self):\n for p in (0, 0.1234):\n for train in (True, False):\n for cuda in (True, False):\n rnn = nn.RNN(100, 100, 2, bias=False, dropout=p, nonlinearity='relu')\n if cuda:\n rnn.cuda()\n\n if train:\n rnn.train()\n else:\n rnn.eval()\n input = torch.rand(1, 1, 100)\n hx = torch.rand(2, 1, 100)\n if cuda:\n input = input.cuda()\n hx = hx.cuda()\n\n output1, hy1 = rnn(input, hx)\n output2, hy2 = rnn(input, hx)\n\n buf = io.BytesIO()\n rnn_pickle = torch.save(rnn, buf)\n buf.seek(0)\n rnn2 = torch.load(buf)\n rnn2.flatten_parameters()\n output3, hy3 = rnn2(input, hx)\n\n if p == 0 or not train:\n self.assertEqual(output1, output2)\n self.assertEqual(output1, output3)\n self.assertEqual(hy1, hy2)\n self.assertEqual(hy1, hy3)\n else:\n self.assertNotEqual(output1, output2)\n self.assertNotEqual(output1, output3)\n self.assertNotEqual(hy1, hy2)\n self.assertNotEqual(hy1, hy3)\n\n @unittest.skipIf(not (TEST_CUDNN and (TEST_CUDNN_VERSION if TEST_CUDNN_VERSION else 0) >= 5103), \"needs cudnn >= 5.1\")\n def test_RNN_change_dropout(self):\n for train, cuda in product((True, False), repeat=2):\n rnn = nn.RNN(100, 100, 2, dropout=0, nonlinearity='relu')\n input = torch.rand(3, 2, 100)\n if cuda:\n input.data = input.data.cuda()\n rnn.cuda()\n\n if train:\n rnn.train()\n else:\n rnn.eval()\n\n prev_output = None\n for p in (0, 0.5, 0, 0.7, 0.2, 1, 0.2, 0):\n rnn.dropout = p\n output1, hy1 = rnn(input)\n output2, hy2 = rnn(input)\n\n if p == 0 or p == 1 or not train:\n self.assertEqual(output1, output2)\n self.assertEqual(hy1, hy2)\n else:\n self.assertNotEqual(output1, output2)\n self.assertNotEqual(hy1, hy2)\n\n if prev_output is not None:\n if not train:\n self.assertEqual(output1.data, prev_output)\n self.assertEqual(output2.data, prev_output)\n else:\n self.assertNotEqual(output1.data, prev_output)\n self.assertNotEqual(output2.data, prev_output)\n prev_output = output1.data\n\n def test_inplace_thnn(self):\n modules = [nn.ReLU, nn.ELU, nn.SELU, nn.CELU, nn.RReLU]\n for mod in modules:\n r = mod(inplace=True)\n input = torch.randn(5, 5, requires_grad=True)\n output = r(input + 0)\n grad_output = torch.randn(5, 5)\n grad_output_clone = grad_output.clone()\n output.backward(grad_output)\n self.assertEqual(grad_output, grad_output_clone)\n\n @unittest.skipIf(not TEST_CUDA, 'CUDA not available')\n @repeat_test_for_types(get_all_fp_dtypes(include_bfloat16=AMPERE_OR_ROCM))\n def test_noncontig_conv_grad_cuda(self, dtype=torch.float):\n # FIXME: remove after adding non-contiguous grad tests for all modules\n module = nn.Conv2d(3, 5, kernel_size=3, padding=1).to(\"cuda\", dtype)\n input = torch.randn(2, 3, 10, 10, dtype=dtype, device=\"cuda\", requires_grad=True)\n output = module(input)\n\n grad = torch.randn(2, 2, 5, 10, 10, dtype=dtype, device=\"cuda\")[:, 1]\n assert not grad.is_contiguous()\n output.backward(grad, retain_graph=True)\n self.assertIsNotNone(input.grad)\n result = input.grad.data.clone()\n input.grad.data.zero_()\n\n output.backward(grad.contiguous())\n self.assertEqual(result, input.grad.data, atol=dtype2prec_DONTUSE[dtype], rtol=0)\n\n def test_pixel_shuffle_unshuffle(self):\n def _test_pixel_shuffle_unshuffle_helper(num_input_dims, valid_channels_dim=True,\n upscale_factor=None):\n # Function to imperatively ensure pixels are shuffled to the correct locations.\n # Used to validate the batch operations in pixel_shuffle.\n def _verify_pixel_shuffle(input, output, upscale_factor):\n for c in range(output.size(-3)):\n for h in range(output.size(-2)):\n for w in range(output.size(-1)):\n height_idx = h // upscale_factor\n weight_idx = w // upscale_factor\n channel_idx = (upscale_factor * (h % upscale_factor)) + (w % upscale_factor) + \\\n (c * upscale_factor ** 2)\n self.assertEqual(output[..., c, h, w], input[..., channel_idx, height_idx, weight_idx])\n\n upscale_factor = random.randint(2, 5) if upscale_factor is None else upscale_factor\n # If valid_channels_dim=False, add 1 to make channels dim indivisible by upscale_factor ** 2.\n channels = random.randint(1, 4) * upscale_factor ** 2 + (0 if valid_channels_dim else 1)\n height = random.randint(5, 10)\n width = random.randint(5, 10)\n\n if num_input_dims == 1:\n input = torch.rand(channels, requires_grad=True)\n elif num_input_dims == 2:\n input = torch.rand(height, width, requires_grad=True)\n else:\n batch_sizes = [random.randint(1, 3) for _ in range(num_input_dims - 3)]\n input = torch.rand(*batch_sizes, channels, height, width, requires_grad=True)\n ps = nn.PixelShuffle(upscale_factor)\n pus = nn.PixelUnshuffle(downscale_factor=upscale_factor)\n\n if num_input_dims >= 3 and valid_channels_dim and upscale_factor > 0:\n output = ps(input)\n _verify_pixel_shuffle(input, output, upscale_factor)\n output.backward(output.data)\n self.assertEqual(input.data, input.grad.data)\n\n # Ensure unshuffle properly inverts shuffle.\n unshuffle_output = pus(output)\n self.assertEqual(input, unshuffle_output)\n else:\n self.assertRaises(RuntimeError, lambda: ps(input))\n\n def _test_pixel_unshuffle_error_case_helper(num_input_dims, valid_height_dim=True, valid_width_dim=True,\n downscale_factor=None):\n downscale_factor = random.randint(2, 5) if downscale_factor is None else downscale_factor\n channels = random.randint(1, 4)\n # If valid_height_dim=False, add 1 to make height dim indivisible by downscale_factor.\n height = random.randint(3, 5) * abs(downscale_factor) + (0 if valid_height_dim else 1)\n # If valid_width_dim=False, add 1 to make width dim indivisible by downscale_factor.\n width = random.randint(3, 5) * abs(downscale_factor) + (0 if valid_width_dim else 1)\n\n if num_input_dims == 1:\n input = torch.rand(channels, requires_grad=True)\n elif num_input_dims == 2:\n input = torch.rand(height, width, requires_grad=True)\n else:\n batch_sizes = [random.randint(1, 3) for _ in range(num_input_dims - 3)]\n input = torch.rand(*batch_sizes, channels, height, width, requires_grad=True)\n\n pus = nn.PixelUnshuffle(downscale_factor)\n self.assertRaises(RuntimeError, lambda: pus(input))\n\n def _test_pixel_shuffle_unshuffle_for_input_dims(num_input_dims):\n # For 1D - 2D, this is an error case.\n # For 3D - 5D, this is a success case for pixel_shuffle + pixel_unshuffle.\n _test_pixel_shuffle_unshuffle_helper(num_input_dims=num_input_dims)\n\n # Error cases for pixel_shuffle.\n _test_pixel_shuffle_unshuffle_helper(num_input_dims=num_input_dims, valid_channels_dim=False)\n _test_pixel_shuffle_unshuffle_helper(num_input_dims=num_input_dims, upscale_factor=0)\n _test_pixel_shuffle_unshuffle_helper(num_input_dims=num_input_dims, upscale_factor=-2)\n\n # Error cases for pixel_unshuffle.\n _test_pixel_unshuffle_error_case_helper(num_input_dims=num_input_dims, valid_height_dim=False)\n _test_pixel_unshuffle_error_case_helper(num_input_dims=num_input_dims, valid_width_dim=False)\n _test_pixel_unshuffle_error_case_helper(num_input_dims=num_input_dims, downscale_factor=0)\n _test_pixel_unshuffle_error_case_helper(num_input_dims=num_input_dims, downscale_factor=-2)\n\n def test_pixel_shuffle_unshuffle_1D():\n _test_pixel_shuffle_unshuffle_for_input_dims(num_input_dims=1)\n\n def test_pixel_shuffle_unshuffle_2D():\n _test_pixel_shuffle_unshuffle_for_input_dims(num_input_dims=2)\n\n def test_pixel_shuffle_unshuffle_3D():\n _test_pixel_shuffle_unshuffle_for_input_dims(num_input_dims=3)\n\n def test_pixel_shuffle_unshuffle_4D():\n _test_pixel_shuffle_unshuffle_for_input_dims(num_input_dims=4)\n\n def test_pixel_shuffle_unshuffle_5D():\n _test_pixel_shuffle_unshuffle_for_input_dims(num_input_dims=5)\n\n test_pixel_shuffle_unshuffle_1D()\n test_pixel_shuffle_unshuffle_2D()\n test_pixel_shuffle_unshuffle_3D()\n test_pixel_shuffle_unshuffle_4D()\n test_pixel_shuffle_unshuffle_5D()\n\n def test_elu_inplace_view(self):\n v = torch.tensor([1.0, -1.0, 1.0, -1.0], requires_grad=True)\n\n def func(root):\n x = root.clone()\n view = x.narrow(0, 1, 2)\n res = F.elu(view, inplace=True)\n self.assertIs(res, view)\n return x\n\n gradcheck(func, [v])\n gradgradcheck(func, [v])\n\n def test_relu_inplace_view(self):\n v = torch.tensor([1.0, -1.0, 1.0, -1.0], requires_grad=True)\n\n def func(root):\n x = root.clone()\n view = x.narrow(0, 1, 2)\n res = F.relu(view, inplace=True)\n self.assertIs(res, view)\n return x\n\n gradcheck(func, [v])\n gradgradcheck(func, [v])\n\n @unittest.skipIf(not TEST_CUDA, 'CUDA not available')\n def test_PReLU_backward_requires_grad_false(self):\n m = nn.PReLU().to('cuda')\n x = torch.randn(2, 3, 4, 5, requires_grad=False, device='cuda')\n y = m(x)\n y.mean().backward()\n self.assertEqual(x.grad, None)\n\n @unittest.skipIf(\n not TEST_NUMPY or not TEST_SCIPY, \"Numpy or Scipy not found\")\n def test_gelu(self):\n def _test_gelu(n, m, dtype, contiguous, atol=None, rtol=None):\n numpy_dtype = {\n torch.bfloat16: torch.float, torch.float: torch.float, torch.double: torch.double\n }[dtype]\n devices = ['cpu'] if dtype != torch.bfloat16 else [] + \\\n ['cuda'] if TEST_CUDA else []\n\n def _gelu_ref(X):\n return X * stats.norm.cdf(X)\n\n for d in devices:\n if contiguous:\n X = torch.rand(n, m, dtype=dtype, requires_grad=True, device=d)\n else:\n X = torch.rand(n, m, dtype=dtype, requires_grad=True, device=d)[:, ::2]\n res = F.gelu(X)\n ref = _gelu_ref(X.to(numpy_dtype).cpu().detach().numpy())\n self.assertEqual(res, ref, rtol=rtol, atol=atol)\n if dtype != torch.bfloat16:\n gradcheck(F.gelu, [X], eps=1e-4)\n\n for n in range(1, 10):\n for m in range(1, 10):\n _test_gelu(n, m, torch.bfloat16, True, 1e-2, 0)\n _test_gelu(n, m, torch.bfloat16, False, 1e-2, 0)\n _test_gelu(n, m, torch.float32, True)\n _test_gelu(n, m, torch.float32, False)\n _test_gelu(n, m, torch.float64, True)\n _test_gelu(n, m, torch.float64, False)\n\n\n def test_bce_loss_always_nonnegative(self):\n target = torch.ones(5)\n input = torch.ones(5)\n self.assertEqual((nn.BCELoss()(input, target) < 0).sum(), 0)\n\n target = torch.zeros(5)\n input = torch.zeros(5)\n self.assertEqual((nn.BCELoss()(input, target) < 0).sum(), 0)\n\n def test_bce_with_logits_raises_if_target_and_input_are_different_size(self):\n target = torch.rand(5)\n input = torch.rand(5, 1)\n with self.assertRaises(ValueError):\n nn.BCEWithLogitsLoss()(input, target)\n\n target = torch.rand(5, 1)\n input = torch.rand(5)\n with self.assertRaises(ValueError):\n nn.BCEWithLogitsLoss()(input, target)\n\n def test_bce_with_logits_gives_same_result_as_sigmoid_and_bce_loss(self):\n sigmoid = nn.Sigmoid()\n\n target = torch.rand(64, 4)\n output = torch.rand(64, 4) - 0.5\n\n self.assertEqual(nn.BCEWithLogitsLoss()(output, target), nn.BCELoss()(sigmoid(output), target))\n\n weight = torch.rand(4)\n self.assertEqual(nn.BCEWithLogitsLoss(weight)(output, target), nn.BCELoss(weight)(sigmoid(output), target))\n\n target = torch.zeros(4, 1, dtype=torch.float)\n output = torch.empty(4, 1, dtype=torch.float).fill_(-100)\n\n self.assertEqual(nn.BCEWithLogitsLoss()(output, target), nn.BCELoss()(sigmoid(output), target))\n\n self.assertEqual(nn.BCEWithLogitsLoss(reduction='none')(output, target),\n nn.BCELoss(reduction='none')(sigmoid(output), target))\n\n weight = torch.rand(1, dtype=torch.float)\n self.assertEqual(nn.BCEWithLogitsLoss(weight)(output, target), nn.BCELoss(weight)(sigmoid(output), target))\n\n def test_bce_loss_input_range(self):\n bceloss = nn.BCELoss()\n\n target = torch.rand(25, 25)\n output_valid = torch.rand(25, 25)\n output_too_negative = output_valid - 1.0\n output_too_positive = output_valid + 1.0\n\n loss_valid = bceloss(output_valid, target)\n with self.assertRaisesRegex(RuntimeError, 'between 0 and 1'):\n loss_too_negative = bceloss(output_too_negative, target)\n with self.assertRaisesRegex(RuntimeError, 'between 0 and 1'):\n loss_too_positive = bceloss(output_too_positive, target)\n\n def test_bce_loss_size_mismatch(self):\n bceloss = nn.BCELoss()\n a = torch.rand(25)\n b = torch.rand(25, 1)\n with self.assertRaisesRegex(ValueError, r'Using a target size \\('):\n bceloss(a, b)\n\n def test_bce_with_logits_gives_same_result_as_sigmoid_and_bce_loss_large_tensors_with_grad(self):\n x_size = 1024\n y_size = 256\n target = torch.rand(x_size, y_size)\n\n for reduction in ['none', 'mean', 'sum']:\n output_sig = torch.rand(x_size, y_size) - 0.5\n output_logits = output_sig.clone().detach()\n\n output_sig.requires_grad = True\n output_logits.requires_grad = True\n weight = torch.rand(y_size)\n\n loss_sig = nn.BCELoss(weight, reduction=reduction)(\n torch.sigmoid(output_sig), target\n )\n loss_logits = nn.BCEWithLogitsLoss(weight, reduction=reduction)(\n output_logits, target\n )\n\n self.assertEqual(loss_logits, loss_sig)\n\n if reduction == 'none':\n grad = torch.rand(x_size, y_size)\n loss_sig.backward(grad)\n loss_logits.backward(grad)\n else:\n loss_sig.backward()\n loss_logits.backward()\n\n self.assertEqual(output_sig.grad, output_logits.grad)\n\n def test_bce_with_logits_has_correct_grad_at_zero(self):\n output = torch.zeros(3, 1, requires_grad=True)\n target = torch.zeros(3, 1)\n nn.BCEWithLogitsLoss(reduction='sum')(output, target).backward()\n expected_grad = torch.empty(3, 1).fill_(0.5)\n self.assertEqual(output.grad, expected_grad)\n\n def test_bce_with_logits_broadcasts_weights(self):\n target = torch.rand(16, 4)\n output = torch.rand(16, 4) - 0.5\n\n weight = torch.rand(4)\n out1 = nn.BCEWithLogitsLoss(weight)(output, target)\n\n weight = weight.expand(16, 4).contiguous()\n out2 = nn.BCEWithLogitsLoss(weight)(output, target)\n\n self.assertEqual(out1, out2)\n\n weight = torch.rand(16, 1)\n out1 = nn.BCEWithLogitsLoss(weight)(output, target)\n\n weight = weight.expand(16, 4).contiguous()\n out2 = nn.BCEWithLogitsLoss(weight)(output, target)\n\n self.assertEqual(out1, out2)\n\n def test_bce_with_logits_ones_in_pos_weights_are_the_same_as_none(self):\n target = torch.rand(64, 4)\n output = torch.rand(64, 4) - 0.5\n pos_weight = torch.ones(64, 4)\n\n self.assertEqual(nn.BCEWithLogitsLoss()(output, target),\n nn.BCEWithLogitsLoss(pos_weight=pos_weight)(output, target))\n\n def test_bce_with_logits_broadcasts_pos_weights(self):\n target = torch.rand(64, 4)\n output = torch.rand(64, 4) - 0.5\n pos_weight = torch.rand(4)\n out1 = nn.BCEWithLogitsLoss(pos_weight=pos_weight)(output, target)\n\n pos_weight1 = pos_weight.expand(1, 4)\n out2 = nn.BCEWithLogitsLoss(pos_weight=pos_weight1)(output, target)\n\n pos_weight2 = pos_weight.expand(64, 4)\n out3 = nn.BCEWithLogitsLoss(pos_weight=pos_weight2)(output, target)\n\n self.assertEqual(out1, out2)\n self.assertEqual(out1, out3)\n\n def test_bce_with_logits_with_pos_weight_has_correct_grad_at_zero(self):\n output = torch.zeros(3, 1, requires_grad=True)\n target = torch.zeros(3, 1)\n pos_weight = torch.ones(3, 1)\n nn.BCEWithLogitsLoss(pos_weight=pos_weight, reduction='sum')(output, target).backward()\n expected_grad = torch.empty(3, 1).fill_(0.5)\n grad = output.grad\n self.assertEqual(grad, expected_grad)\n\n def test_bce_with_logits_stability(self):\n output = torch.tensor([0., -120.])\n target = torch.tensor([0., 1.])\n pos_weight = torch.tensor([1., 1.])\n\n out1 = nn.BCEWithLogitsLoss()(output, target)\n self.assertTrue(torch.isfinite(out1).all().item())\n\n out2 = nn.BCEWithLogitsLoss(pos_weight=pos_weight)(output, target)\n self.assertTrue(torch.isfinite(out2).all().item())\n\n def test_bce_loss_broadcasts_weights(self):\n sigmoid = nn.Sigmoid()\n target = torch.rand(16, 4)\n output = torch.rand(16, 4) - 0.5\n\n weight = torch.rand(4)\n out1 = nn.BCELoss(weight)(sigmoid(output), target)\n\n weight = weight.expand(16, 4).contiguous()\n out2 = nn.BCELoss(weight)(sigmoid(output), target)\n\n self.assertEqual(out1, out2)\n\n weight = torch.rand(16, 1)\n out1 = nn.BCELoss(weight)(sigmoid(output), target)\n\n weight = weight.expand(16, 4).contiguous()\n out2 = nn.BCELoss(weight)(sigmoid(output), target)\n\n self.assertEqual(out1, out2)\n\n def test_elu_inplace_gradgrad(self):\n v = torch.randn(8, requires_grad=True)\n\n def func(root):\n x = root.clone()\n return F.elu(x, inplace=True)\n\n gradcheck(func, [v])\n gradgradcheck(func, [v])\n\n def test_hardtanh_inplace_gradgrad(self):\n v = torch.randn(8, requires_grad=True)\n\n def func(root):\n x = root.clone()\n return F.hardtanh(x, inplace=True)\n\n gradcheck(func, [v])\n gradgradcheck(func, [v])\n\n # test hardtanh backward froo large tensor\n def test_hardtanh_backward(self):\n x = torch.randn(128, 10000, requires_grad=True)\n grad = torch.randn(128, 10000)\n z = torch.zeros(128, 10000)\n y = F.hardtanh(x)\n y.backward(grad)\n # ref backward path for hardtanh\n mask = (x > -1) & (x < 1)\n x_grad_ref = torch.where(mask, grad, z)\n self.assertEqual(x.grad, x_grad_ref)\n\n @unittest.skipIf(not TEST_CUDA, \"CUDA unavailable\")\n @unittest.skipIf(not TEST_CUDNN, \"needs cudnn\")\n @skipIfRocm\n def test_batchnorm_cudnn_nhwc(self):\n def run_test(input, grad_output):\n c = input.size(1)\n mod = nn.BatchNorm2d(c).cuda().float()\n mod.weight.data.uniform_()\n mod.bias.data.uniform_()\n ref_input = input.detach().clone().contiguous().requires_grad_(True)\n ref_grad = grad.detach().clone().contiguous()\n ref_mod = nn.BatchNorm2d(c).cuda().float()\n ref_mod.load_state_dict(mod.state_dict())\n out = mod(input)\n out.backward(grad_output)\n ref_out = ref_mod(ref_input)\n ref_out.backward(ref_grad)\n self.assertTrue(out.is_contiguous(memory_format=torch.channels_last))\n self.assertTrue(ref_out.is_contiguous())\n self.assertEqual(out, ref_out)\n self.assertEqual(mod.weight.grad, ref_mod.weight.grad)\n self.assertEqual(mod.bias.grad, ref_mod.bias.grad)\n self.assertEqual(input.grad, ref_input.grad)\n\n input = torch.randint(1, 10, (4, 8, 2, 2), dtype=torch.float32, device=\"cuda\")\n input = input.contiguous(memory_format=torch.channels_last).detach().requires_grad_()\n\n grad = torch.randint(1, 10, (4, 8, 2, 2), dtype=torch.float32, device=\"cuda\")\n grad = grad.contiguous(memory_format=torch.channels_last)\n run_test(input, grad)\n # see #42588, grad is channels_last contiguous, but grad.suggest_memory_format (rightly) return \"contiguous\"\n # not channels_last\n input = torch.randint(1, 10, (2, 8, 8, 1), dtype=torch.float32, device=\"cuda\")\n input = input.contiguous(memory_format=torch.channels_last).detach().requires_grad_()\n grad = torch.randint(1, 10, (2, 8, 8, 1), dtype=torch.float32, device=\"cuda\")\n grad = grad.permute(0, 2, 1, 3)\n run_test(input, grad)\n\n @unittest.skipIf(not TEST_CUDA, \"CUDA unavailable\")\n def test_batchnorm_cudnn_half(self):\n # THNN\n input = torch.randint(1, 10, (2, 3, 2, 2), dtype=torch.half, device=\"cuda\", requires_grad=True)\n m = nn.BatchNorm2d(3).half().cuda()\n thnn_output = m(input)\n thnn_output.sum().backward()\n thnn_input_grad = input.grad.data.clone()\n self.assertEqualTypeString(thnn_output, input)\n # cuDNN\n if TEST_CUDNN:\n input.grad = None\n m = m.float()\n cudnn_output = m(input)\n cudnn_output.sum().backward()\n cudnn_input_grad = input.grad.data.clone()\n self.assertEqualTypeString(cudnn_output, input)\n self.assertEqual(cudnn_output, thnn_output)\n self.assertEqual(cudnn_input_grad, thnn_input_grad, atol=1e-3, rtol=0)\n\n @unittest.skipIf(not TEST_CUDA, \"CUDA unavailable\")\n def test_batchnorm_nonaffine_cuda_half_input(self):\n input = torch.randn(16, 3, 24, 24, dtype=torch.half, device=\"cuda\")\n m = nn.BatchNorm2d(3, affine=False).cuda().float() # keep running stats in FP32\n output = m(input)\n self.assertEqualTypeString(output, input)\n m.eval()\n output = m(input)\n self.assertEqualTypeString(output, input)\n\n @unittest.skipIf(not TEST_CUDA, \"CUDA unavailable\")\n @repeat_test_for_types([torch.float, torch.half])\n def test_batchnorm_large_batch(self, dtype=torch.float):\n bn = nn.BatchNorm2d(1).to('cuda', dtype)\n data = torch.rand(880801, 1, 1, 1, device=\"cuda\", dtype=dtype)\n out = bn(data).sum().backward()\n\n def test_batchnorm_raises_error_if_less_than_one_value_per_channel(self):\n x = torch.rand(10)[None, :, None]\n with self.assertRaises(ValueError):\n torch.nn.BatchNorm1d(10)(x)\n\n def test_batchnorm_raises_error_if_running_mean_is_not_same_size_as_input(self):\n input = torch.rand(2, 10)\n running_var = torch.rand(10)\n wrong_sizes = [9, 11]\n for size in wrong_sizes:\n with self.assertRaises(RuntimeError):\n F.batch_norm(input, torch.rand(size), running_var)\n\n def test_batchnorm_raises_error_if_running_var_is_not_same_size_as_input(self):\n input = torch.rand(2, 10)\n running_mean = torch.rand(10)\n wrong_sizes = [9, 11]\n for size in wrong_sizes:\n with self.assertRaises(RuntimeError):\n F.batch_norm(input, running_mean, torch.rand(size))\n\n def test_batchnorm_raises_error_if_weight_is_not_same_size_as_input(self):\n input = torch.rand(2, 10)\n running_mean = torch.rand(10)\n running_var = torch.rand(10)\n wrong_sizes = [9, 11]\n for size in wrong_sizes:\n with self.assertRaises(RuntimeError):\n F.batch_norm(input, running_mean, running_var, weight=Parameter(torch.rand(size)))\n\n def test_batchnorm_raises_error_if_bias_is_not_same_size_as_input(self):\n input = torch.rand(2, 10)\n running_mean = torch.rand(10)\n running_var = torch.rand(10)\n wrong_sizes = [9, 11]\n for size in wrong_sizes:\n with self.assertRaises(RuntimeError):\n F.batch_norm(input, running_mean, running_var, bias=Parameter(torch.rand(size)))\n\n def test_batchnorm_buffer_update_when_stats_are_not_tracked(self):\n input_size = (32, 4)\n # Instantiate BN with buffers that are not None\n bn = nn.BatchNorm1d(input_size[1], track_running_stats=True)\n # Use buffers for normalization but don't update them\n bn.track_running_stats = False\n # Store initial values\n num_batches = bn.num_batches_tracked.clone()\n running_mean = bn.running_mean.clone()\n running_var = bn.running_var.clone()\n # Forward random tensor\n _ = bn(torch.rand(input_size))\n # Ensure none of the buffers has been updated\n self.assertTrue(torch.equal(num_batches, bn.num_batches_tracked))\n self.assertTrue(torch.equal(running_mean, bn.running_mean))\n self.assertTrue(torch.equal(running_var, bn.running_var))\n\n def test_pairwise_distance(self):\n input1 = torch.randn(4, 4, requires_grad=True)\n input2 = torch.randn(4, 4, requires_grad=True)\n self.assertTrue(gradcheck(lambda x, y: F.pairwise_distance(x, y), (input1, input2)))\n\n def test_pdist(self):\n for device, trans in itertools.product(device_(), [False, True]):\n inp = torch.randn(4, 5, dtype=torch.double, device=device, requires_grad=True)\n if trans:\n inp = inp.transpose(0, 1)\n for p in [0, 1, 2, 0.5, 1.5, 2.5, float('inf')]:\n self.assertTrue(gradcheck(lambda x: F.pdist(x, p), (inp,)))\n\n def test_pdist_zeros(self):\n \"\"\"Test that grad is still valid when dist is 0\"\"\"\n for device in device_():\n inp = torch.randn(1, 3, dtype=torch.double, device=device, requires_grad=True).repeat([2, 1])\n for p in [0, 1, 2, 0.5, 1.5, 2.5, float('inf')]:\n self.assertTrue(gradcheck(lambda x: F.pdist(x, p), (inp,)))\n\n def test_pdist_empty_row(self):\n for device in device_():\n inp = torch.randn(1, 3, dtype=torch.double, device=device, requires_grad=True)\n self.assertTrue(gradcheck(F.pdist, (inp,)))\n\n def test_pdist_empty_col(self):\n for device in device_():\n inp = torch.randn(4, 0, dtype=torch.double, device=device, requires_grad=True)\n self.assertTrue(gradcheck(F.pdist, (inp,)))\n\n @unittest.expectedFailure\n def test_pdist_cpu_gradgrad_unimplemented(self):\n inp = torch.randn(4, 5, requires_grad=True)\n gradgradcheck(F.pdist, (inp,))\n\n @unittest.expectedFailure\n def test_pdist_cuda_gradgrad_unimplemented(self):\n inp = torch.randn(4, 5, device='cuda', requires_grad=True)\n gradgradcheck(F.pdist, (inp,))\n\n def test_cosine_embedding_loss_with_diff_type(self):\n for device in device_():\n input1 = torch.tensor([[2, 3, 4], [6, 2, 4]], dtype=torch.double, device=device)\n input2 = torch.tensor([[2, 3, 5], [3, 2, 1]], dtype=torch.double, device=device)\n target = torch.tensor([1, -1], dtype=torch.int, device=device)\n expected = torch.nn.functional.cosine_embedding_loss(input1, input2, target)\n for dt1 in torch.testing.get_all_math_dtypes(device):\n for dt2 in torch.testing.get_all_math_dtypes(device):\n for dt3 in torch.testing.get_all_math_dtypes(device):\n # dt3 is used as dtype for target = [1, -1], so let's skip unsigned type\n if dt3 == torch.uint8:\n continue\n if dt1.is_complex or dt2.is_complex or dt3.is_complex:\n continue\n input1 = input1.to(dt1)\n input2 = input2.to(dt2)\n target = target.to(dt3)\n result = torch.nn.functional.cosine_embedding_loss(input1, input2, target)\n self.assertEqual(result.item(), expected.item(), atol=0.001, rtol=0)\n\n def test_kl_div_with_diff_type(self):\n for device in device_():\n input = torch.tensor([[2, 3, 5], [3, 2, 1]], dtype=torch.double, device=device)\n target = torch.tensor([[1, 2, 3], [4, 5, 6]], dtype=torch.double, device=device)\n expected = torch.nn.functional.kl_div(input, target)\n for input_dtype in torch.testing.get_all_math_dtypes(device):\n if input_dtype.is_complex:\n continue\n for target_dtype in [torch.float32, torch.float64, torch.float16]:\n if (torch.device(device).type == 'cpu' and target_dtype == torch.float16):\n continue\n input = input.to(input_dtype)\n target = target.to(target_dtype)\n result = torch.nn.functional.kl_div(input, target)\n self.assertEqual(result.item(), expected.item(), atol=0.001, rtol=0)\n\n def test_kl_div_with_diff_type_log_target(self):\n for device in device_():\n input = torch.tensor([[2, 3, 5], [3, 2, 1]], dtype=torch.double, device=device)\n target = torch.tensor([[1, 2, 3], [4, 5, 6]], dtype=torch.double, device=device).log()\n expected = torch.nn.functional.kl_div(input, target, log_target=True)\n for input_dtype in torch.testing.get_all_math_dtypes(device):\n if input_dtype.is_complex:\n continue\n for target_dtype in [torch.float32, torch.float64, torch.float16]:\n if (torch.device(device).type == 'cpu' and target_dtype == torch.float16):\n continue\n input = input.to(input_dtype)\n target = target.to(target_dtype)\n result = torch.nn.functional.kl_div(input, target, log_target=True)\n self.assertEqual(result.item(), expected.item(), atol=0.001, rtol=0)\n\n def test_kl_div_log_softmax_target(self):\n for device in device_():\n a = torch.tensor([[1.0, 2, 3], [5.0, 5, 5]], device=device)\n b = torch.tensor([[1.0, 2, 3], [5.0, 5, 5]], device=device)\n self.assertEqual(\n F.kl_div(F.log_softmax(a, 1), F.log_softmax(b, 1), reduction='none', log_target=True),\n torch.zeros_like(a)\n )\n\n def test_cosine_embedding_loss_no_reduce(self):\n input1 = torch.randn(15, 10, requires_grad=True)\n input2 = torch.randn(15, 10, requires_grad=True)\n target = torch.randn(15).sign()\n self.assertTrue(gradcheck(lambda x, y, z: F.cosine_embedding_loss(\n x, y, z, reduction='none'), (input1, input2, target)))\n self.assertEqual(F.cosine_embedding_loss(input1, input2, target, reduction='none'),\n loss_reference_fns['CosineEmbeddingLoss'](input1, input2, target, reduction='none'))\n\n def test_cosine_embedding_loss_margin_no_reduce(self):\n input1 = torch.randn(15, 10, requires_grad=True)\n input2 = torch.randn(15, 10, requires_grad=True)\n target = torch.randn(15).sign()\n self.assertTrue(gradcheck(lambda x, y, z: F.cosine_embedding_loss(\n x, y, z, margin=0.5, reduction='none'), (input1, input2, target)))\n self.assertEqual(F.cosine_embedding_loss(input1, input2, target, margin=0.5, reduction='none'),\n loss_reference_fns['CosineEmbeddingLoss'](input1, input2, target,\n margin=0.5, reduction='none'))\n\n def test_cosine_embedding_loss_invalid_target_shape(self):\n input1 = torch.randn(15, 10)\n input2 = torch.randn(15, 10)\n target = torch.randn(15, 1).sign()\n\n with self.assertRaisesRegex(RuntimeError, \"1D target tensor expected\"):\n F.cosine_embedding_loss(input1, input2, target)\n\n def test_margin_ranking_loss_no_reduce(self):\n input1 = torch.randn(15).mul_(10).requires_grad_()\n input2 = torch.randn(15).mul_(10).requires_grad_()\n target = torch.randn(15).sign()\n self.assertTrue(gradcheck(lambda x, y, z: F.margin_ranking_loss(\n x, y, z, reduction='none'), (input1, input2, target)))\n self.assertEqual(F.margin_ranking_loss(input1, input2, target, reduction='none'),\n loss_reference_fns['MarginRankingLoss'](input1, input2, target, reduction='none'))\n\n def test_margin_ranking_loss_margin_no_reduce(self):\n input1 = torch.randn(15).mul_(10).requires_grad_()\n input2 = torch.randn(15).mul_(10).requires_grad_()\n target = torch.randn(15).sign()\n self.assertTrue(gradcheck(lambda x, y, z: F.margin_ranking_loss(\n x, y, z, margin=0.5, reduction='none'), (input1, input2, target)))\n self.assertEqual(F.margin_ranking_loss(input1, input2, target, margin=0.5, reduction='none'),\n loss_reference_fns['MarginRankingLoss'](input1, input2, target, margin=0.5, reduction='none'))\n\n def test_triplet_margin_loss(self):\n input1 = torch.randn(5, 10, requires_grad=True)\n input2 = torch.randn(5, 10, requires_grad=True)\n input3 = torch.randn(5, 10, requires_grad=True)\n self.assertTrue(gradcheck(lambda x1, x2, x3: F.triplet_margin_loss(\n x1, x2, x3), (input1, input2, input3)))\n self.assertEqual(F.triplet_margin_loss(input1, input2, input3),\n loss_reference_fns['TripletMarginLoss'](input1, input2, input3))\n\n def test_triplet_margin_loss_swap(self):\n input1 = torch.randn(5, 10, requires_grad=True)\n input2 = torch.randn(5, 10, requires_grad=True)\n input3 = torch.randn(5, 10, requires_grad=True)\n self.assertTrue(gradcheck(lambda x1, x2, x3: F.triplet_margin_loss(\n x1, x2, x3, swap=True), (input1, input2, input3)))\n self.assertEqual(F.triplet_margin_loss(input1, input2, input3, swap=True),\n loss_reference_fns['TripletMarginLoss'](input1, input2, input3, swap=True))\n\n def test_triplet_margin_loss_no_reduce(self):\n input1 = torch.randn(5, 10, requires_grad=True)\n input2 = torch.randn(5, 10, requires_grad=True)\n input3 = torch.randn(5, 10, requires_grad=True)\n self.assertTrue(gradcheck(lambda x1, x2, x3: F.triplet_margin_loss(\n x1, x2, x3, reduction='none'), (input1, input2, input3)))\n self.assertEqual(F.triplet_margin_loss(input1, input2, input3, reduction='none'),\n loss_reference_fns['TripletMarginLoss'](input1, input2, input3, reduction='none'))\n\n def test_triplet_margin_loss_swap_no_reduce(self):\n input1 = torch.randn(5, 10, requires_grad=True)\n input2 = torch.randn(5, 10, requires_grad=True)\n input3 = torch.randn(5, 10, requires_grad=True)\n self.assertTrue(gradcheck(lambda x1, x2, x3: F.triplet_margin_loss(\n x1, x2, x3, swap=True, reduction='none'), (input1, input2, input3)))\n self.assertEqual(F.triplet_margin_loss(input1, input2, input3, swap=True, reduction='none'),\n loss_reference_fns['TripletMarginLoss'](input1, input2, input3, swap=True, reduction='none'))\n\n def test_pointwise_loss_target_grad_none_reduction(self):\n i = torch.randn(5, 10)\n t = torch.randn(5, 10, requires_grad=True)\n self.assertEqual(F.mse_loss(i, t, reduction='none').size(), t.size())\n self.assertEqual(F.l1_loss(i, t, reduction='none').size(), t.size())\n\n def test_pointwise_loss_broadcast(self):\n losses = {\n 'mse_loss': lambda x, y, r: F.mse_loss(x, y, reduction=r),\n 'l1_loss': lambda x, y, r: F.l1_loss(x, y, reduction=r),\n 'smooth_l1_loss': lambda x, y, r: F.smooth_l1_loss(x, y, reduction=r),\n 'huber_loss': lambda x, y, r: F.huber_loss(x, y, reduction=r),\n }\n\n input = torch.randn(2, 1, requires_grad=True)\n for _name, fn in losses.items():\n for requires_grad in [True, False]:\n # When target.requires_grad=True, its impl is in Python, while the other is in TH.\n target = torch.randn(2, 10, requires_grad=requires_grad)\n for reduction in ['none', 'mean', 'sum']:\n l = fn(input, target, reduction)\n if reduction == 'none':\n self.assertEqual(l.size(), target.size())\n self.assertTrue(gradcheck(fn, (input, target, reduction)))\n\n # https://github.com/pytorch/pytorch/issues/27692 reports\n # that l1_loss get a wrong result for big batch size\n def test_l1_loss_correct(self):\n for dtype in [torch.float, torch.cfloat]:\n for N in range(1, 50, 10):\n input = torch.rand(N, 3, 1024, 1024, dtype=dtype)\n self.assertEqual(\n torch.nn.L1Loss()(input, torch.zeros_like(input)),\n input.abs().mean())\n\n def test_smoothl1loss_negative_beta_not_supported(self):\n with self.assertRaises(RuntimeError):\n F.smooth_l1_loss(torch.randn(2, 2), torch.randn(2, 2), beta=-1.0)\n\n def test_huber_loss_invalid_delta(self):\n def _test_huber_loss_delta_error_helper(delta):\n input, target = torch.randn(2, 2), torch.randn(2, 2)\n loss = torch.nn.HuberLoss(delta=delta)\n with self.assertRaises(RuntimeError):\n loss(input, target)\n\n def test_huber_loss_negative_delta():\n _test_huber_loss_delta_error_helper(delta=-0.5)\n\n def test_huber_loss_zero_delta():\n _test_huber_loss_delta_error_helper(delta=0.0)\n\n test_huber_loss_negative_delta()\n test_huber_loss_zero_delta()\n\n def test_cosine_similarity(self):\n input1 = torch.randn(4, 4, requires_grad=True)\n input2 = torch.randn(4, 4, requires_grad=True)\n self.assertTrue(gradcheck(lambda x, y: F.cosine_similarity(x, y), (input1, input2)))\n\n input1 = torch.randn(4, 5, 6, requires_grad=True)\n input2 = torch.randn(4, 5, 6, requires_grad=True)\n self.assertTrue(gradcheck(lambda x, y: F.cosine_similarity(x, y, dim=0), (input1, input2)))\n self.assertTrue(gradcheck(lambda x, y: F.cosine_similarity(x, y, dim=-1), (input1, input2)))\n\n input1 = torch.randn((), requires_grad=True)\n input2 = torch.randn((), requires_grad=True)\n self.assertTrue(gradcheck(lambda x, y: F.cosine_similarity(x, y, dim=0), (input1, input2)))\n self.assertTrue(gradcheck(lambda x, y: F.cosine_similarity(x, y, dim=-1), (input1, input2)))\n\n # Check cosine_similarity input/output shapes\n input_size = (1, 3, 2, 1)\n expected_size = (1, 2, 1)\n input1 = torch.randn(input_size, requires_grad=True)\n input2 = torch.randn(input_size, requires_grad=True)\n self.assertEqual(F.cosine_similarity(input1, input2, dim=1).size(), expected_size)\n\n # Check numerical precision, issue #18057\n vv1 = torch.tensor(list([float(i) for i in range(84)])).unsqueeze(0)\n vv2 = torch.tensor(list([float(i) for i in range(84)])).unsqueeze(0)\n out = F.cosine_similarity(vv1, vv2)\n self.assertLessEqual(out, 1.0)\n\n # Check dividing by 0.\n input1 = torch.randn(10).requires_grad_()\n input2 = torch.zeros_like(input1).requires_grad_()\n torch.cosine_similarity(input1, input2, 0).sum().backward()\n self.assertEqual(input1.grad, torch.zeros_like(input1))\n self.assertEqual(input2.grad, input1 * 1e8)\n\n def test_grid_sample_error_checking(self):\n input = torch.empty(1, 1, 2, 2)\n grid = torch.empty(1, 1, 1, 2)\n\n # assert no error\n F.grid_sample(input, grid, align_corners=False)\n\n with self.assertRaisesRegex(ValueError, \"but got: 'garbage'\"):\n F.grid_sample(input, grid, mode='garbage', align_corners=False)\n\n with self.assertRaisesRegex(ValueError, \"but got: 'garbage'\"):\n F.grid_sample(input, grid, padding_mode='garbage', align_corners=False)\n\n with self.assertRaisesRegex(RuntimeError, \"expected input and grid to have same dtype\"):\n F.grid_sample(input.float(), grid.double(), align_corners=False)\n\n with self.assertRaisesRegex(RuntimeError, \"expected 4D or 5D input\"):\n F.grid_sample(input[0], grid, align_corners=False)\n\n with self.assertRaisesRegex(RuntimeError, \"grid with same number of dimensions\"):\n F.grid_sample(input, torch.empty(1, 1, 1, 1, 3), align_corners=False)\n\n with self.assertRaisesRegex(RuntimeError, \"expected grid and input to have same batch size\"):\n F.grid_sample(input, torch.empty(2, 1, 1, 2), align_corners=False)\n\n with self.assertRaisesRegex(RuntimeError, \"expected grid to have size 2 in last dimension\"):\n F.grid_sample(input, torch.empty(1, 1, 1, 3), align_corners=False)\n\n with self.assertRaisesRegex(RuntimeError, \"expected input to have non-empty spatial dimensions\"):\n F.grid_sample(torch.empty(1, 1, 0, 2), grid, align_corners=False)\n\n with self.assertRaisesRegex(RuntimeError, \"bicubic interpolation only supports 4D input\"):\n F.grid_sample(torch.empty(1, 1, 2, 2, 2), torch.empty(1, 1, 1, 1, 3), mode='bicubic')\n\n if TEST_CUDA:\n with self.assertRaisesRegex(RuntimeError, \"expected input and grid to be on same device\"):\n F.grid_sample(input.cuda(), grid, align_corners=False)\n\n def test_affine_grid_error_checking(self):\n # 2D affine\n theta = torch.empty(1, 2, 3, dtype=torch.double)\n size = torch.Size([1, 1, 2, 2])\n\n # assert no error\n F.affine_grid(theta, size, align_corners=False)\n\n # check for warning for empty span along dimension\n with warnings.catch_warnings(record=True) as w:\n # Ensure warnings are being shown\n warnings.simplefilter(\"always\")\n # Should not trigger warning\n F.affine_grid(theta, torch.Size([1, 1, 2, 1]), align_corners=False)\n # Check no warning occurs\n self.assertNotIn('See the documentation of affine_grid for details.', ' '.join(map(str, w)))\n # Should trigger warning\n F.affine_grid(theta, torch.Size([1, 1, 2, 1]), align_corners=True)\n # Check warning occurs\n self.assertIn('See the documentation of affine_grid for details.', ' '.join(map(str, w)))\n\n with self.assertRaisesRegex(ValueError, \"Expected theta to have floating point type\"):\n F.affine_grid(theta.int(), size, align_corners=False)\n\n with self.assertRaisesRegex(ValueError, \"Expected a batch of 2D affine matrices of shape Nx2x3\"):\n F.affine_grid(theta[0], size, align_corners=False)\n\n with self.assertRaisesRegex(ValueError, \"Expected a batch of 2D affine matrices of shape Nx2x3\"):\n F.affine_grid(theta.unsqueeze(0), size, align_corners=False)\n\n with self.assertRaisesRegex(ValueError, \"Expected a batch of 2D affine matrices of shape Nx2x3\"):\n F.affine_grid(theta.repeat(1, 2, 1), size, align_corners=False)\n\n with self.assertRaisesRegex(ValueError, \"Expected a batch of 2D affine matrices of shape Nx2x3\"):\n F.affine_grid(theta.repeat(1, 1, 2), size, align_corners=False)\n\n # 3D affine\n theta = torch.empty(1, 3, 4, dtype=torch.double)\n size = torch.Size([1, 1, 2, 2, 2])\n\n # assert no error\n F.affine_grid(theta, size, align_corners=False)\n\n # check for warning for empty span along dimension\n with warnings.catch_warnings(record=True) as w:\n # Ensure warnings are being shown\n warnings.simplefilter(\"always\")\n # Should not trigger warning\n F.affine_grid(theta, torch.Size([1, 1, 3, 2, 1]), align_corners=False)\n # Check no warning occurs\n self.assertNotIn('See the documentation of affine_grid for details.', ' '.join(map(str, w)))\n # Should trigger warning\n F.affine_grid(theta, torch.Size([1, 1, 3, 2, 1]), align_corners=True)\n # Check warning occurs\n self.assertIn('See the documentation of affine_grid for details.', ' '.join(map(str, w)))\n\n with self.assertRaisesRegex(ValueError, \"Expected a batch of 3D affine matrices of shape Nx3x4\"):\n F.affine_grid(theta[0], size, align_corners=False)\n\n with self.assertRaisesRegex(ValueError, \"Expected a batch of 3D affine matrices of shape Nx3x4\"):\n F.affine_grid(theta.unsqueeze(0), size, align_corners=False)\n\n with self.assertRaisesRegex(ValueError, \"Expected a batch of 3D affine matrices of shape Nx3x4\"):\n F.affine_grid(theta.repeat(1, 2, 1), size, align_corners=False)\n\n with self.assertRaisesRegex(ValueError, \"Expected a batch of 3D affine matrices of shape Nx3x4\"):\n F.affine_grid(theta.repeat(1, 1, 2), size, align_corners=False)\n\n with self.assertRaisesRegex(NotImplementedError, \"affine_grid only supports 4D and 5D sizes\"):\n F.affine_grid(theta, torch.Size([1, 2, 2]), align_corners=False)\n\n with self.assertRaisesRegex(NotImplementedError, \"affine_grid only supports 4D and 5D sizes\"):\n F.affine_grid(theta, torch.Size([1, 1, 2, 2, 2, 2]), align_corners=False)\n\n @skipIfRocm\n def test_grid_sample(self):\n def test(N, C, H, W, mode, padding_mode, align_corners):\n def test_shape(N, C, IH, IW, H, W, mode, padding_mode, align_corners):\n for grid_dim_contig_order in [(0, 1, 2, 3), (0, 3, 1, 2), (3, 0, 1, 2), (0, 2, 1, 3)]:\n # grid_dim_contig_order specifies the dimension order that can\n # make grid to be contiguous.\n # i.e., grid.permute(grid_dim_contig_order) is contiguous.\n # e.g., with grid_dim_contig_order=[0, 3, 1, 2], grid should be\n # initialized with contiguous tensor of shape [N, 2, H, W]\n # and permuted to [N, H, W, 2] afterwards.\n grid_shape = [N, H, W, 2]\n grid_init_shape = [grid_shape[d] for d in grid_dim_contig_order]\n grid_fwd_permute = [None, None, None, None]\n for i, d in enumerate(grid_dim_contig_order):\n grid_fwd_permute[d] = i\n\n def get_grid(device='cpu', data=None):\n if data is not None:\n assert list(data.shape) == grid_shape\n data = data.permute(grid_dim_contig_order).to(device)\n else:\n data = torch.randn(grid_init_shape, device=device)\n grid = data.permute(grid_fwd_permute)\n assert grid.permute(grid_dim_contig_order).is_contiguous()\n return grid\n\n input_cpu = torch.randn(C, N, IH, IW).transpose(0, 1).requires_grad_()\n grid_cpu = get_grid().requires_grad_()\n out_cpu = F.grid_sample(input_cpu, grid_cpu, mode=mode, padding_mode=padding_mode,\n align_corners=align_corners)\n self.assertTrue(out_cpu.size() == torch.Size([N, C, H, W]))\n\n gradients = torch.randn_like(out_cpu)\n out_cpu.backward(gradients)\n\n\n # Compare against unvectorized CPU fallback\n\n # NOTE [ grid_sample CPU fallback ]\n # grid_sample uses AVX for 2d images, but that requires 32-bit indexing for\n # 32-bit floats. So we also have a fallback that is used only for float tensors\n # requiring 64-bit indexing. That requires too much memory to run on CI, so we\n # also export the fallback and test it here to ensure feature parity with\n # the vectorized version.\n input_fallback = input_cpu.float().detach_().requires_grad_()\n grid_fallback = grid_cpu.float().detach_().requires_grad_()\n out_fallback = torch._grid_sampler_2d_cpu_fallback(\n input_fallback, grid_fallback,\n F.GRID_SAMPLE_INTERPOLATION_MODES[mode],\n F.GRID_SAMPLE_PADDING_MODES[padding_mode],\n align_corners)\n self.assertEqual(out_fallback, out_cpu.float(), atol=1e-5, rtol=5e-5)\n\n out_fallback.backward(gradients.float())\n self.assertEqual(input_fallback.grad, input_cpu.grad.float(), atol=1e-4, rtol=5e-5)\n self.assertEqual(grid_fallback.grad, grid_cpu.grad.float(), atol=1e-4, rtol=5e-5)\n\n if TEST_CUDA:\n input_cuda = input_cpu.detach().transpose(0, 1).cuda().transpose(0, 1).requires_grad_()\n grid_cuda = get_grid('cuda', grid_cpu.detach()).requires_grad_()\n out_cuda = F.grid_sample(input_cuda, grid_cuda, mode=mode, padding_mode=padding_mode,\n align_corners=align_corners)\n self.assertEqual(out_cpu, out_cuda)\n\n out_cuda.backward(gradients.cuda())\n self.assertEqual(input_cpu.grad, input_cuda.grad)\n self.assertEqual(grid_cpu.grad, grid_cuda.grad, atol=5e-5, rtol=0)\n\n # check that zero-dimensional input strides don't error out\n base_input = torch.randn(N, C, 1, IW)\n input_cpu = base_input.expand_as(input_cuda).requires_grad_()\n out_cpu = F.grid_sample(input_cpu, grid_cpu, mode=mode, padding_mode=padding_mode,\n align_corners=align_corners)\n\n input_cuda = base_input.cuda().expand_as(input_cuda).requires_grad_()\n out_cuda = F.grid_sample(input_cuda, grid_cuda, mode=mode, padding_mode=padding_mode,\n align_corners=align_corners)\n self.assertEqual(out_cpu, out_cuda)\n\n # test same size output\n test_shape(N, C, H, W, H, W, mode, padding_mode, align_corners)\n\n # test larger output\n N = random.randint(2, 8)\n C = random.randint(2, 8)\n IH = random.randint(2, 8)\n IW = random.randint(2, 8)\n H = random.randint(IH + 1, 12)\n W = random.randint(IW + 1, 12)\n test_shape(N, C, IH, IW, H, W, mode, padding_mode, align_corners)\n\n # test smaller output\n N = random.randint(2, 8)\n C = random.randint(2, 8)\n IH = random.randint(2, 8)\n IW = random.randint(2, 8)\n H = random.randint(2, IH)\n W = random.randint(2, IW)\n test_shape(N, C, IH, IW, H, W, mode, padding_mode, align_corners)\n\n # test 1x1 inpput\n N = random.randint(2, 8)\n C = random.randint(2, 8)\n IH = 1\n IW = 1\n H = random.randint(2, 5)\n W = random.randint(2, 5)\n test_shape(N, C, IH, IW, H, W, mode, padding_mode, align_corners)\n\n # testing empty grid\n N = random.randint(2, 8)\n C = random.randint(2, 8)\n IH = random.randint(2, 8)\n IW = random.randint(2, 8)\n W = random.randint(3, IW + 2)\n test_shape(N, C, IH, IW, 0, W, mode, padding_mode, align_corners)\n\n # testing empty channel\n N = random.randint(2, 8)\n IH = random.randint(2, 8)\n IW = random.randint(2, 8)\n H = random.randint(3, IH + 2)\n W = random.randint(3, IW + 2)\n test_shape(N, 0, IH, IW, H, W, mode, padding_mode, align_corners)\n\n # testing empty batch\n C = random.randint(2, 8)\n IH = random.randint(2, 8)\n IW = random.randint(2, 8)\n H = random.randint(3, IH + 2)\n W = random.randint(3, IW + 2)\n test_shape(0, C, IH, IW, H, W, mode, padding_mode, align_corners)\n\n for mode in ('bilinear', 'nearest', 'bicubic'):\n for padding_mode in ('zeros', 'border', 'reflection'):\n for align_corners in (True, False):\n # test known input on CPU\n input = torch.arange(1., 11).view(1, 1, 2, 5)\n grid = torch.tensor(\n [[[-0.9, -4.1], [0, 0.2000], [1, -1], [-0.333, 1e-6], [0.5, 1.0]],\n [[-1.0, -0.5], [0, 0.3333], [1, -1], [-0.200, 1e-6], [1.5, 0.5]]]).view(1, 2, 5, 2)\n if mode == 'bilinear':\n if padding_mode == 'zeros':\n if align_corners:\n groundtruth = torch.tensor(\n [[0.0000, 6.0000000000, 5.0000, 4.8340, 9.0000],\n [2.2500, 6.3332500450, 5.0000, 5.1000, 0.0000]]).view(1, 1, 2, 5)\n else:\n groundtruth = torch.tensor(\n [[0.0000, 6.5000000000, 1.2500, 4.6675000191, 4.6250],\n [0.5000, 7.1665000916, 1.2500, 5.0000000000, 0.0000]]).view(1, 1, 2, 5)\n elif padding_mode == 'border':\n if align_corners:\n groundtruth = torch.tensor(\n [[1.2000, 6.0000000000, 5.0000, 4.8340, 9.0000],\n [2.2500, 6.3332500450, 5.0000, 5.1000, 8.7500]]).view(1, 1, 2, 5)\n else:\n groundtruth = torch.tensor(\n [[1.0000, 6.5000000000, 5.0000, 4.6675000191, 9.2500],\n [1.0000, 7.1665000916, 5.0000, 5.0000000000, 10.0000]]).view(1, 1, 2, 5)\n elif padding_mode == 'reflection':\n if align_corners:\n groundtruth = torch.tensor(\n [[3.4500, 6.0000000000, 5.0000, 4.8340, 9.0000],\n [2.2500, 6.3332500450, 5.0000, 5.1000, 7.7500]]).view(1, 1, 2, 5)\n else:\n groundtruth = torch.tensor(\n [[3.0000004768, 6.5000000000, 5.0000, 4.6675000191, 9.2500],\n [1.0000000000, 7.1665000916, 5.0000, 5.0000000000, 9.2500]]).view(1, 1, 2, 5)\n else:\n raise AssertionError(\"missing groundtruth test for padding mode '{}'\".format(padding_mode))\n elif mode == 'nearest':\n if padding_mode == 'zeros':\n if align_corners:\n groundtruth = torch.tensor(\n [[0., 8., 5., 7., 9.],\n [1., 8., 5., 8., 0.]]).view(1, 1, 2, 5)\n else:\n groundtruth = torch.tensor(\n [[0., 8., 5., 7., 0.],\n [1., 8., 5., 8., 0.]]).view(1, 1, 2, 5)\n elif padding_mode == 'border':\n if align_corners:\n groundtruth = torch.tensor(\n [[1., 8., 5., 7., 9.],\n [1., 8., 5., 8., 10.]]).view(1, 1, 2, 5)\n else:\n groundtruth = torch.tensor(\n [[1., 8., 5., 7., 9.],\n [1., 8., 5., 8., 10.]]).view(1, 1, 2, 5)\n elif padding_mode == 'reflection':\n if align_corners:\n groundtruth = torch.tensor(\n [[1., 8., 5., 7., 9.],\n [1., 8., 5., 8., 9.]]).view(1, 1, 2, 5)\n else:\n groundtruth = torch.tensor(\n [[1., 8., 5., 7., 9.],\n [1., 8., 5., 8., 9.]]).view(1, 1, 2, 5)\n else:\n raise AssertionError(\"missing groundtruth test for padding mode '{}'\".format(padding_mode))\n elif mode == 'bicubic':\n if padding_mode == 'zeros':\n if align_corners:\n groundtruth = torch.tensor(\n [[-0.10424726, 7.1400003, 5.0000, 5.7842274, 9.0000],\n [2.4492188, 7.4814040, 5.0000, 6.0277520, 0.0000]]).view(1, 1, 2, 5)\n else:\n groundtruth = torch.tensor(\n [[0.00000, 7.6287503, 1.0625, 5.5977230, 5.3270264],\n [0.40625, 8.0288770, 1.0625, 5.9375067, -0.3515625]]).view(1, 1, 2, 5)\n elif padding_mode == 'border':\n if align_corners:\n groundtruth = torch.tensor(\n [[1.1520010, 6.0599990, 5.0000, 4.870930, 9.0000000],\n [2.1328125, 6.4258375, 5.0000, 5.076003, 8.8671875]]).view(1, 1, 2, 5)\n else:\n groundtruth = torch.tensor(\n [[0.894531, 6.6050020, 4.625, 4.7138715, 9.800781],\n [0.906250, 7.2822485, 4.625, 5.0000052, 10.00000]]).view(1, 1, 2, 5)\n elif padding_mode == 'reflection':\n if align_corners:\n groundtruth = torch.tensor(\n [[3.1822524, 6.239998, 5.0000, 4.8709273, 9.00000],\n [1.7812500, 6.703594, 5.0000, 5.0760007, 8.21875]]).view(1, 1, 2, 5)\n else:\n groundtruth = torch.tensor(\n [[2.7993753, 6.6050020, 4.25, 4.7138715, 10.269531],\n [0.8125000, 7.2822485, 4.25, 5.0000052, 9.332031]]).view(1, 1, 2, 5)\n else:\n raise AssertionError(\"missing groundtruth test for padding mode '{}'\".format(padding_mode))\n\n else:\n raise AssertionError(\"missing groundtruth test for interpolation mode '{}'\".format(mode))\n output = F.grid_sample(input, grid, mode=mode, padding_mode=padding_mode,\n align_corners=align_corners)\n self.assertEqual(output, groundtruth, atol=1e-5, rtol=0,\n msg=\"groundtruth comparison failed for mode={}, \"\n \"padding_mode={}\".format(mode, padding_mode))\n\n # See NOTE [ grid_sample CPU fallback ]\n output = torch._grid_sampler_2d_cpu_fallback(\n input.float(), grid.float(),\n F.GRID_SAMPLE_INTERPOLATION_MODES[mode],\n F.GRID_SAMPLE_PADDING_MODES[padding_mode],\n align_corners)\n self.assertEqual(output, groundtruth.float(), atol=1e-5, rtol=0)\n\n # explicit check for gradient edge cases\n input = torch.arange(0., 5).expand((1, 1, 5, 5)).requires_grad_()\n grid = torch.tensor(\n [[[1.0, 1.0], [1.0, -1.0], [0.8, 0.8], [0.8, -0.8]],\n [[-1.0, -1.0], [-1.0, 1.0], [-0.8, -0.8], [-0.8, 0.8]]]).view(1, 2, 4, 2).requires_grad_()\n if mode == 'bilinear':\n if padding_mode == 'zeros':\n if align_corners:\n groundtruth = torch.tensor(\n [[[[-8., -8.], [-8., 0.], [2., 0.], [2., 0.]],\n [[2., 0.], [2., 0.], [2., 0.], [2., 0.]]]]).view(1, 2, 4, 2)\n else:\n groundtruth = torch.tensor(\n [[[[-5., -5.], [-5., 5.], [-10., -10.], [-10., 10.]],\n [[0., 0.], [0., 0.], [0., 0.], [0., 0.]]]]).view(1, 2, 4, 2)\n elif padding_mode == 'border':\n if align_corners:\n groundtruth = torch.tensor(\n [[[[-0., -0.], [-0., 0.], [2., 0.], [2., 0.]],\n [[0., 0.], [0., 0.], [2., 0.], [2., 0.]]]]).view(1, 2, 4, 2)\n else:\n groundtruth = torch.tensor(\n [[[[-0., -0.], [-0., 0.], [-0., -0.], [-0., 0.]],\n [[0., 0.], [0., 0.], [0., 0.], [0., 0.]]]]).view(1, 2, 4, 2)\n elif padding_mode == 'reflection':\n if align_corners:\n groundtruth = torch.tensor(\n [[[[-0., -0.], [-0., 0.], [2., 0.], [2., 0.]],\n [[0., 0.], [0., 0.], [2., 0.], [2., 0.]]]]).view(1, 2, 4, 2)\n else:\n groundtruth = torch.tensor(\n [[[[-0., -0.], [-0., 0.], [-0., -0.], [-0., 0.]],\n [[0., 0.], [0., 0.], [0., 0.], [0., 0.]]]]).view(1, 2, 4, 2)\n else:\n raise AssertionError(\"missing gradient groundtruth test for padding mode '{}'\".format(padding_mode))\n elif mode == 'nearest':\n groundtruth = torch.tensor(\n [[[[-0., -0.], [-0., 0.], [-0., -0.], [-0., 0.]],\n [[0., 0.], [0., 0.], [0., 0.], [0., 0.]]]]).view(1, 2, 4, 2)\n elif mode == 'bicubic':\n if padding_mode == 'zeros':\n if align_corners:\n groundtruth = torch.tensor(\n [[[[-4.5, -6.], [-4.5, 6.], [2.725679, 0.740878], [2.725679, -0.740878]],\n [[1.5, 0.], [1.5, 0.], [1.927921, -0.05688], [1.927921, 0.05688]]]]).view(1, 2, 4, 2)\n else:\n groundtruth = torch.tensor(\n [[[[-5.859375, -5.888672], [-5.859375, 5.888672], [-5.6250, -7.5000], [-5.6250, 7.5000]],\n [[-0.234375, -0.263672], [-0.234375, 0.263672], [1.8750, 0.], [1.8750, 0.]]]]\n ).view(1, 2, 4, 2)\n elif padding_mode == 'border':\n if align_corners:\n groundtruth = torch.tensor(\n [[[[1.5, 0.], [1.5, 0.], [1.74, 0.], [1.74, 0.]],\n [[1.5, 0.], [1.5, 0.], [1.74, 0.], [1.74, 0.]]]]).view(1, 2, 4, 2)\n else:\n groundtruth = torch.tensor(\n [[[[-0.46875, 0.], [-0.46875, 0.], [1.8750, 0.], [1.8750, 0.]],\n [[-0.46875, 0.], [-0.46875, 0.], [1.8750, 0.], [1.8750, 0.]]]]).view(1, 2, 4, 2)\n elif padding_mode == 'reflection':\n if align_corners:\n groundtruth = torch.tensor(\n [[[[0., 0.], [0., 0.], [1.92, 0.], [1.92, 0.]],\n [[0., 0.], [0., 0.], [1.92, 0.], [1.92, 0.]]]]).view(1, 2, 4, 2)\n else:\n groundtruth = torch.tensor(\n [[[[0., 0.], [0., 0.], [1.875, 0.], [1.875, 0.]],\n [[0., 0.], [0., 0.], [1.875, 0.], [1.875, 0.]]]]).view(1, 2, 4, 2)\n else:\n raise AssertionError(\"missing gradient groundtruth test for padding mode '{}'\".format(padding_mode))\n else:\n raise AssertionError(\"missing gradient groundtruth test for interpolation mode '{}'\".format(mode))\n F.grid_sample(input, grid, mode=mode, padding_mode=padding_mode,\n align_corners=align_corners).sum().backward()\n self.assertEqual(grid.grad, groundtruth, atol=1e-5, rtol=0,\n msg=\"gradient groundtruth comparison failed for mode={}, \"\n \"padding_mode={}\".format(mode, padding_mode))\n\n # See NOTE [ grid_sample CPU fallback ]\n grid.grad.zero_()\n torch._grid_sampler_2d_cpu_fallback(\n input.float(), grid.float(),\n F.GRID_SAMPLE_INTERPOLATION_MODES[mode],\n F.GRID_SAMPLE_PADDING_MODES[padding_mode],\n align_corners).sum().backward()\n self.assertEqual(grid.grad, groundtruth, atol=1e-5, rtol=0)\n\n # do gradcheck\n N = random.randint(2, 8)\n C = random.randint(2, 6)\n H = random.randint(2, 8)\n W = random.randint(2, 8)\n input = torch.randn(N, C, H, W, requires_grad=True)\n grid = torch.randn(N, H, W, 2, requires_grad=True)\n self.assertTrue(gradcheck(\n lambda inp, grid: F.grid_sample(inp, grid, mode=mode, padding_mode=padding_mode,\n align_corners=align_corners),\n (input, grid)))\n\n test(N, C, H, W, mode, padding_mode, align_corners=align_corners)\n if TEST_CUDNN:\n with cudnn.flags(enabled=False):\n test(N, C, H, W, mode, padding_mode, align_corners=align_corners)\n\n def test_grid_sample_3d(self):\n def test(N, C, D, H, W, mode, padding_mode, align_corners):\n def test_shape(N, C, ID, IH, IW, D, H, W, mode, padding_mode, align_corners):\n input_cpu = torch.randn(C, N, ID, IH, IW).transpose(0, 1).requires_grad_()\n grid_cpu = torch.randn(D, N, H, W, 3).transpose(0, 1).requires_grad_()\n out_cpu = F.grid_sample(input_cpu, grid_cpu, mode=mode, padding_mode=padding_mode,\n align_corners=align_corners)\n self.assertTrue(out_cpu.size() == torch.Size([N, C, D, H, W]))\n\n gradients = torch.randn_like(out_cpu)\n out_cpu.backward(gradients)\n\n if TEST_CUDA:\n input_cuda = input_cpu.detach().transpose(0, 1).cuda().transpose(0, 1).requires_grad_()\n grid_cuda = grid_cpu.detach().transpose(0, 1).cuda().transpose(0, 1).requires_grad_()\n out_cuda = F.grid_sample(input_cuda, grid_cuda, mode=mode, padding_mode=padding_mode,\n align_corners=align_corners)\n self.assertEqual(out_cpu, out_cuda)\n\n out_cuda.backward(gradients.cuda())\n self.assertEqual(input_cpu.grad, input_cuda.grad)\n self.assertEqual(grid_cpu.grad, grid_cuda.grad, atol=5e-5, rtol=0)\n\n # check that zero-dimensional input strides don't error out\n base_input = torch.randn(N, C, 1, IH, IW)\n input_cpu = base_input.expand_as(input_cuda).requires_grad_()\n grid_cpu = torch.randn(N, D, H, W, 3, requires_grad=True)\n out_cpu = F.grid_sample(input_cpu, grid_cpu, mode=mode, padding_mode=padding_mode,\n align_corners=align_corners)\n\n input_cuda = base_input.cuda().expand_as(input_cuda).requires_grad_()\n grid_cuda = grid_cpu.detach().cuda().requires_grad_()\n out_cuda = F.grid_sample(input_cuda, grid_cuda, mode=mode, padding_mode=padding_mode,\n align_corners=align_corners)\n self.assertEqual(out_cpu, out_cuda)\n\n # test same size output\n test_shape(N, C, D, H, W, D, H, W, mode, padding_mode, align_corners)\n\n # test larger output\n N = random.randint(2, 7)\n C = random.randint(2, 5)\n ID = random.randint(2, 7)\n IH = random.randint(2, 7)\n IW = random.randint(2, 7)\n D = random.randint(ID + 1, 10)\n H = random.randint(IH + 1, 10)\n W = random.randint(IW + 1, 10)\n test_shape(N, C, ID, IH, IW, D, H, W, mode, padding_mode, align_corners)\n\n # test smaller output\n N = random.randint(2, 7)\n C = random.randint(2, 5)\n ID = random.randint(2, 7)\n IH = random.randint(2, 7)\n IW = random.randint(2, 7)\n D = random.randint(2, ID)\n H = random.randint(2, IH)\n W = random.randint(2, IW)\n test_shape(N, C, ID, IH, IW, D, H, W, mode, padding_mode, align_corners)\n\n # test 1x1 inpput\n N = random.randint(2, 7)\n C = random.randint(2, 7)\n ID = 1\n IH = 1\n IW = 1\n H = random.randint(2, 5)\n W = random.randint(2, 5)\n test_shape(N, C, ID, IH, IW, D, H, W, mode, padding_mode, align_corners)\n\n # testing empty grid\n N = random.randint(2, 7)\n C = random.randint(2, 5)\n ID = random.randint(2, 7)\n IH = random.randint(2, 7)\n IW = random.randint(2, 7)\n D = random.randint(3, ID + 2)\n W = random.randint(3, IW + 2)\n test_shape(N, C, ID, IH, IW, D, 0, W, mode, padding_mode, align_corners)\n\n # testing empty channel\n N = random.randint(2, 7)\n ID = random.randint(2, 5)\n IH = random.randint(2, 7)\n IW = random.randint(2, 7)\n D = random.randint(3, ID + 2)\n H = random.randint(3, IH + 2)\n W = random.randint(3, IW + 2)\n test_shape(N, 0, ID, IH, IW, D, H, W, mode, padding_mode, align_corners)\n\n # testing empty batch\n C = random.randint(2, 5)\n ID = random.randint(2, 7)\n IH = random.randint(2, 7)\n IW = random.randint(2, 7)\n D = random.randint(3, ID + 2)\n H = random.randint(3, IH + 2)\n W = random.randint(3, IW + 2)\n test_shape(0, C, ID, IH, IW, D, H, W, mode, padding_mode, align_corners)\n\n for mode in ('bilinear', 'nearest'):\n for padding_mode in ('zeros', 'border', 'reflection'):\n for align_corners in (True, False):\n # do gradcheck\n N = random.randint(2, 5)\n C = random.randint(2, 4)\n D = random.randint(2, 5)\n H = random.randint(2, 5)\n W = random.randint(2, 5)\n input = torch.randn(N, C, D, H, W, requires_grad=True)\n grid = torch.randn(N, D, H, W, 3, requires_grad=True)\n self.assertTrue(gradcheck(\n lambda inp, grid: F.grid_sample(inp, grid, mode=mode, padding_mode=padding_mode,\n align_corners=align_corners),\n (input, grid)))\n\n test(N, C, D, H, W, mode, padding_mode, align_corners)\n\n def test_affine_grid(self):\n # test known input on CPU\n input = torch.arange(1., 7).view(1, 2, 3)\n output = F.affine_grid(input, torch.Size([1, 1, 2, 2]), align_corners=True)\n groundtruth = torch.Tensor(\n [[[0, -3], [2, 5]], [[4, 7], [6, 15]]]).view(1, 2, 2, 2)\n self.assertEqual(output, groundtruth)\n output = F.affine_grid(input, torch.Size([1, 1, 2, 2]), align_corners=False)\n groundtruth = torch.Tensor(\n [[[1.5, 1.5], [2.5, 5.5]], [[3.5, 6.5], [4.5, 10.5]]]).view(1, 2, 2, 2)\n self.assertEqual(output, groundtruth)\n\n for align_corners in (True, False):\n # do gradcheck\n N = random.randint(1, 8)\n C = random.randint(1, 8)\n H = random.randint(1, 8)\n W = random.randint(1, 8)\n sz = torch.Size([N, C, H, W])\n inp = torch.randn(N, 2, 3, requires_grad=True)\n with warnings.catch_warnings(record=True):\n warnings.simplefilter(\"always\") # python2 requires this so other tests can trigger\n self.assertTrue(gradcheck(\n lambda inp: F.affine_grid(inp, sz, align_corners=align_corners),\n (inp,)))\n\n # test CPU against CUDA\n if TEST_CUDA:\n N = random.randint(1, 8)\n C = random.randint(1, 8)\n H = random.randint(1, 8)\n W = random.randint(1, 8)\n sz = torch.Size([N, C, H, W])\n for align_corners in (True, False):\n input_cpu = torch.randn(N, 2, 3, requires_grad=True)\n with warnings.catch_warnings(record=True):\n warnings.simplefilter(\"always\") # python2 requires this so other tests can trigger\n out_cpu = F.affine_grid(input_cpu, sz, align_corners=align_corners)\n gradients = torch.randn(out_cpu.size())\n out_cpu.backward(gradients)\n input_gpu = input_cpu.detach().cuda().requires_grad_()\n with warnings.catch_warnings(record=True):\n warnings.simplefilter(\"always\") # python2 requires this so other tests can trigger\n out_cuda = F.affine_grid(input_gpu, sz, align_corners=align_corners)\n out_cuda.backward(gradients.cuda())\n self.assertEqual(out_cpu, out_cuda)\n self.assertEqual(input_cpu.grad, input_gpu.grad)\n\n def test_affine_grid_3d(self):\n # test known input on CPU\n input = torch.arange(1., 13).view(1, 3, 4)\n output = F.affine_grid(input, torch.Size([1, 1, 2, 2, 2]), align_corners=True)\n groundtruth = torch.Tensor(\n [[[[[-2, -10, -18], [0, 0, 0]], [[2, 2, 2], [4, 12, 20]]],\n [[[4, 4, 4], [6, 14, 22]], [[8, 16, 24], [10, 26, 42]]]]]).view(1, 2, 2, 2, 3)\n self.assertEqual(output, groundtruth)\n output = F.affine_grid(input, torch.Size([1, 1, 2, 2, 2]), align_corners=False)\n groundtruth = torch.Tensor(\n [[[[[1, -1, -3], [2, 4, 6]], [[3, 5, 7], [4, 10, 16]]],\n [[[4, 6, 8], [5, 11, 17]], [[6, 12, 18], [7, 17, 27]]]]]).view(1, 2, 2, 2, 3)\n self.assertEqual(output, groundtruth)\n\n for align_corners in (True, False):\n # do gradcheck\n N = random.randint(1, 8)\n C = random.randint(1, 8)\n D = random.randint(1, 8)\n H = random.randint(1, 8)\n W = random.randint(1, 8)\n sz = torch.Size([N, C, D, H, W])\n inp = torch.randn(N, 3, 4, requires_grad=True)\n with warnings.catch_warnings(record=True):\n warnings.simplefilter(\"always\") # python2 requires this so other tests can trigger\n self.assertTrue(gradcheck(\n lambda inp: F.affine_grid(inp, sz, align_corners=align_corners),\n (inp,)))\n\n # test CPU against CUDA\n if TEST_CUDA:\n N = random.randint(1, 8)\n C = random.randint(1, 8)\n D = random.randint(1, 8)\n H = random.randint(1, 8)\n W = random.randint(1, 8)\n sz = torch.Size([N, C, D, H, W])\n for align_corners in (True, False):\n input_cpu = torch.randn(N, 3, 4, requires_grad=True)\n with warnings.catch_warnings(record=True):\n warnings.simplefilter(\"always\") # python2 requires this so other tests can trigger\n out_cpu = F.affine_grid(input_cpu, sz, align_corners=align_corners)\n gradients = torch.randn(out_cpu.size())\n out_cpu.backward(gradients)\n input_gpu = input_cpu.detach().cuda().requires_grad_()\n with warnings.catch_warnings(record=True):\n warnings.simplefilter(\"always\") # python2 requires this so other tests can trigger\n out_cuda = F.affine_grid(input_gpu, sz, align_corners=align_corners)\n out_cuda.backward(gradients.cuda())\n self.assertEqual(out_cpu, out_cuda)\n self.assertEqual(input_cpu.grad, input_gpu.grad)\n\n def test_channel_shuffle(self):\n # 3D tensor\n x = torch.tensor(\n [[[1, 2],\n [5, 6],\n [9, 10],\n [13, 14],\n ]]\n )\n y_ref = torch.tensor(\n [[[1, 2],\n [9, 10],\n [5, 6],\n [13, 14],\n ]]\n )\n # ChannelsFirst\n y = F.channel_shuffle(x, 2)\n self.assertEqual(y, y_ref)\n # ChannelsLast not supported for 3dim\n\n # 4D tensor\n x = torch.tensor(\n [[[[1, 2],\n [3, 4]],\n [[5, 6],\n [7, 8]],\n [[9, 10],\n [11, 12]],\n [[13, 14],\n [15, 16]],\n ]]\n )\n y_ref = torch.tensor(\n [[[[1, 2],\n [3, 4]],\n [[9, 10],\n [11, 12]],\n [[5, 6],\n [7, 8]],\n [[13, 14],\n [15, 16]],\n ]]\n )\n # ChannelsFirst NCHW\n y = F.channel_shuffle(x, 2)\n self.assertEqual(y, y_ref)\n # ChannelsLast NHWC\n y = F.channel_shuffle(x.contiguous(memory_format=torch.channels_last), 2)\n y = y.contiguous(memory_format=torch.contiguous_format)\n self.assertEqual(y, y_ref)\n\n # 5D tensor\n x = torch.tensor(\n [[[[[1, 2],\n [3, 4]]],\n [[[5, 6],\n [7, 8]]],\n [[[9, 10],\n [11, 12]]],\n [[[13, 14],\n [15, 16]]],\n ]]\n )\n y_ref = torch.tensor(\n [[[[[1, 2],\n [3, 4]]],\n [[[9, 10],\n [11, 12]]],\n [[[5, 6],\n [7, 8]]],\n [[[13, 14],\n [15, 16]]],\n ]]\n )\n # ChannelsFirst NCHW\n y = F.channel_shuffle(x, 2)\n self.assertEqual(y, y_ref)\n # ChannelsLast NHWC\n y = F.channel_shuffle(x.contiguous(memory_format=torch.channels_last_3d), 2)\n y = y.contiguous(memory_format=torch.contiguous_format)\n self.assertEqual(y, y_ref)\n\n def test_upsamplingNearest1d(self):\n m = nn.Upsample(size=4, mode='nearest')\n in_t = torch.ones(1, 1, 2)\n in_uint8_t = torch.ones(1, 1, 2, dtype=torch.uint8)\n with warnings.catch_warnings(record=True) as w:\n out_t = m(in_t)\n out_uint8_t = m(in_t)\n self.assertEqual(torch.ones(1, 1, 4), out_t.data)\n # TODO(#38095): Replace assertEqualIgnoreType. See issue #38095\n self.assertEqualIgnoreType(torch.ones(1, 1, 4, dtype=torch.uint8), out_uint8_t.data)\n\n input = torch.randn(1, 1, 2, requires_grad=True)\n gradcheck(lambda x: F.interpolate(x, 4, mode='nearest'), [input])\n\n def test_upsamplingLinear1d(self):\n for align_corners in [True, False]:\n kwargs = dict(mode='linear', align_corners=align_corners)\n\n # test float scale factor up & downsampling\n for scale_factor in [0.5, 1.5, 2]:\n m = nn.Upsample(scale_factor=scale_factor, **kwargs)\n in_t = torch.ones(1, 1, 2)\n out_size = int(math.floor(in_t.shape[-1] * scale_factor))\n with warnings.catch_warnings(record=True) as w:\n out_t = m(in_t)\n self.assertEqual(torch.ones(1, 1, out_size), out_t.data)\n\n input = torch.randn(1, 1, 2, requires_grad=True)\n gradcheck(lambda x: F.interpolate(x, out_size, **kwargs), (input,))\n\n def test_upsamplingLinear1d_spatial_invariance(self):\n m = nn.Upsample(scale_factor=3, mode='linear', align_corners=False)\n in_t_9 = torch.zeros(1, 1, 9)\n in_t_9[:, :, :4].normal_()\n with warnings.catch_warnings(record=True) as w:\n out_t_9 = m(in_t_9)\n out_t_5 = m(in_t_9[:, :, :5])\n self.assertEqual(out_t_9[:, :, :15], out_t_5)\n\n def test_upsamplingNearest2d(self):\n for memory_format in [torch.contiguous_format, torch.channels_last]:\n m = nn.Upsample(size=4, mode='nearest')\n in_t = torch.ones(1, 2, 2, 2).contiguous(memory_format=memory_format)\n in_uint8_t = torch.ones(1, 2, 2, 2, dtype=torch.uint8).contiguous(memory_format=memory_format)\n with warnings.catch_warnings(record=True) as w:\n out_t = m(in_t)\n out_uint8_t = m(in_uint8_t)\n self.assertEqual(torch.ones(1, 2, 4, 4), out_t)\n self.assertEqual(torch.ones(1, 2, 4, 4, dtype=torch.uint8), out_uint8_t)\n # Assert that memory format is carried through to the output\n self.assertTrue(out_t.is_contiguous(memory_format=memory_format))\n\n # test forward when input's height is not same as width\n m = nn.Upsample(size=(4, 2), mode='nearest')\n in_t = torch.ones(1, 2, 2, 1).contiguous(memory_format=memory_format)\n with warnings.catch_warnings(record=True) as w:\n out_t = m(in_t)\n self.assertEqual(torch.ones(1, 2, 4, 2), out_t)\n self.assertTrue(out_t.is_contiguous(memory_format=memory_format))\n\n # test backward when input's height is not same as width\n input = torch.ones(1, 2, 2, 1, requires_grad=True).contiguous(memory_format=memory_format)\n gradcheck(lambda x: F.interpolate(x, size=(4, 2), mode='nearest'), [input])\n gradgradcheck(lambda x: F.interpolate(x, size=(4, 2), mode='nearest'), [input])\n\n input = torch.randn(1, 2, 2, 2, requires_grad=True).contiguous(memory_format=memory_format)\n self.assertEqual(\n F.interpolate(input, 4, mode='nearest'),\n F.interpolate(input, scale_factor=2, mode='nearest'))\n gradcheck(lambda x: F.interpolate(x, 4, mode='nearest'), [input])\n gradgradcheck(lambda x: F.interpolate(x, 4, mode='nearest'), [input])\n\n # Assert that cpu and cuda handle channels_last memory format in the same way\n # https://github.com/pytorch/pytorch/issues/54590\n if torch.cuda.is_available():\n a = torch.ones(2, 2, 3, 4, requires_grad=True).contiguous(memory_format=torch.channels_last)\n # make the data asymmetric; ensure that cuda/cpu handle channels_last appropriately.\n a[1][1][2][2] = a[1][1][2][3] = 0\n\n out_cpu = torch.nn.functional.interpolate(a, scale_factor=2, mode='nearest')\n out_cuda = torch.nn.functional.interpolate(a.to('cuda'), scale_factor=2, mode='nearest')\n self.assertEqual(out_cpu, out_cuda.to('cpu'))\n\n gradcheck(lambda x: F.interpolate(x, 4, mode='nearest'), [a])\n gradgradcheck(lambda x: F.interpolate(x, 4, mode='nearest'), [a])\n\n gradcheck(lambda x: F.interpolate(x, 4, mode='nearest'), [a.to('cuda')])\n gradgradcheck(lambda x: F.interpolate(x, 4, mode='nearest'), [a.to('cuda')])\n\n def test_upsamplingBilinear2d(self):\n for align_corners in [True, False]:\n kwargs = dict(mode='bilinear', align_corners=align_corners)\n\n for memory_format in [torch.contiguous_format, torch.channels_last]:\n\n # test float scale factor up & downsampling\n for scale_factor in [0.5, 1.5, 2]:\n m = nn.Upsample(scale_factor=scale_factor, **kwargs)\n in_t = torch.ones(1, 2, 2, 2).contiguous(memory_format=memory_format)\n out_size = int(math.floor(in_t.shape[-1] * scale_factor))\n with warnings.catch_warnings(record=True) as w:\n out_t = m(in_t)\n self.assertEqual(torch.ones(1, 2, out_size, out_size), out_t.data)\n # Assert that memory format is carried through to the output\n self.assertTrue(out_t.is_contiguous(memory_format=memory_format))\n\n input = torch.randn(1, 2, 2, 2, requires_grad=True)\n gradcheck(lambda x: F.interpolate(x, out_size, **kwargs), [input])\n\n def test_upsamplingBicubic2d(self):\n # test output against known input: align_corners=False result must match opencv\n in_t = torch.arange(8.).view(1, 2, 2, 2)\n expected_out_t = torch.Tensor(\n [[[[-0.31641, 0.01562, 0.56250, 0.89453],\n [0.34766, 0.67969, 1.22656, 1.55859],\n [1.44141, 1.77344, 2.32031, 2.65234],\n [2.10547, 2.43750, 2.98438, 3.31641]],\n\n [[3.68359, 4.01562, 4.56250, 4.89453],\n [4.34766, 4.67969, 5.22656, 5.55859],\n [5.44141, 5.77344, 6.32031, 6.65234],\n [6.10547, 6.43750, 6.98438, 7.31641]]]])\n out_t = F.interpolate(in_t, scale_factor=2, mode='bicubic', align_corners=False)\n torch.set_printoptions(precision=5)\n # TODO(#38095): Replace assertEqualIgnoreType. See issue #38095\n self.assertEqualIgnoreType(out_t, expected_out_t, atol=1e-5, rtol=0)\n\n\n device_list = ['cpu']\n if TEST_CUDA:\n device_list.append('cuda')\n\n for align_corners in [True, False]:\n kwargs = dict(mode='bicubic', align_corners=align_corners)\n # test float scale factor up & downsampling\n for device in device_list:\n for scale_factor in [0.5, 1, 1.5, 2]:\n in_t = torch.ones(2, 2, 2, 2).to(device)\n out_t = F.interpolate(in_t, scale_factor=scale_factor, **kwargs)\n out_size = int(math.floor(in_t.shape[-1] * scale_factor))\n self.assertEqual(torch.ones(2, 2, out_size, out_size), out_t.data,\n atol=1e-5, rtol=0)\n\n input = torch.randn(2, 2, 2, 2, requires_grad=True)\n gradcheck(lambda x: F.interpolate(x, out_size, **kwargs), [input])\n\n def test_upsampling_not_recompute_scale_factor(self):\n # test output against known input: result must match opencv\n in_t = torch.arange(8.).view(1, 2, 2, 2)\n expected_out_t = torch.Tensor(\n [[[[-0.32725, -0.08843, 0.37933, 0.79744],\n [0.15039, 0.38921, 0.85697, 1.27508],\n [1.08591, 1.32473, 1.79249, 2.21060],\n [1.92213, 2.16095, 2.62871, 3.04682]],\n\n [[3.67275, 3.91157, 4.37933, 4.79744],\n [4.15039, 4.38921, 4.85697, 5.27508],\n [5.08591, 5.32473, 5.79249, 6.21060],\n [5.92213, 6.16095, 6.62871, 7.04682]]]])\n if IS_PPC:\n # Both OpenCV and PyTorch give a slightly different result on PPC\n expected_out_t = torch.Tensor(\n [[[[-0.32725, -0.08843, 0.37933, 0.79744],\n [0.15039, 0.38921, 0.85697, 1.27508],\n [1.08591, 1.32473, 1.79249, 2.21060],\n [1.92212, 2.16094, 2.62870, 3.04681]],\n\n [[3.67275, 3.91157, 4.37933, 4.79743],\n [4.15039, 4.38921, 4.85697, 5.27508],\n [5.08591, 5.32473, 5.79249, 6.21059],\n [5.92212, 6.16094, 6.62870, 7.04680]]]])\n out_t = F.interpolate(in_t, scale_factor=2.3, mode='bicubic', align_corners=False, recompute_scale_factor=False)\n torch.set_printoptions(precision=5)\n # TODO(#38095): Replace assertEqualIgnoreType. See issue #38095\n self.assertEqualIgnoreType(out_t, expected_out_t, atol=1e-4, rtol=0)\n\n device_list = ['cpu']\n if TEST_CUDA:\n device_list.append('cuda')\n\n for align_corners in [True, False]:\n kwargs = dict(mode='bicubic', align_corners=align_corners)\n # test float scale factor up & downsampling\n for device in device_list:\n for scale_factor in [0.6, 1.6, 2.3]:\n in_t = torch.ones(2, 2, 2, 2).to(device)\n out_t = F.interpolate(in_t, scale_factor=scale_factor, **kwargs)\n out_size = int(math.floor(in_t.shape[-1] * scale_factor))\n self.assertEqual(torch.ones(2, 2, out_size, out_size), out_t.data, atol=1e-5, rtol=0)\n\n input = torch.randn(2, 2, 2, 2, requires_grad=True)\n gradcheck(lambda x: F.interpolate(x, out_size, **kwargs), [input])\n\n def test_upsamplingBilinear2d_spatial_invariance(self):\n m = nn.Upsample(scale_factor=3, mode='bilinear', align_corners=False)\n in_t_9 = torch.zeros(1, 1, 9, 9)\n in_t_9[:, :, :4, :4].normal_()\n with warnings.catch_warnings(record=True) as w:\n out_t_9 = m(in_t_9)\n out_t_5 = m(in_t_9[:, :, :5, :5])\n self.assertEqual(out_t_9[:, :, :15, :15], out_t_5)\n\n def test_upsamplingNearest3d(self):\n for memory_format in [torch.contiguous_format, torch.channels_last_3d]:\n m = nn.Upsample(size=4, mode='nearest')\n in_t = torch.ones(1, 2, 2, 2, 2).contiguous(memory_format=memory_format)\n in_uint8_t = torch.ones(1, 2, 2, 2, 2, dtype=torch.uint8).contiguous(memory_format=memory_format)\n with warnings.catch_warnings(record=True) as w:\n out_t = m(in_t)\n out_uint8_t = m(in_uint8_t)\n self.assertEqual(torch.ones(1, 2, 4, 4, 4), out_t)\n self.assertEqual(torch.ones(1, 2, 4, 4, 4, dtype=torch.uint8), out_uint8_t)\n # Assert that memory format is carried through to the output\n self.assertTrue(out_t.is_contiguous(memory_format=memory_format))\n\n input = torch.randn(1, 2, 2, 2, 2, requires_grad=True).contiguous(memory_format=memory_format)\n gradcheck(lambda x: F.interpolate(x, 4, mode='nearest'), [input])\n\n # Assert that cpu and cuda handle channels_last memory format in the same way\n # https://github.com/pytorch/pytorch/issues/54590\n if torch.cuda.is_available():\n a = torch.ones(2, 2, 2, 3, 4, requires_grad=True).contiguous(memory_format=torch.channels_last_3d)\n # make the data asymmetric; ensure that cuda/cpu handle channels_last appropriately.\n a[1][1][1][2][2] = a[1][1][1][2][3] = 0\n\n out_cpu = torch.nn.functional.interpolate(a, scale_factor=2, mode='nearest')\n out_cuda = torch.nn.functional.interpolate(a.to('cuda'), scale_factor=2, mode='nearest')\n self.assertEqual(out_cpu, out_cuda.to('cpu'))\n\n gradcheck(lambda x: F.interpolate(x, 4, mode='nearest'), [a])\n gradgradcheck(lambda x: F.interpolate(x, 4, mode='nearest'), [a])\n\n gradcheck(lambda x: F.interpolate(x, 4, mode='nearest'), [a.to('cuda')])\n gradgradcheck(lambda x: F.interpolate(x, 4, mode='nearest'), [a.to('cuda')])\n\n def test_upsamplingTrilinear3d(self):\n for align_corners in [True, False]:\n kwargs = dict(mode='trilinear', align_corners=align_corners)\n\n for memory_format in [torch.contiguous_format, torch.channels_last_3d]:\n # test float scale factor up & downsampling\n for scale_factor in [0.5, 1.5, 2]:\n m = nn.Upsample(scale_factor=scale_factor, **kwargs)\n in_t = torch.ones(1, 2, 2, 2, 2).contiguous(memory_format=memory_format)\n out_size = int(math.floor(in_t.shape[-1] * scale_factor))\n with warnings.catch_warnings(record=True) as w:\n out_t = m(in_t)\n self.assertEqual(torch.ones(1, 2, out_size, out_size, out_size), out_t.data)\n # Assert that memory format is carried through to the output\n self.assertTrue(out_t.is_contiguous(memory_format=memory_format))\n\n input = torch.randn(1, 2, 2, 2, 2, requires_grad=True)\n self.assertEqual(\n F.interpolate(input, (out_size, out_size, out_size), **kwargs),\n F.interpolate(input, scale_factor=scale_factor, **kwargs))\n gradcheck(lambda x: F.interpolate(x, out_size, **kwargs), [input])\n gradgradcheck(lambda x: F.interpolate(x, out_size, **kwargs), [input])\n\n def test_upsamplingTrilinear3d_spatial_invariance(self):\n m = nn.Upsample(scale_factor=3, mode='trilinear', align_corners=False)\n in_t_9 = torch.zeros(1, 1, 9, 9, 9)\n in_t_9[:, :, :4, :4, :4].normal_()\n with warnings.catch_warnings(record=True) as w:\n out_t_9 = m(in_t_9)\n out_t_5 = m(in_t_9[:, :, :5, :5, :5])\n self.assertEqual(out_t_9[:, :, :15, :15, :15], out_t_5)\n\n @unittest.skipIf(not TEST_CUDA, \"CUDA unavailable\")\n def test_interpolate_illegal_memory_access(self):\n in_s = 45\n out_s = 14\n\n input = torch.ones((1, 1, in_s), device='cuda', requires_grad=True)\n # note we allocated grad_output to be larger so out of bound access\n # woudl be visible in grad_input\n grad = torch.ones((1, 1, out_s * 2), device='cuda', requires_grad=True)\n grad = grad[:, :, :out_s]\n\n input_ref = input.detach().cpu().requires_grad_()\n grad_ref = grad.cpu()\n\n out = F.interpolate(input, size=(out_s,), mode='nearest')\n out.backward(grad)\n\n out_ref = F.interpolate(input_ref, size=(out_s,), mode='nearest')\n out_ref.backward(grad_ref)\n\n self.assertEqual(out_ref, out)\n self.assertEqual(input_ref.grad, input.grad)\n\n def test_interpolate(self):\n def _test_interpolate_helper(in_t, scale_factor, layer):\n out_size = int(math.floor(in_t.shape[-1] * scale_factor))\n dim = len(in_t.shape) - 2\n out_shape = [1, 1] + [out_size] * dim\n with warnings.catch_warnings(record=True) as w:\n out_t = layer(in_t)\n self.assertEqual(torch.ones(out_shape), out_t)\n\n self.assertEqual(\n F.interpolate(in_t, (out_size,) * dim, **kwargs),\n F.interpolate(in_t, scale_factor=scale_factor, **kwargs))\n gradcheck(lambda x: F.interpolate(x, out_size, **kwargs), [in_t])\n gradgradcheck(lambda x: F.interpolate(x, out_size, **kwargs), [in_t])\n\n def _make_input(dim, device):\n size = [1, 1]\n size += [2] * dim\n return torch.ones(size, requires_grad=True, device=device)\n\n device_list = ['cpu']\n if TEST_CUDA:\n device_list.append('cuda')\n\n for device in device_list:\n for scale_factor in [0.5, 1.5, 2]:\n for mode in ['nearest', 'area']:\n kwargs = dict(mode=mode)\n m = nn.Upsample(scale_factor=scale_factor, **kwargs).to(device)\n for input in [_make_input(1, device), _make_input(2, device), _make_input(3, device)]:\n _test_interpolate_helper(input, scale_factor, m)\n\n for align_corners in [True, False]:\n kwargs = dict(mode='linear', align_corners=align_corners)\n m = nn.Upsample(scale_factor=scale_factor, **kwargs).to(device)\n _test_interpolate_helper(_make_input(1, device), scale_factor, m)\n\n kwargs = dict(mode='bilinear', align_corners=align_corners)\n m = nn.Upsample(scale_factor=scale_factor, **kwargs).to(device)\n _test_interpolate_helper(_make_input(2, device), scale_factor, m)\n\n kwargs = dict(mode='bicubic', align_corners=align_corners)\n\n def m(t):\n return F.interpolate(t, scale_factor=scale_factor, **kwargs).to(device)\n _test_interpolate_helper(_make_input(2, device), scale_factor, m)\n\n kwargs = dict(mode='trilinear', align_corners=align_corners)\n m = nn.Upsample(scale_factor=scale_factor, **kwargs).to(device)\n _test_interpolate_helper(_make_input(3, device), scale_factor, m)\n\n def test_linear_broadcasting(self):\n m = nn.Linear(5, 8)\n inp = torch.randn(2, 3, 5)\n expected = m(inp.view(6, 5)).view(2, 3, 8)\n self.assertEqual(expected, m(inp))\n\n def test_bilinear(self):\n module = nn.Bilinear(10, 10, 8)\n input1 = torch.randn(4, 10, requires_grad=True)\n input2 = torch.randn(4, 10, requires_grad=True)\n grad_output = torch.randn(4, 8)\n\n res = module(input1, input2)\n expected = (torch.einsum(\"bi,kij,bj->bk\", input1, module.weight, input2) +\n module.bias)\n self.assertEqual(res, expected)\n grads = torch.autograd.grad(res, [module.weight, module.bias, input1, input2], grad_output)\n grads_expected = torch.autograd.grad(expected, [module.weight, module.bias, input1, input2], grad_output)\n for g, ge in zip(grads, grads_expected):\n self.assertEqual(g, ge)\n\n def test_bilinear_no_bias(self):\n module = nn.Bilinear(10, 10, 8)\n module_no_bias = nn.Bilinear(10, 10, 8, False)\n\n module.bias.data.zero_()\n module.weight.data.copy_(module_no_bias.weight)\n\n input1 = torch.randn(4, 10, requires_grad=True)\n input2 = torch.randn(4, 10, requires_grad=True)\n grad_output = torch.randn(4, 8)\n\n def run(net):\n input1.grad = input2.grad = None\n output = net(input1, input2)\n output.backward(grad_output)\n\n return output.data, input1.grad.data, input2.grad.data\n\n out, g1, g2 = run(module)\n out_nb, g1_nb, g2_nb = run(module_no_bias)\n\n self.assertEqual(out, out_nb)\n self.assertEqual(g1, g1_nb)\n self.assertEqual(g2, g2_nb)\n\n _assertGradAndGradgradChecks(self,\n lambda x1, x2: F.bilinear(x1, x2, module_no_bias.weight, module_no_bias.bias),\n (input1, input2))\n\n def test_bilinear_broadcasting(self):\n m = nn.Bilinear(5, 6, 8)\n input1 = torch.randn(2, 3, 5)\n input2 = torch.randn(2, 3, 6)\n expected = m(input1.view(6, 5), input2.view(6, 6)).view(2, 3, 8)\n self.assertEqual(expected, m(input1, input2))\n\n def test_conv_tbc(self):\n inp = torch.randn(9, 4, 5, requires_grad=True)\n weight = torch.randn(3, 5, 6, requires_grad=True)\n bias = torch.randn(6, requires_grad=True)\n\n gradcheck(lambda i, w, b, pad: F.conv_tbc(i, w, b, pad), (inp, weight, bias, 3))\n\n def run_conv_double_back_test(self, kern, stride, padding, chan_in, chan_out, batch_size,\n inp_size, dilation, no_weight, groups=1, use_cuda=False,\n use_bias=True, dtype=torch.double):\n if use_cuda:\n device = torch.device(\"cuda\")\n else:\n device = torch.device(\"cpu\")\n\n x = torch.randn(batch_size, chan_in, inp_size, inp_size, device=device,\n dtype=dtype, requires_grad=True)\n weight = torch.randn(chan_out, chan_in // groups, kern, kern, device=device,\n dtype=dtype, requires_grad=not no_weight)\n if use_bias:\n bias = torch.randn(chan_out, device=device, dtype=dtype, requires_grad=True)\n else:\n bias = None\n\n def func(*inputs):\n if use_bias:\n lx, lweight, lbias = inputs\n else:\n lx, lweight = inputs\n lbias = None\n # We disable cudnn during forward to avoid finite difference imprecision issues\n with cudnn.flags(enabled=False):\n out = F.conv2d(lx, lweight, lbias, stride, padding, dilation, groups)\n return out\n\n if use_bias:\n inputs = x, weight, bias\n else:\n inputs = x, weight\n\n dummy_out = func(*inputs)\n grad_y = torch.randn_like(dummy_out, device=device, dtype=dtype, requires_grad=True)\n\n # Issue #15353: test mkldnn double backward, don't run gradgradcheck due\n # to imprecision issues\n if dtype == torch.float:\n g, = torch.autograd.grad(dummy_out.sum(), x, create_graph=True)\n return g.requires_grad\n\n return gradgradcheck(func, inputs, (grad_y,))\n\n @unittest.skipIf(not TEST_CUDA, \"CUDA unavailable\")\n @unittest.skipIf(not TEST_CUDNN, \"needs cudnn\")\n @skipIfRocm\n def test_grouped_conv_cudnn_nhwc_support(self):\n # in order to catch the hols in grouped convolution in nhwc support for earlier cudnn version\n input = torch.randn((16, 16, 8, 8), dtype=torch.float16, device=\"cuda\").to(memory_format=torch.channels_last)\n weight = torch.randn((8, 4, 3, 3), dtype=torch.float16, device=\"cuda\").to(memory_format=torch.channels_last)\n out = torch.cudnn_convolution(input, weight, None, (1, 1), (1, 1), (1, 1), 4, False, False)\n input = torch.randn((16, 8, 8, 8), dtype=torch.float16, device=\"cuda\").to(memory_format=torch.channels_last)\n out = torch.cudnn_convolution_transpose(input, weight, None, (1, 1), (0, 0), (1, 1), (1, 1), 4, False, False)\n\n @unittest.expectedFailure\n @unittest.skipIf(not TEST_CUDA, \"CUDA unavailable\")\n @unittest.skipIf(not TEST_CUDNN, \"needs cudnn\")\n def test_conv_cudnn_memory_layout_dominance(self):\n # desired behavior here is to have the memory_layout of conv.weight to\n # dominante the layout of output.\n # which is not the same as current behavior, we'll fix this in\n # following up PRs and remove the `expectedFailure` tag\n input = torch.randint(1, 10, (2, 8, 4, 4), dtype=torch.float32, device=\"cuda\", requires_grad=True)\n conv = nn.Conv2d(8, 4, 3).cuda().float()\n\n out = conv(input)\n self.assertTrue(out.is_contiguous())\n\n input = input.contiguous(memory_format=torch.channels_last)\n out = conv(input)\n self.assertTrue(out.is_contiguous())\n\n conv.weight.data = conv.weight.contiguous(memory_format=torch.channels_last)\n out = conv(input)\n self.assertTrue(out.is_contiguous(memory_format=torch.channels_last))\n\n input = input.contiguous()\n out = conv(input)\n self.assertTrue(out.is_contiguous(memory_format=torch.channels_last))\n\n def test_conv_double_backward(self):\n batch_size = 2\n for kern, inp_size, dilations in [(3, 6, [1, 2]), (3, 7, [1]), (4, 9, [1])]:\n for stride, padding, chan_in, chan_out, dilation in \\\n product([1, 2], [0, 1, 2], [2], [3], dilations):\n for no_weight in (True, False):\n for dtype in (torch.float, torch.double):\n result = self.run_conv_double_back_test(kern, stride,\n padding, chan_in, chan_out,\n batch_size, inp_size, dilation,\n no_weight, dtype=dtype)\n self.assertTrue(result,\n \"Conv double backward test failed with parameters:\" +\n \"\\nkern: \" + str(kern) +\n \"\\nstride: \" + str(stride) +\n \"\\npadding: \" + str(padding) +\n \"\\nchan_in: \" + str(chan_in) +\n \"\\nchan_out: \" + str(chan_out) +\n \"\\nbatch_size: \" + str(batch_size) +\n \"\\ninp_size: \" + str(inp_size) +\n \"\\ndilation: \" + str(dilation) +\n \"\\ndtype: \" + str(dtype))\n\n def test_conv_double_backward_no_bias(self):\n kern = 3\n stride = 2\n chan_in, chan_out = 2, 4\n batch_size = 2\n inp_size = 5\n padding = 1\n dilation = 1\n no_weight = False\n use_bias = True\n result = self.run_conv_double_back_test(kern, stride,\n padding, chan_in, chan_out,\n batch_size, inp_size, dilation,\n no_weight, use_bias=use_bias)\n self.assertTrue(result,\n \"Conv double backward test failed with parameters:\" +\n \"\\nkern: \" + str(kern) +\n \"\\nstride: \" + str(stride) +\n \"\\npadding: \" + str(padding) +\n \"\\nchan_in: \" + str(chan_in) +\n \"\\nchan_out: \" + str(chan_out) +\n \"\\nbatch_size: \" + str(batch_size) +\n \"\\ninp_size: \" + str(inp_size) +\n \"\\ndilation: \" + str(dilation))\n\n def test_conv_double_backward_groups(self):\n kern = 3\n stride = 1\n padding = 2\n chan_in, chan_out = 2, 4\n batch_size = 2\n inp_size = 6\n dilation = 1\n no_weight = False\n groups = 2\n result = self.run_conv_double_back_test(kern, stride,\n padding, chan_in * groups, chan_out * groups,\n batch_size, inp_size, dilation,\n no_weight, groups=groups)\n self.assertTrue(result,\n \"Conv double backward test failed with parameters:\" +\n \"\\nkern: \" + str(kern) +\n \"\\nstride: \" + str(stride) +\n \"\\npadding: \" + str(padding) +\n \"\\nchan_in: \" + str(chan_in) +\n \"\\nchan_out: \" + str(chan_out) +\n \"\\nbatch_size: \" + str(batch_size) +\n \"\\ninp_size: \" + str(inp_size) +\n \"\\ndilation: \" + str(dilation) +\n \"\\ngroups: \" + str(groups))\n\n def test_conv_double_backward_stride(self):\n batch_size = 2\n\n # Cannot provide ggW when stride is > 1\n for kern, inp_size, dilations in [(3, 5, [1, 2]), (3, 7, [1])]:\n for stride, padding, chan_in, chan_out, dilation in product([2], [0, 1], [1], [2], dilations):\n no_weight = False\n self.run_conv_double_back_test(kern, stride,\n padding, chan_in, chan_out,\n batch_size, inp_size, dilation,\n no_weight)\n\n @unittest.skipIf(not TEST_CUDA, \"CUDA unavailable\")\n def test_cudnn_noncontiguous_weight(self):\n # Noncontiguous weights must be contiguous() before being\n # passed to cuDNN\n input = torch.tensor([1, 1, 1], dtype=torch.double, device=\"cuda\").view(1, 1, 3)\n weights1 = torch.tensor([1], dtype=torch.double, device=\"cuda\").expand(1, 1, 2)\n weights2 = torch.tensor([1], dtype=torch.double, device=\"cuda\").expand(1, 1, 2).contiguous()\n self.assertEqual(F.conv1d(input, weights1, bias=None, stride=2, dilation=2),\n F.conv1d(input, weights2, bias=None, stride=2, dilation=2))\n\n @unittest.skipIf(not TEST_CUDA, \"CUDA unavailable\")\n @repeat_test_for_types(DOUBLE_TENSORTYPES)\n def test_conv_double_backward_cuda(self, dtype=torch.double):\n # Double backward only runs with DoubleTensor due to precison reason\n batch_size = 1\n for kern, inp_size, dilations in [(3, 5, [1, 2]), (4, 9, [1])]:\n for stride, padding, chan_in, chan_out, dilation in product([1], [2], [2], [3], dilations):\n no_weight = stride == 2\n result = self.run_conv_double_back_test(kern, stride,\n padding, chan_in, chan_out,\n batch_size, inp_size, dilation,\n no_weight, use_cuda=True, dtype=dtype)\n self.assertTrue(result,\n \"Conv double backward test failed with parameters:\" +\n \"\\nkern: \" + str(kern) +\n \"\\nstride: \" + str(stride) +\n \"\\npadding: \" + str(padding) +\n \"\\nchan_in: \" + str(chan_in) +\n \"\\nchan_out: \" + str(chan_out) +\n \"\\nbatch_size: \" + str(batch_size) +\n \"\\ninp_size: \" + str(inp_size) +\n \"\\ndilation: \" + str(dilation))\n\n def run_grad_conv_test(self, func_forward, func_backward, dim=1, gradient='input'):\n for kern, inp_size in [(3, 6), (3, 7), (4, 9)]:\n for batch, stride, padding, chan_in, chan_out, dilation in \\\n product([1, 2], [1, 2], [0, 1, 2], [2], [3], [1]):\n\n for has_bias in [True, False]:\n input_shape = [batch, chan_in]\n weight_shape = [chan_out, chan_in]\n for _ in range(dim):\n input_shape.append(inp_size)\n weight_shape.append(kern)\n\n input = torch.randn(input_shape, requires_grad=True)\n weight = torch.randn(weight_shape, requires_grad=True)\n if has_bias:\n bias = torch.randn([chan_out], requires_grad=True)\n output = func_forward(input, weight, stride=stride, padding=padding, dilation=dilation, bias=bias)\n\n gradient_o = torch.randn(output.shape)\n gradient_w = torch.autograd.grad(output, input if (gradient == 'input') else weight, gradient_o)\n\n self.assertEqual(gradient_w[0],\n func_backward(\n input_shape if (gradient == 'input') else input,\n weight_shape if (gradient == 'weight') else weight,\n gradient_o,\n stride=stride,\n padding=padding,\n dilation=dilation))\n\n def test_grad_conv1d_input(self):\n self.run_grad_conv_test(F.conv1d, F.grad.conv1d_input, 1, 'input')\n\n def test_grad_conv1d_weight(self):\n self.run_grad_conv_test(F.conv1d, F.grad.conv1d_weight, 1, 'weight')\n\n def test_grad_conv2d_input(self):\n self.run_grad_conv_test(F.conv2d, F.grad.conv2d_input, 2, 'input')\n\n def test_grad_conv2d_weight(self):\n self.run_grad_conv_test(F.conv2d, F.grad.conv2d_weight, 2, 'weight')\n\n def test_grad_conv3d_input(self):\n self.run_grad_conv_test(F.conv3d, F.grad.conv3d_input, 3, 'input')\n\n def test_grad_conv3d_weight(self):\n self.run_grad_conv_test(F.conv3d, F.grad.conv3d_weight, 3, 'weight')\n\n @unittest.skipIf(not torch._nnpack_available(), \"NNPACK unavailable\")\n def test_nnpack_conv(self):\n for kern, inp_size in [(3, 6), (3, 7), (4, 9)]:\n for batch, stride, padding, chan_in, chan_out in \\\n product([1, 2, 3, 4], [1, 2], [0, 1, 2], [2], [3]):\n\n for has_bias in [True, False]:\n input_shape = [batch, chan_in]\n weight_shape = [chan_out, chan_in]\n for _ in range(2):\n input_shape.append(inp_size)\n weight_shape.append(kern)\n\n input = torch.randn(input_shape, requires_grad=True, dtype=torch.float)\n weight = torch.randn(weight_shape, requires_grad=True, dtype=torch.float)\n if has_bias:\n bias = torch.randn([chan_out], requires_grad=True, dtype=torch.float)\n output = torch._nnpack_spatial_convolution(input, weight, stride=stride, padding=padding, bias=bias)\n output_expected = torch.nn.functional.conv2d(input, weight, stride=stride, padding=padding, bias=bias)\n self.assertEqual(output, output_expected, atol=3e-4, rtol=0)\n\n gradient_o = torch.randn(output.shape, dtype=torch.float)\n\n grads = torch.autograd.grad(output, [input, weight], gradient_o)\n grads_expected = torch.autograd.grad(output_expected, [input, weight], gradient_o)\n for gr, gr_expected in zip(grads, grads_expected):\n self.assertEqual(gr, gr_expected, atol=3e-4, rtol=0)\n\n def test_fold_invalid_arg(self):\n # input wrong dimension\n\n fold = nn.Fold(output_size=(4, 5), kernel_size=(2, 3))\n with self.assertRaisesRegex(NotImplementedError, r\"Only 3D input Tensors are supported\"):\n fold(torch.randn(1, 5))\n\n # input.size(1) not divisible by \\prod(kernel_size)\n\n fold = nn.Fold(output_size=(4, 5), kernel_size=(2, 3))\n with self.assertRaisesRegex(RuntimeError, r\"be divisible by the product of kernel_size\"):\n fold(torch.randn(1, 5, 9))\n\n with self.assertRaisesRegex(RuntimeError, r\"be divisible by the product of kernel_size\"):\n fold(torch.randn(1, 19, 9))\n\n # input.size(2) not matching the total number of sliding blocks\n\n with self.assertRaisesRegex(RuntimeError, r\"match the calculated number of sliding blocks\"):\n fold = nn.Fold(output_size=(4, 5), kernel_size=(2, 3))\n fold(torch.randn(1, 6, 10))\n\n with self.assertRaisesRegex(RuntimeError, r\"match the calculated number of sliding blocks\"):\n fold = nn.Fold(output_size=(4, 5), kernel_size=(2, 3), stride=(2, 2))\n fold(torch.randn(1, 6, 5))\n\n with self.assertRaisesRegex(RuntimeError, r\"match the calculated number of sliding blocks\"):\n fold = nn.Fold(output_size=(4, 5), kernel_size=(2, 3), stride=(2, 2), dilation=(1, 2), padding=(2, 0))\n fold(torch.randn(1, 6, 5)) # should be 4 * 1 = 4 sliding blocks\n\n def test_unfold_invalid_arg(self):\n # input wrong dimension\n\n unfold = nn.Unfold(kernel_size=(2, 3))\n with self.assertRaisesRegex(NotImplementedError, r\"Only 4D input Tensors are supported\"):\n unfold(torch.randn(1, 5, 2))\n\n # calculated output shape is too small\n\n with self.assertRaisesRegex(RuntimeError, r\"too small \\(non-positive\\)\"):\n unfold = nn.Unfold(kernel_size=(2, 3))\n unfold(torch.randn(1, 2, 2, 2))\n\n with self.assertRaisesRegex(RuntimeError, r\"too small \\(non-positive\\)\"):\n unfold = nn.Unfold(kernel_size=(5, 3), padding=(1, 1))\n unfold(torch.randn(1, 2, 2, 3))\n\n with self.assertRaisesRegex(RuntimeError, r\"too small \\(non-positive\\)\"):\n unfold = nn.Unfold(kernel_size=(1, 3), padding=(1, 1), dilation=(1, 2))\n unfold(torch.randn(1, 2, 2, 2))\n\n def test_conv_padding_mode(self):\n with self.assertRaisesRegex(ValueError, \"padding_mode must be one of\"):\n nn.Conv2d(3, 3, 3, padding_mode=\"xyz\")\n\n with self.assertRaisesRegex(ValueError, \"padding_mode must be one of\"):\n nn.Conv2d(3, 3, 3, padding_mode=3)\n\n with self.assertRaisesRegex(ValueError, \"Only \\\"zeros\\\" \"):\n nn.ConvTranspose2d(3, 3, 3, padding_mode=\"reflect\")\n\n def test_softmin(self):\n x = torch.randn(2, 16)\n self.assertEqual(F.softmin(x, 1), F.softmax(-x, 1))\n self.assertEqual(F.softmin(x, 0), F.softmax(-x, 0))\n\n def test_log_softmax_cpu(self, dtype=torch.bfloat16):\n inputf = torch.rand(32, 100, device=\"cpu\", dtype=torch.float, requires_grad=True)\n input = inputf.to(dtype).detach().requires_grad_(True)\n outf = F.log_softmax(inputf, dim=-1)\n out = F.log_softmax(input, dim=-1)\n self.assertEqual(out.dtype, dtype)\n # TODO(#38095): Replace assertEqualIgnoreType. See issue #38095\n self.assertEqualIgnoreType(out, outf, atol=0.1, rtol=0)\n\n out.sum().backward()\n outf.sum().backward()\n self.assertEqual(input.grad.dtype, dtype)\n self.assertEqual(input.grad, inputf.grad.to(dtype), atol=0.1, rtol=0)\n\n def test_adaptive_log_softmax(self):\n # args validation\n with self.assertRaises(ValueError):\n _ = nn.AdaptiveLogSoftmaxWithLoss(16, 20, [5, 15, 15], div_value=2.)\n\n with self.assertRaises(ValueError):\n _ = nn.AdaptiveLogSoftmaxWithLoss(16, 20, [5, 15, 10], div_value=2.)\n\n with self.assertRaises(ValueError):\n _ = nn.AdaptiveLogSoftmaxWithLoss(16, 20, [5, 10, 25], div_value=2.)\n\n with self.assertRaisesRegex(ValueError, \"cutoffs should be a sequence of unique,\"):\n _ = nn.AdaptiveLogSoftmaxWithLoss(16, 20, [5, 10, 20], div_value=2.)\n\n # not raise\n _ = nn.AdaptiveLogSoftmaxWithLoss(16, 20, [5, 10, 19], div_value=2.)\n\n # input shapes\n with self.assertRaisesRegex(RuntimeError, r\"Input and target should have the same size\"):\n asfm = nn.AdaptiveLogSoftmaxWithLoss(16, 20, [5, 10, 15], div_value=2.)\n x = torch.randn(2, 16)\n y = torch.tensor([0, 5, 10])\n asfm(x, y)\n\n # out-of-bound targets\n with self.assertRaisesRegex(RuntimeError, r\"Target values should be in\"):\n asfm = nn.AdaptiveLogSoftmaxWithLoss(16, 20, [5, 10, 15], div_value=2.)\n x = torch.randn(2, 16)\n y = torch.tensor([0, 20])\n asfm(x, y)\n\n # cluster sizes\n asfm = nn.AdaptiveLogSoftmaxWithLoss(16, 20, [5, 10, 15], div_value=2.)\n x = torch.randn(2, 16)\n y = torch.tensor([0, 17])\n\n self.assertEqual(asfm.head.weight.size(), (5 + 3, 16)) # 5 targets in head, 3 clusters, dimensionality 16\n self.assertEqual(asfm.tail[0][1].weight.size(), (5, 8)) # 5 targets in this cluster, dimensionality 8\n self.assertEqual(asfm.tail[1][1].weight.size(), (5, 4))\n self.assertEqual(asfm.tail[2][1].weight.size(), (5, 2))\n\n self.assertEqual(asfm(x, y).output.size(), (2, ))\n\n # log_probs actually returns log_proba\n asfm = nn.AdaptiveLogSoftmaxWithLoss(8, 4, [2], div_value=2.)\n x = torch.randn(4, 8)\n logprob_out = asfm.log_prob(x)\n\n self.assertEqual(torch.exp(logprob_out).data.sum(1), torch.ones(4))\n\n # forward returns the same thing as log_probs\n for v in [0, 1, 2, 3]:\n y = torch.full((4,), v, dtype=torch.long)\n out, loss = asfm(x, y)\n\n self.assertEqual(out, logprob_out.gather(1, y.unsqueeze(1)).squeeze())\n self.assertEqual(loss, F.nll_loss(logprob_out, y))\n\n # predict\n x = torch.randn(64, 8).abs_()\n\n # argmax in shortlist\n asfm = nn.AdaptiveLogSoftmaxWithLoss(8, 10, [4, 8], div_value=2., head_bias=True)\n asfm.head.weight.data.abs_()\n asfm.head.bias.data.abs_()\n asfm.head.weight.data[asfm.shortlist_size:, :].zero_()\n\n out = asfm.predict(x)\n self.assertEqual(out, asfm.log_prob(x).argmax(dim=1))\n\n # argmax outside of shortlist\n asfm = nn.AdaptiveLogSoftmaxWithLoss(8, 10, [4, 8], div_value=2., head_bias=True)\n asfm.head.weight.data.abs_()\n asfm.head.bias.data.abs_()\n asfm.head.weight.data[:asfm.shortlist_size, :].zero_()\n\n out = asfm.predict(x)\n self.assertEqual(out, asfm.log_prob(x).argmax(dim=1))\n\n # half of the argmax in shortlist, half in clusters\n asfm = nn.AdaptiveLogSoftmaxWithLoss(8, 10, [4, 8], div_value=2., head_bias=True)\n asfm.head.weight.data.abs_()\n asfm.head.bias.data.abs_()\n\n x[:32, :asfm.shortlist_size].zero_()\n x[32:, asfm.shortlist_size:].zero_()\n\n asfm.head.weight.data[:asfm.shortlist_size, asfm.shortlist_size:].zero_()\n asfm.head.weight.data[asfm.shortlist_size:, :asfm.shortlist_size].zero_()\n\n out = asfm.predict(x)\n self.assertEqual(out, asfm.log_prob(x).argmax(dim=1))\n\n def test_cross_entropy_loss(self, dtype=torch.bfloat16):\n loss_cpu = nn.CrossEntropyLoss().cpu()\n inputf = torch.randn(15, 10, device=\"cpu\", dtype=torch.float, requires_grad=True)\n input = inputf.to(dtype).detach().requires_grad_(True)\n target = torch.empty(15, dtype=torch.long).random_(10)\n\n outf = loss_cpu(inputf, target)\n out = loss_cpu(input, target)\n self.assertEqual(out.dtype, dtype)\n # TODO(#38095): Replace assertEqualIgnoreType. See issue #38095\n self.assertEqualIgnoreType(out, outf, atol=1e-1, rtol=0)\n\n outf.backward()\n out.backward()\n self.assertEqual(input.grad.dtype, dtype)\n # TODO(#38095): Replace assertEqualIgnoreType. See issue #38095\n self.assertEqualIgnoreType(input.grad, inputf.grad, atol=1e-1, rtol=0)\n\n @unittest.skipIf(not torch.cuda.is_available(), \"CUDA not available\")\n def test_convert_sync_batchnorm(self):\n module = torch.nn.Sequential(\n torch.nn.BatchNorm1d(100),\n torch.nn.InstanceNorm1d(100)\n ).cuda()\n\n # necessary to have an anchor point for comparison, in case the\n # convert_sync_batchnorm updates in place\n comp_module = torch.nn.Sequential(\n torch.nn.BatchNorm1d(100),\n torch.nn.InstanceNorm1d(100)\n ).cuda()\n comp_module.load_state_dict(module.state_dict())\n\n sync_bn_module = torch.nn.SyncBatchNorm.convert_sync_batchnorm(module)\n children = list(sync_bn_module.children())\n self.assertEqual(children[0].__class__, torch.nn.SyncBatchNorm)\n self.assertEqual(children[1].__class__, torch.nn.InstanceNorm1d)\n\n for layer, converted_layer in zip(comp_module.children(), sync_bn_module.children()):\n for key in layer.state_dict().keys():\n self.assertEqual(layer.state_dict()[key].device, converted_layer.state_dict()[key].device)\n self.assertEqual(layer.state_dict()[key], converted_layer.state_dict()[key])\n\n def test_functional_grad_conv(self):\n # Conv 1D\n input = torch.randn(1, 1, 5, requires_grad=True)\n weight = torch.randn(1, 1, 3, requires_grad=True)\n output = F.conv1d(input, weight, dilation=2)\n grad_output = torch.randn(output.shape)\n\n grad_input_autograd = torch.autograd.grad(output, input, grad_output)[0]\n grad_input_functional = torch.nn.grad.conv1d_input(input.shape, weight, grad_output, dilation=2)\n self.assertEqual(grad_input_functional, grad_input_autograd)\n\n # Conv 2D\n input = torch.randn(1, 1, 5, 5, requires_grad=True)\n weight = torch.randn(1, 1, 3, 3, requires_grad=True)\n output = F.conv2d(input, weight, dilation=2)\n grad_output = torch.randn(output.shape)\n\n grad_input_autograd = torch.autograd.grad(output, input, grad_output)[0]\n grad_input_functional = torch.nn.grad.conv2d_input(input.shape, weight, grad_output, dilation=2)\n self.assertEqual(grad_input_functional, grad_input_autograd)\n\n # Conv 3D\n input = torch.randn(1, 1, 5, 5, 5, requires_grad=True)\n weight = torch.randn(1, 1, 3, 3, 3, requires_grad=True)\n output = F.conv3d(input, weight, dilation=2)\n grad_output = torch.randn(output.shape)\n\n grad_input_autograd = torch.autograd.grad(output, input, grad_output)[0]\n grad_input_functional = torch.nn.grad.conv3d_input(input.shape, weight, grad_output, dilation=2)\n self.assertEqual(grad_input_functional, grad_input_autograd)\n\n # Warning for _grad_input_padding\n with warnings.catch_warnings(record=True) as w:\n torch.nn.grad._grad_input_padding(torch.rand(1, 2, 3), [1, 2, 5], (1,), (0,), (3,))\n self.assertEqual(len(w), 1)\n\n def test_flatten(self):\n tensor_input = torch.randn(2, 1, 2, 3)\n\n # Flatten Tensor\n\n flatten = nn.Flatten(start_dim=1, end_dim=-1)\n tensor_output = flatten(tensor_input)\n self.assertEqual(tensor_output.size(), torch.Size([2, 6]))\n\n def test_unflatten(self):\n tensor_input = torch.randn(2, 50)\n\n # Unflatten Tensor (unflattened_size as a tuple of ints and list of ints)\n\n for us in ((2, 5, 5), [2, 5, 5]):\n unflatten = nn.Unflatten(dim=1, unflattened_size=us)\n tensor_output = unflatten(tensor_input)\n self.assertEqual(tensor_output.size(), torch.Size([2, 2, 5, 5]))\n\n # Unflatten NamedTensor\n\n unflatten = nn.Unflatten(dim='features', unflattened_size=(('C', 2), ('H', 5), ('W', 5)))\n named_tensor_input = tensor_input.refine_names('N', 'features')\n named_tensor_output = unflatten(named_tensor_input)\n self.assertEqual(named_tensor_output.size(), torch.Size([2, 2, 5, 5]))\n\n def test_unflatten_invalid_arg(self):\n # Wrong type for unflattened_size (tuple of floats)\n\n with self.assertRaisesRegex(\n TypeError,\n r\"unflattened_size must be tuple of ints, but found element of type float at pos 2\"):\n nn.Unflatten(dim=1, unflattened_size=(2, 5, 5.0))\n\n # Wrong type for unflattened_size (list of lists and list of tuples)\n for us in ([['C', 2], ['W', 5], ['H', 5]], [('C', 2), ('W', 5), ('H', 5)]):\n with self.assertRaisesRegex(\n TypeError,\n r\"unflattened_size must be a tuple of tuples, but found type list\"):\n nn.Unflatten(dim='features', unflattened_size=us)\n\n # Wrong type for unflattened_size (tuple of lists)\n\n with self.assertRaisesRegex(\n TypeError,\n r\"unflattened_size must be tuple of tuples, but found element of type list at pos 0\"):\n nn.Unflatten(dim='features', unflattened_size=(['C', 2], ['W', 5], ['H', 5]))\n\n # Wrong type for unflattened_size (tuple of dicts)\n\n with self.assertRaisesRegex(\n TypeError,\n r\"unflattened_size must be tuple of tuples, but found element of type dict at pos 0\"):\n nn.Unflatten(dim='features', unflattened_size=({'C': 2}, {'W': 5}, {'H': 5}))\n\n def test_layer_norm_grads_with_create_graph_flag(self):\n atol = 1e-5\n rtol = 1e-3\n\n x = torch.randn((4, 4, 16), requires_grad=True)\n layer_norm = nn.LayerNorm((16,), 1e-5, True)\n with torch.no_grad():\n layer_norm.weight = torch.nn.Parameter(0.1 * torch.ones_like(layer_norm.weight))\n\n grads1 = torch.autograd.grad(layer_norm(x).sum(), x, create_graph=False)[0]\n grads2 = torch.autograd.grad(layer_norm(x).sum(), x, create_graph=True)[0]\n\n self.assertTrue(torch.allclose(grads1, grads2, rtol, atol))\n\n if TEST_CUDA:\n x = x.to('cuda')\n layer_norm = layer_norm.to('cuda')\n\n grads1 = torch.autograd.grad(layer_norm(x).sum(), x, create_graph=False)[0]\n grads2 = torch.autograd.grad(layer_norm(x).sum(), x, create_graph=True)[0]\n\n self.assertTrue(torch.allclose(grads1, grads2, rtol, atol))\n\n def test_padding_list(self):\n # Padding can be a list, or tuple (regression test for gh-54452)\n x = torch.randn(4, 8, 32, 32)\n net = torch.nn.ConvTranspose2d(8, 16, kernel_size=3, padding=[3, 3])\n y = net(x)\n\n net = torch.nn.ConvTranspose2d(8, 16, kernel_size=3, padding=(3, 3))\n y = net(x)\n\n\nclass TestNNInit(TestCase):\n def setUp(self):\n super(TestNNInit, self).setUp()\n random.seed(123)\n\n def _is_normal(self, tensor, mean, std):\n samples = tensor.view(-1).tolist()\n p_value = stats.kstest(samples, 'norm', args=(mean, std))[1]\n return p_value > 0.0001\n\n def _is_trunc_normal(self, tensor, mean, std, a, b):\n # scipy's trunc norm is suited for data drawn from N(0, 1),\n # so we need to transform our data to test it using scipy.\n z_samples = (tensor.view(-1) - mean) / std\n z_samples = z_samples.tolist()\n a0 = (a - mean) / std\n b0 = (b - mean) / std\n p_value = stats.kstest(z_samples, 'truncnorm', args=(a0, b0))[1]\n return p_value > 0.0001\n\n def _is_uniform(self, tensor, a, b):\n samples = tensor.view(-1).tolist()\n p_value = stats.kstest(samples, 'uniform', args=(a, (b - a)))[1]\n return p_value > 0.0001\n\n def _create_random_nd_tensor(self, dims, size_min, size_max):\n size = [random.randint(size_min, size_max) for _ in range(dims)]\n tensor = torch.zeros(size)\n return tensor\n\n def _random_float(self, a, b):\n return (b - a) * random.random() + a\n\n def test_calculate_gain_linear(self):\n for fn in ['linear', 'conv1d', 'conv2d', 'conv3d', 'conv_transpose2d', 'conv_transpose2d', 'conv_transpose3d']:\n gain = init.calculate_gain(fn)\n self.assertEqual(gain, 1)\n\n def test_calculate_gain_nonlinear(self):\n for fn in ['sigmoid', 'tanh', 'relu', 'leaky_relu']:\n gain = init.calculate_gain(fn)\n if fn == 'sigmoid':\n self.assertEqual(gain, 1)\n elif fn == 'tanh': # 5 / 3\n self.assertEqual(gain, 1.6666666666666667)\n elif fn == 'relu': # sqrt(2)\n self.assertEqual(gain, 1.4142135623730951)\n elif fn == 'leaky_relu': # sqrt(2 / 1 + slope^2))\n self.assertEqual(gain, 1.4141428569978354)\n elif fn == 'selu':\n self.assertEqual(gain, 0.75)\n\n def test_calculate_gain_leaky_relu(self):\n for param in [None, 0, 0.01, 10]:\n gain = init.calculate_gain('leaky_relu', param)\n if param is None: # Default slope is 0.01\n self.assertEqual(gain, 1.4141428569978354)\n elif param == 0: # No slope = same gain as normal ReLU\n self.assertEqual(gain, 1.4142135623730951)\n elif param == 0.01:\n self.assertEqual(gain, 1.4141428569978354)\n elif param == 10:\n self.assertEqual(gain, 0.14071950894605836)\n\n def test_calculate_gain_leaky_relu_only_accepts_numbers(self):\n for param in [True, [1], {'a': 'b'}]:\n with self.assertRaises(ValueError):\n init.calculate_gain('leaky_relu', param)\n\n def test_calculate_gain_only_accepts_valid_nonlinearities(self):\n for n in [2, 5, 25]:\n # Generate random strings of lengths that definitely aren't supported\n random_string = ''.join([random.choice(string.ascii_lowercase) for i in range(n)])\n with self.assertRaises(ValueError):\n init.calculate_gain(random_string)\n\n @unittest.skipIf(not TEST_SCIPY, \"Scipy not found.\")\n def test_uniform(self):\n for dims in [1, 2, 4]:\n input_tensor = self._create_random_nd_tensor(dims, size_min=30, size_max=50)\n a = self._random_float(-3, 3)\n b = a + self._random_float(1, 5)\n init.uniform_(input_tensor, a=a, b=b)\n assert self._is_uniform(input_tensor, a, b)\n\n @unittest.skipIf(not TEST_SCIPY, \"Scipy not found.\")\n def test_normal(self):\n for dims in [1, 2, 4]:\n input_tensor = self._create_random_nd_tensor(dims, size_min=30, size_max=50)\n mean = self._random_float(-3, 3)\n std = self._random_float(1, 5)\n init.normal_(input_tensor, mean=mean, std=std)\n\n assert self._is_normal(input_tensor, mean, std)\n\n @unittest.skipIf(not TEST_SCIPY, \"Scipy not found.\")\n def test_trunc_normal(self):\n for dims in [1, 2, 4]:\n input_tensor = self._create_random_nd_tensor(dims, size_min=30, size_max=50)\n mean = self._random_float(-3, 3)\n std = self._random_float(.01, 1)\n a = self._random_float(mean - 2 * std, mean)\n b = self._random_float(mean, mean + 2 * std)\n init.trunc_normal_(input_tensor, mean=mean, std=std, a=a, b=b)\n\n assert self._is_trunc_normal(input_tensor, mean, std, a, b)\n\n def test_constant(self):\n for dims in [1, 2, 4]:\n input_tensor = self._create_random_nd_tensor(dims, size_min=1, size_max=5)\n val = self._random_float(1, 10)\n init.constant_(input_tensor, val)\n\n self.assertEqual(input_tensor, input_tensor.clone().fill_(val))\n\n def test_ones_and_zeros(self):\n for init_fn_, val in zip([init.ones_, init.zeros_], [1, 0]):\n for dims in [1, 2, 4]:\n input_tensor = self._create_random_nd_tensor(dims, size_min=1, size_max=5)\n init_fn_(input_tensor)\n\n self.assertEqual(input_tensor, input_tensor.clone().fill_(val))\n\n def test_eye(self):\n input_tensor = self._create_random_nd_tensor(2, size_min=1, size_max=5)\n init.eye_(input_tensor)\n\n # Check every single element\n for i in range(input_tensor.size(0)):\n for j in range(input_tensor.size(1)):\n if i == j:\n assert input_tensor[i][j] == 1\n else:\n assert input_tensor[i][j] == 0\n\n def test_eye_only_works_on_2d_inputs(self):\n for dims in [1, 3]:\n with self.assertRaises(ValueError):\n tensor = self._create_random_nd_tensor(dims, size_min=1, size_max=3)\n init.eye_(tensor)\n\n def test_max_unpool(self):\n # Test 1D\n output, indices = F.max_pool1d(torch.randn([1, 1, 4]), 2, stride=2, return_indices=True)\n self.assertEqual(F.max_unpool1d(output, indices, 2), F.max_unpool1d(output, indices, 2, stride=2))\n\n # Test list / tuple passed as argument to max_unpool1d\n input = torch.randn([1, 1, 5])\n output, indices = F.max_pool1d(input, 2, stride=2, return_indices=True)\n self.assertEqual(F.max_unpool1d(output, indices, 2, stride=2, output_size=input.shape),\n F.max_unpool1d(output, indices, 2, stride=2, output_size=input.size()))\n\n # Test 2D\n output, indices = F.max_pool2d(torch.randn([1, 1, 4, 4]), 2, stride=2, return_indices=True)\n self.assertEqual(F.max_unpool2d(output, indices, 2), F.max_unpool2d(output, indices, 2, stride=2))\n\n # Test 3D\n output, indices = F.max_pool3d(torch.randn([4, 4, 4, 4, 4]), 2, stride=2, return_indices=True)\n self.assertEqual(F.max_unpool3d(output, indices, 2), F.max_unpool3d(output, indices, 2, stride=2))\n\n def test_dirac_properties(self):\n for dims in [3, 4, 5]:\n for groups in [1, 2, 3]:\n # prepare random tensor with random sizes, but fits groups\n a, c, d, e = (random.randint(1, 5) for _ in range(4))\n b = random.randint(1, 5 * groups) # same range as a*groups but all range allowed\n # make sure first dim divides by groups\n input_tensor = torch.randn((a * groups, b, c, d, e)[:dims])\n\n init.dirac_(input_tensor, groups)\n\n c_out, c_in = input_tensor.size(0) // groups, input_tensor.size(1)\n min_d = min(c_out, c_in)\n # Check number of nonzeros is equivalent to smallest dim (for each group)\n assert torch.nonzero(input_tensor).size(0) == min_d * groups\n # Check sum of values (can have precision issues, hence assertEqual) is also equivalent\n self.assertEqual(input_tensor.sum(), min_d * groups)\n\n\n def test_dirac_identity(self):\n for groups in [1, 3]:\n batch, in_c, out_c, size, kernel_size = 8, 3, 9, 5, 3 # in_c, out_c must divide by groups\n eff_out_c = out_c // groups\n\n # Test 1D\n input_var = torch.randn(batch, in_c, size)\n filter_var = torch.zeros(eff_out_c, in_c, kernel_size)\n filter_var = torch.cat([filter_var] * groups)\n init.dirac_(filter_var, groups)\n output_var = F.conv1d(input_var, filter_var)\n input_tensor, output_tensor = input_var.data, output_var.data # Variables do not support nonzero\n for g in range(groups):\n # Assert in_c outputs are preserved (per each group)\n self.assertEqual(input_tensor[:, :, 1:-1],\n output_tensor[:, eff_out_c * g:eff_out_c * g + in_c, :])\n # Assert extra outputs are 0\n assert torch.nonzero(output_tensor[:, eff_out_c * g + in_c:eff_out_c * (g + 1), :]).numel() == 0\n\n # Test 2D\n input_var = torch.randn(batch, in_c, size, size)\n filter_var = torch.zeros(eff_out_c, in_c, kernel_size, kernel_size)\n filter_var = torch.cat([filter_var] * groups)\n init.dirac_(filter_var, groups)\n output_var = F.conv2d(input_var, filter_var)\n input_tensor, output_tensor = input_var.data, output_var.data # Variables do not support nonzero\n for g in range(groups):\n # Assert in_c outputs are preserved (per each group)\n self.assertEqual(input_tensor[:, :, 1:-1, 1:-1],\n output_tensor[:, eff_out_c * g:eff_out_c * g + in_c, :, :])\n # Assert extra outputs are 0\n assert torch.nonzero(output_tensor[:, eff_out_c * g + in_c:eff_out_c * (g + 1), :, :]).numel() == 0\n\n # Test 3D\n input_var = torch.randn(batch, in_c, size, size, size)\n filter_var = torch.zeros(eff_out_c, in_c, kernel_size, kernel_size, kernel_size)\n filter_var = torch.cat([filter_var] * groups)\n init.dirac_(filter_var, groups)\n output_var = F.conv3d(input_var, filter_var)\n input_tensor, output_tensor = input_var.data, output_var.data\n for g in range(groups):\n # Assert in_c outputs are preserved (per each group)\n self.assertEqual(input_tensor[:, :, 1:-1, 1:-1, 1:-1],\n output_tensor[:, eff_out_c * g:eff_out_c * g + in_c, :, :, :])\n # Assert extra outputs are 0\n assert torch.nonzero(output_tensor[:, eff_out_c * g + in_c:eff_out_c * (g + 1), :, :, :]).numel() == 0\n\n def test_dirac_only_works_on_3_4_5d_inputs(self):\n for dims in [1, 2, 6]:\n with self.assertRaises(ValueError):\n tensor = self._create_random_nd_tensor(dims, size_min=1, size_max=3)\n init.dirac_(tensor)\n\n def test_xavier_uniform_errors_on_inputs_smaller_than_2d(self):\n for dims in [0, 1]:\n tensor = self._create_random_nd_tensor(dims, size_min=1, size_max=1)\n with self.assertRaises(ValueError):\n init.xavier_uniform_(tensor)\n\n def test_xavier_normal_errors_on_inputs_smaller_than_2d(self):\n for dims in [0, 1]:\n tensor = self._create_random_nd_tensor(dims, size_min=1, size_max=1)\n with self.assertRaises(ValueError):\n init.xavier_normal_(tensor)\n\n @unittest.skipIf(not TEST_SCIPY, \"Scipy not found.\")\n def test_xavier_uniform(self):\n for use_gain in [True, False]:\n for dims in [2, 4]:\n input_tensor = self._create_random_nd_tensor(dims, size_min=20, size_max=25)\n gain = 1\n\n if use_gain:\n gain = self._random_float(0.1, 2)\n init.xavier_uniform_(input_tensor, gain=gain)\n else:\n init.xavier_uniform_(input_tensor)\n\n fan_in = input_tensor.size(1)\n fan_out = input_tensor.size(0)\n if input_tensor.dim() > 2:\n fan_in *= input_tensor[0, 0].numel()\n fan_out *= input_tensor[0, 0].numel()\n\n expected_std = gain * math.sqrt(2.0 / (fan_in + fan_out))\n bounds = expected_std * math.sqrt(3)\n assert self._is_uniform(input_tensor, -bounds, bounds)\n\n @unittest.skipIf(not TEST_SCIPY, \"Scipy not found.\")\n def test_xavier_normal(self):\n for use_gain in [True, False]:\n for dims in [2, 4]:\n input_tensor = self._create_random_nd_tensor(dims, size_min=20, size_max=25)\n gain = 1\n\n if use_gain:\n gain = self._random_float(0.1, 2)\n init.xavier_normal_(input_tensor, gain=gain)\n else:\n init.xavier_normal_(input_tensor)\n\n fan_in = input_tensor.size(1)\n fan_out = input_tensor.size(0)\n if input_tensor.dim() > 2:\n fan_in *= input_tensor[0, 0].numel()\n fan_out *= input_tensor[0, 0].numel()\n\n expected_std = gain * math.sqrt(2.0 / (fan_in + fan_out))\n assert self._is_normal(input_tensor, 0, expected_std)\n\n def test_kaiming_uniform_errors_on_inputs_smaller_than_2d(self):\n for dims in [0, 1]:\n with self.assertRaises(ValueError):\n tensor = self._create_random_nd_tensor(dims, size_min=1, size_max=1)\n init.kaiming_uniform_(tensor)\n\n def test_kaiming_normal_errors_on_inputs_smaller_than_2d(self):\n for dims in [0, 1]:\n with self.assertRaises(ValueError):\n tensor = self._create_random_nd_tensor(dims, size_min=1, size_max=1)\n init.kaiming_normal_(tensor)\n\n @unittest.skipIf(not TEST_SCIPY, \"Scipy not found.\")\n def test_kaiming_uniform(self):\n for use_a in [True, False]:\n for dims in [2, 4]:\n for mode in ['fan_in', 'fan_out']:\n input_tensor = self._create_random_nd_tensor(dims, size_min=20, size_max=25)\n if use_a:\n a = self._random_float(0.1, 2)\n init.kaiming_uniform_(input_tensor, a=a, mode=mode)\n else:\n a = 0\n init.kaiming_uniform_(input_tensor, mode=mode)\n\n fan_in = input_tensor.size(1)\n fan_out = input_tensor.size(0)\n if input_tensor.dim() > 2:\n fan_in *= input_tensor[0, 0].numel()\n fan_out *= input_tensor[0, 0].numel()\n\n if mode == 'fan_in':\n n = fan_in\n else:\n n = fan_out\n\n expected_std = math.sqrt(2.0 / ((1 + a**2) * n))\n bounds = expected_std * math.sqrt(3.0)\n assert self._is_uniform(input_tensor, -bounds, bounds)\n\n @unittest.skipIf(not TEST_SCIPY, \"Scipy not found.\")\n def test_kaiming_normal(self):\n for use_a in [True, False]:\n for dims in [2, 4]:\n for mode in ['fan_in', 'fan_out']:\n input_tensor = self._create_random_nd_tensor(dims, size_min=20, size_max=25)\n if use_a:\n a = self._random_float(0.1, 2)\n init.kaiming_normal_(input_tensor, a=a, mode=mode)\n else:\n a = 0\n init.kaiming_normal_(input_tensor, mode=mode)\n\n fan_in = input_tensor.size(1)\n fan_out = input_tensor.size(0)\n if input_tensor.dim() > 2:\n fan_in *= input_tensor[0, 0].numel()\n fan_out *= input_tensor[0, 0].numel()\n\n if mode == 'fan_in':\n n = fan_in\n else:\n n = fan_out\n\n expected_std = math.sqrt(2.0 / ((1 + a**2) * n))\n assert self._is_normal(input_tensor, 0, expected_std)\n\n def test_sparse_only_works_on_2d_inputs(self):\n for dims in [1, 3]:\n with self.assertRaises(ValueError):\n sparsity = self._random_float(0.1, 0.9)\n tensor = self._create_random_nd_tensor(dims, size_min=1, size_max=3)\n init.sparse_(tensor, sparsity)\n\n @unittest.skipIf(not TEST_SCIPY, \"Scipy not found.\")\n def test_sparse_default_std(self):\n for use_random_std in [True, False]:\n input_tensor = self._create_random_nd_tensor(2, size_min=30, size_max=35)\n rows, cols = input_tensor.size(0), input_tensor.size(1)\n sparsity = self._random_float(0.1, 0.2)\n\n std = 0.01 # default std\n if use_random_std:\n std = self._random_float(0.01, 0.2)\n init.sparse_(input_tensor, sparsity=sparsity, std=std)\n else:\n init.sparse_(input_tensor, sparsity=sparsity)\n\n for col_idx in range(input_tensor.size(1)):\n column = input_tensor[:, col_idx]\n assert column[column == 0].nelement() >= math.ceil(sparsity * rows)\n\n assert self._is_normal(input_tensor[input_tensor != 0], 0, std)\n\n @skipIfNoLapack\n def test_orthogonal(self):\n for use_gain in [True, False]:\n for tensor_size in [[3, 4], [4, 3], [20, 2, 3, 4], [2, 3, 4, 5]]:\n input_tensor = torch.zeros(tensor_size)\n gain = 1.0\n\n if use_gain:\n gain = self._random_float(0.1, 2)\n init.orthogonal_(input_tensor, gain=gain)\n else:\n init.orthogonal_(input_tensor)\n\n rows, cols = tensor_size[0], reduce(mul, tensor_size[1:])\n flattened_tensor = input_tensor.view(rows, cols)\n if rows > cols:\n self.assertEqual(torch.mm(flattened_tensor.t(), flattened_tensor),\n torch.eye(cols) * gain ** 2, atol=1e-6, rtol=0)\n else:\n self.assertEqual(torch.mm(flattened_tensor, flattened_tensor.t()),\n torch.eye(rows) * gain ** 2, atol=1e-6, rtol=0)\n\n def test_deprecation(self):\n x = torch.randn(3, 3)\n\n def fn():\n init.normal(x)\n\n with self.assertWarnsRegex(UserWarning, 'deprecated', msg='methods not suffixed with underscore should be deprecated'):\n fn()\n\nclass TestFusionEval(TestCase):\n @given(X=hu.tensor(shapes=((5, 3, 5, 5),)),\n running_mean=hu.tensor(shapes=(6,)),\n running_var=hu.tensor(shapes=(6,)))\n def test_fuse_module_eval_numerics(self, X, running_mean, running_var):\n inputs, _ = X\n\n iC, oC = inputs.shape[1], len(running_mean[0])\n inputs = torch.from_numpy(inputs).to(torch.double)\n kernel_size = (3, 3)\n\n conv_ref = torch.nn.Conv2d(iC, oC, bias=True, kernel_size=kernel_size)\n bn_ref = torch.nn.BatchNorm2d(oC)\n bn_ref.running_mean = torch.from_numpy(running_mean[0]).to(torch.double)\n bn_ref.running_var = torch.from_numpy(running_var[0]).to(torch.double)\n\n conv_ref.eval()\n bn_ref.eval()\n\n Y_ref = bn_ref(conv_ref(inputs))\n conv_bn_fused = torch.nn.utils.fusion.fuse_conv_bn_eval(conv_ref,\n bn_ref)\n Y_hat = conv_bn_fused(inputs)\n\n self.assertEqual(Y_ref, Y_hat, msg=\"Conv+BN fusion results are off\")\n\n na_bn_ref = torch.nn.BatchNorm2d(oC, affine=False)\n na_bn_ref.running_mean = torch.from_numpy(running_mean[0]).to(torch.double)\n na_bn_ref.running_var = torch.from_numpy(running_var[0]).to(torch.double)\n na_bn_ref.eval()\n\n Y_ref = na_bn_ref(conv_ref(inputs))\n conv_na_bn_fused = torch.nn.utils.fusion.fuse_conv_bn_eval(conv_ref,\n na_bn_ref)\n Y_hat = conv_na_bn_fused(inputs)\n\n self.assertEqual(Y_ref, Y_hat, msg=\"Conv+BN(non-affine) fusion results are off\")\n\n\nclass TestConstantPadNd(TestCase):\n def test_constant_pad_nd(self):\n a = torch.tensor([[1, 2], [3, 4]])\n res = torch.constant_pad_nd(a, [1, 2, 1, 0], 9)\n expected = torch.tensor([\n [9, 9, 9, 9, 9],\n [9, 1, 2, 9, 9],\n [9, 3, 4, 9, 9]\n ])\n self.assertEqual(res, expected)\n\n def test_preserves_memory_format(self):\n nchw_tensor = torch.rand((1, 2, 5, 3))\n nchw_padded = torch.constant_pad_nd(nchw_tensor, [1, 2], 0.5)\n self.assertTrue(nchw_padded.is_contiguous(memory_format=torch.contiguous_format))\n\n nhwc_tensor = nchw_tensor.contiguous(memory_format=torch.channels_last)\n nhwc_padded = torch.constant_pad_nd(nhwc_tensor, [1, 2], 0.5)\n self.assertTrue(nhwc_padded.is_contiguous(memory_format=torch.channels_last))\n\n\nclass TestAddRelu(TestCase):\n def test_add_relu(self):\n a = torch.rand((7, 11))\n b = torch.rand((7, 11))\n a = a.float()\n b = b.float()\n a = a * -10\n a = a + 5\n add_res = a + b\n relu_res = torch.relu(add_res)\n add_relu_res = torch._VF._add_relu(a, b)\n\n self.assertTrue(torch.allclose(add_relu_res, relu_res))\n\n\ndef add_test(test, decorator=None):\n def add(test_name, fn):\n if hasattr(TestNN, test_name):\n raise RuntimeError('Found two tests with the same name: ' + test_name)\n if decorator is not None:\n fn = decorator(fn)\n setattr(TestNN, test_name, fn)\n\n test_name = test.get_name()\n if not hasattr(test, 'test_cpu') or test.test_cpu:\n add(test_name, lambda self, test=test: test(self))\n cuda_test_name = test_name + '_cuda'\n # With dtype enable, it's good enough to test against three floating types\n kwargs = {}\n if 'extra_args' in get_function_arglist(test.test_cuda):\n kwargs['extra_args'] = test.extra_args\n\n if 'dtype' in get_function_arglist(test.test_cuda):\n if tf32_is_not_fp32() and test.with_tf32:\n\n def with_tf32_off(self, test=test, kwargs=kwargs):\n with tf32_off():\n test.test_cuda(self, dtype=torch.float, **kwargs)\n\n add(cuda_test_name + '_fp32', with_tf32_off)\n\n def with_tf32_on(self, test=test, kwargs=kwargs):\n with tf32_on(self, test.tf32_precision):\n test.test_cuda(self, dtype=torch.float, **kwargs)\n\n add(cuda_test_name + '_tf32', with_tf32_on)\n else:\n add(cuda_test_name + '_float', lambda self,\n test=test, kwargs=kwargs: test.test_cuda(self, dtype=torch.float, **kwargs))\n add(cuda_test_name + '_double', lambda self,\n test=test, kwargs=kwargs: test.test_cuda(self, dtype=torch.double, **kwargs))\n\n def test_half(self, test=test, kwargs=kwargs):\n test.test_cuda(self, dtype=torch.half, **kwargs)\n if getattr(test, 'check_half', True):\n add(cuda_test_name + '_half', test_half)\n\n def test_bfloat16(self, test=test, kwargs=kwargs):\n test.test_cuda(self, dtype=torch.bfloat16, **kwargs)\n if getattr(test, 'check_bfloat16', True):\n add(cuda_test_name + '_bfloat16', test_bfloat16)\n\n def test_cfloat(self, test=test, kwargs=kwargs):\n test.test_cuda(self, dtype=torch.cfloat, **kwargs)\n\n def test_cdouble(self, test=test, kwargs=kwargs):\n test.test_cuda(self, dtype=torch.cdouble, **kwargs)\n if getattr(test, 'check_complex', False):\n add(cuda_test_name + '_cfloat', test_cfloat)\n add(cuda_test_name + '_cdouble', test_cdouble)\n\n else:\n if tf32_is_not_fp32() and test.with_tf32:\n\n def with_tf32_off(self, test=test, kwargs=kwargs):\n with tf32_off():\n test.test_cuda(self, **kwargs)\n\n add(cuda_test_name + '_fp32', with_tf32_off)\n\n def with_tf32_on(self, test=test, kwargs=kwargs):\n with tf32_on(self, test.tf32_precision):\n test.test_cuda(self, **kwargs)\n\n add(cuda_test_name + '_tf32', with_tf32_on)\n else:\n add(cuda_test_name, lambda self, test=test, kwargs=kwargs: test.test_cuda(self, **kwargs))\n\nfor test_params in module_tests + new_module_tests:\n # TODO: CUDA is not implemented yet\n if 'constructor' not in test_params:\n name = test_params.pop('module_name')\n test_params['constructor'] = getattr(nn, name)\n decorator = test_params.pop('decorator', None)\n test = NewModuleTest(**test_params)\n add_test(test, decorator)\n if 'check_eval' in test_params:\n # create a new test that is identical but that sets module.training to False\n desc = test_params.get('desc', None)\n test_params['desc'] = 'eval' if desc is None else desc + '_eval'\n\n def gen_eval_constructor(constructor):\n def eval_constructor(*args, **kwargs):\n cons = constructor(*args, **kwargs)\n cons.training = False\n return cons\n eval_constructor.__name__ = constructor.__name__\n return eval_constructor\n\n test_params['constructor'] = gen_eval_constructor(test_params['constructor'])\n test = NewModuleTest(**test_params)\n add_test(test, decorator)\n if 'check_with_long_tensor' in test_params:\n fullname = test_params.get('fullname', None)\n if fullname:\n test_params['fullname'] = fullname + '_with_long_tensor'\n else:\n desc = test_params.get('desc', None)\n test_params['desc'] = 'with_long_tensor' if desc is None else desc + '_with_long_tensor'\n\n def double_equivalent_of_long_tensor(size):\n return torch.randint(-1000, 1000, size=size).double()\n\n def apply_to_cons(t):\n if t.is_floating_point():\n if isinstance(t, Parameter):\n return Parameter(double_equivalent_of_long_tensor(t.size()))\n elif isinstance(t, torch.Tensor):\n return double_equivalent_of_long_tensor(t.size())\n else:\n return t\n\n def gen_long_tensor_constructor(constructor):\n def long_tensor_constructor(*args, **kwargs):\n cons = constructor(*args, **kwargs)\n cons._apply(apply_to_cons)\n return cons\n long_tensor_constructor.__name__ = constructor.__name__\n return long_tensor_constructor\n\n def gen_long_tensor_input(input_size):\n def input_func():\n return double_equivalent_of_long_tensor(input_size)\n return input_func\n\n def reference_fn(i, p, m):\n # For bad reasons this would create LongTensors that requires gradients\n # Remove requires_grad to avoid this\n for p in m.parameters():\n p.requires_grad_(False)\n m._apply(lambda t: t.long())\n input = i.long()\n out = m.forward(input)\n return out\n\n test_params['constructor'] = gen_long_tensor_constructor(test_params['constructor'])\n test_params['input_fn'] = gen_long_tensor_input(test_params['input_size'])\n test_params['reference_fn'] = reference_fn\n test_params['check_forward_only'] = True\n # Currently we don't support conv2d/conv3d for LongTensor in CUDA\n test_params['test_cuda'] = False\n test = NewModuleTest(**test_params)\n\n add_test(test, decorator)\n\nfor test_params in criterion_tests:\n name = test_params.pop('module_name')\n test_params['constructor'] = getattr(nn, name)\n test = CriterionTest(**test_params)\n decorator = test_params.pop('decorator', None)\n add_test(test, decorator)\n if 'check_sum_reduction' in test_params:\n desc = test_params.get('desc', None)\n test_params['desc'] = 'sum_reduction' if desc is None else desc + '_sum_reduction'\n\n def gen_sum_reduction_constructor(constructor):\n def sum_reduction_constructor(*args, **kwargs):\n cons = constructor(*args, reduction='sum', **kwargs)\n return cons\n sum_reduction_constructor.__name__ = constructor.__name__\n return sum_reduction_constructor\n\n test_params['constructor'] = gen_sum_reduction_constructor(test_params['constructor'])\n test = CriterionTest(**test_params)\n add_test(test, decorator)\n\n\nclass UnpoolingNet(nn.Module):\n def __init__(self, pool, unpool):\n super(UnpoolingNet, self).__init__()\n self.pool = pool\n self.unpool = unpool\n\n def forward(self, input):\n return self.unpool(*self.pool(input))\n\n\nadd_test(NewModuleTest(\n constructor=lambda: UnpoolingNet(\n nn.MaxPool1d(2, return_indices=True),\n nn.MaxUnpool1d(2)),\n input_size=(1, 1, 4),\n fullname='MaxUnpool1d_net',))\nadd_test(NewModuleTest(\n constructor=lambda: UnpoolingNet(\n nn.MaxPool2d(2, return_indices=True),\n nn.MaxUnpool2d(2)),\n input_size=(1, 1, 2, 4),\n fullname='MaxUnpool2d_net',))\nadd_test(NewModuleTest(\n constructor=lambda: UnpoolingNet(\n nn.MaxPool3d(2, return_indices=True),\n nn.MaxUnpool3d(2)),\n input_size=(1, 1, 2, 4, 6),\n fullname='MaxUnpool3d_net',\n check_gradgrad=False,))\n\n\nclass _AdaptiveLogSoftmaxWithLoss(nn.AdaptiveLogSoftmaxWithLoss):\n def __call__(self, input):\n t = torch.tensor([0, 1, 4, 8]).to(input.device)\n return nn.AdaptiveLogSoftmaxWithLoss.__call__(self, input, t).output\n\nadd_test(NewModuleTest(\n constructor=lambda: _AdaptiveLogSoftmaxWithLoss(16, 10, [2, 6]),\n input_size=(4, 16),\n fullname='AdaptiveLogSoftmax',\n with_tf32=True,\n tf32_precision=0.005))\n\n\n# The following are helpers for TestNN.test_affine_*\nif torch.cuda.is_available():\n def device_():\n return ['cpu', 'cuda']\nelse:\n def device_():\n return ['cpu']\n\n\ndef angle_rad_():\n return [r * math.pi * 2 for r in [0.0, 0.5, 0.25, 0.125, random.random()]]\n\n\ndef axis_vector_():\n t = (random.random(), random.random(), random.random())\n l = sum(x ** 2 for x in t) ** 0.5\n\n return [(1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0), tuple(x / l for x in t)]\n\n\ndef input_size2d_():\n return [[1, 1, 3, 5], [1, 1, 3, 3], [1, 1, 4, 4], [1, 1, 3, 4]]\n\n\ndef output_size2d_():\n return [[1, 1, 5, 3], [1, 1, 3, 5], [1, 1, 4, 3], [1, 1, 5, 5], [1, 1, 6, 6]]\n\n\ndef input_size2dsq_():\n return [[1, 1, 2, 2], [1, 1, 3, 3], [1, 1, 4, 4], [1, 1, 6, 6]]\n\n\ndef output_size2dsq_():\n return [[1, 1, 2, 2], [1, 1, 3, 3], [1, 1, 4, 4], [1, 1, 5, 5], [1, 1, 6, 6]]\n\n\ndef input_size3d_():\n return [[1, 1, 2, 2, 2], [1, 1, 2, 3, 4], [1, 1, 3, 3, 3], [1, 1, 4, 4, 4], [1, 1, 3, 4, 5]]\n\n\ndef input_size3dsq_():\n return [[1, 1, 2, 2, 2], [1, 1, 3, 3, 3], [1, 1, 4, 4, 4], [1, 1, 6, 6, 6]]\n\n\ndef output_size3dsq_():\n return [[1, 1, 2, 2, 2], [1, 1, 3, 3, 3], [1, 1, 4, 4, 4], [1, 1, 5, 5, 5], [1, 1, 6, 6, 6]]\n\n\ndef output_size3d_():\n return [[1, 1, 2, 2, 2], [1, 1, 3, 3, 3], [1, 1, 3, 4, 5], [1, 1, 4, 3, 2], [1, 1, 5, 5, 5], [1, 1, 6, 6, 6]]\n\n\ndef _buildEquivalentAffineTransforms2d(device, input_size, output_size, angle_rad):\n input_center = [(x - 1) / 2.0 for x in input_size]\n output_center = [(x - 1) / 2.0 for x in output_size]\n\n s = math.sin(angle_rad)\n c = math.cos(angle_rad)\n\n intrans_ary = np.array([\n [1, 0, input_center[2]],\n [0, 1, input_center[3]],\n [0, 0, 1],\n ], dtype=np.float64)\n\n inscale_ary = np.array([\n [input_center[2], 0, 0],\n [0, input_center[3], 0],\n [0, 0, 1],\n ], dtype=np.float64)\n\n rotation_ary = np.array([\n [c, -s, 0],\n [s, c, 0],\n [0, 0, 1],\n ], dtype=np.float64)\n\n outscale_ary = np.array([\n [1.0 / output_center[2], 0, 0],\n [0, 1.0 / output_center[3], 0],\n [0, 0, 1],\n ], dtype=np.float64)\n\n outtrans_ary = np.array([\n [1, 0, -output_center[2]],\n [0, 1, -output_center[3]],\n [0, 0, 1],\n ], dtype=np.float64)\n\n reorder_ary = np.array([\n [0, 1, 0],\n [1, 0, 0],\n [0, 0, 1],\n ], dtype=np.float64)\n\n transform_ary = np.dot(np.dot(np.dot(np.dot(\n intrans_ary,\n inscale_ary),\n rotation_ary.T),\n outscale_ary),\n outtrans_ary)\n grid_ary = np.dot(np.dot(np.dot(reorder_ary, rotation_ary.T), outscale_ary), outtrans_ary)\n\n transform_tensor = torch.from_numpy((rotation_ary)).to(device, torch.float32)\n transform_tensor = transform_tensor[:2].unsqueeze(0)\n\n return transform_tensor, transform_ary, grid_ary\n\n\ndef _buildEquivalentAffineTransforms3d(device, input_size, output_size, angle_rad, axis_vector):\n input_center = [(x - 1) / 2.0 for x in input_size]\n output_center = [(x - 1) / 2.0 for x in output_size]\n\n s = math.sin(angle_rad)\n c = math.cos(angle_rad)\n c1 = 1 - c\n\n intrans_ary = np.array([\n [1, 0, 0, input_center[2]],\n [0, 1, 0, input_center[3]],\n [0, 0, 1, input_center[4]],\n [0, 0, 0, 1],\n ], dtype=np.float64)\n\n inscale_ary = np.array([\n [input_center[2], 0, 0, 0],\n [0, input_center[3], 0, 0],\n [0, 0, input_center[4], 0],\n [0, 0, 0, 1],\n ], dtype=np.float64)\n\n l, m, n = axis_vector\n scipyRotation_ary = np.array([\n [l * l * c1 + c, m * l * c1 - n * s, n * l * c1 + m * s, 0],\n [l * m * c1 + n * s, m * m * c1 + c, n * m * c1 - l * s, 0],\n [l * n * c1 - m * s, m * n * c1 + l * s, n * n * c1 + c, 0],\n [0, 0, 0, 1],\n ], dtype=np.float64)\n\n z, y, x = axis_vector\n torchRotation_ary = np.array([\n [x * x * c1 + c, y * x * c1 - z * s, z * x * c1 + y * s, 0],\n [x * y * c1 + z * s, y * y * c1 + c, z * y * c1 - x * s, 0],\n [x * z * c1 - y * s, y * z * c1 + x * s, z * z * c1 + c, 0],\n [0, 0, 0, 1],\n ], dtype=np.float64)\n\n outscale_ary = np.array([\n [1.0 / output_center[2], 0, 0, 0],\n [0, 1.0 / output_center[3], 0, 0],\n [0, 0, 1.0 / output_center[4], 0],\n [0, 0, 0, 1],\n ], dtype=np.float64)\n\n outtrans_ary = np.array([\n [1, 0, 0, -output_center[2]],\n [0, 1, 0, -output_center[3]],\n [0, 0, 1, -output_center[4]],\n [0, 0, 0, 1],\n ], dtype=np.float64)\n\n reorder_ary = np.array([\n [0, 0, 1, 0],\n [0, 1, 0, 0],\n [1, 0, 0, 0],\n [0, 0, 0, 1],\n ], dtype=np.float64)\n\n transform_ary = np.dot(np.dot(np.dot(np.dot(\n intrans_ary,\n inscale_ary),\n np.linalg.inv(scipyRotation_ary)),\n outscale_ary),\n outtrans_ary)\n grid_ary = np.dot(np.dot(np.dot(reorder_ary, np.linalg.inv(scipyRotation_ary)), outscale_ary), outtrans_ary)\n\n transform_tensor = torch.from_numpy((torchRotation_ary)).to(device, torch.float32)\n transform_tensor = transform_tensor[:3].unsqueeze(0)\n\n return transform_tensor, transform_ary, grid_ary\n# end TestNN.test_affine_* helpers\n\n\nclass TestNNDeviceType(NNTestCase):\n def _test_dropout(self, cls, device, input, memory_format=torch.contiguous_format):\n p = 0.2\n input = input.to(device).fill_(1 - p)\n\n module = cls(p)\n input_var = input.clone(memory_format=memory_format).requires_grad_()\n output = module(input_var)\n self.assertTrue(output.is_contiguous(memory_format=memory_format))\n self.assertLess(abs(output.data.mean() - (1 - p)), 0.05)\n output.backward(input)\n self.assertTrue(input_var.grad.is_contiguous(memory_format=memory_format))\n self.assertLess(abs(input_var.grad.data.mean() - (1 - p)), 0.05)\n\n module = cls(p, True)\n input_var = input.clone(memory_format=memory_format).requires_grad_()\n output = module(input_var + 0)\n self.assertTrue(output.is_contiguous(memory_format=memory_format))\n self.assertLess(abs(output.data.mean() - (1 - p)), 0.05)\n output.backward(input)\n self.assertTrue(input_var.grad.is_contiguous(memory_format=memory_format))\n self.assertLess(abs(input_var.grad.data.mean() - (1 - p)), 0.05)\n\n # check eval mode doesn't change anything\n for inplace in [True, False]:\n module = cls(p, inplace).eval()\n self.assertEqual(input, module(input))\n\n # Check that these don't raise errors\n module.__repr__()\n str(module)\n\n def _test_dropout_discontiguous(self, cls, device, memory_format=torch.contiguous_format):\n # In this test, we verify that dropout preserves the layout and data for different memory formats.\n # We check whether, we get same values for the output of dropout, when the probability\n # of dropout is 0 or very close to 0.\n # Reference: https://github.com/pytorch/pytorch/issues/47176\n close_to_zero_p = 1e-10 # Should be almost zero but not zero, as for p=0 different path is taken\n for p in [0, close_to_zero_p]:\n inp = torch.ones(2, 3, 3, 3, device=device)\n inp_discontiguous = torch.empty(2, 3, 3, 6, device=device, memory_format=memory_format)[..., ::2]\n inp_discontiguous.copy_(inp)\n mod = cls(p=p)\n out = mod(inp_discontiguous)\n if p != 0: # Zero will keep strides as is based on input.\n # When prob == 0, input stride (54, 18, 6, 2) -> output stride (54, 18, 6, 2)\n # When prob != 0, input stride (54, 18, 6, 2) -> output stride (27, 9, 3, 1)\n self.assertTrue(out.is_contiguous(memory_format=memory_format))\n self.assertEqual(inp_discontiguous, out)\n\n def _test_dropout_stride_mean_preserve(self, cls, device):\n def invert_perm(p):\n d = {x: i for i, x in enumerate(p)}\n return (d[0], d[1], d[2], d[3])\n\n inp = torch.ones(2, 3, 4, 5, device=device)\n shifts = [(0, 0), (1, 0), (0, 1), (1, 1)]\n for perm in itertools.permutations((0, 1, 2, 3), r=4):\n for shift in shifts:\n for p in [1e-10, 0.3, 0.5, 0.7]:\n mod = cls(p=p)\n permuted_inp = inp.permute(perm).contiguous().permute(invert_perm(perm))\n permuted_inp = permuted_inp[shift[0]:, shift[1]:, :, :]\n out = mod(permuted_inp)\n\n self.assertTrue(out.permute(perm).is_contiguous())\n self.assertEqual(inp.mean(), out.mean(), rtol=0.5, atol=0.5)\n if p == 1e-10:\n self.assertEqual(permuted_inp, out)\n else:\n self.assertNotEqual(permuted_inp, out)\n\n def _test_InstanceNorm_general(self, cls, input, device, dtype=torch.float):\n # default case track_running_stats=False\n b, c = input.size(0), input.size(1)\n input_var = input.to(device=device, dtype=dtype).requires_grad_()\n\n IN = cls(c, eps=0).to(device, dtype)\n\n output = IN(input_var)\n out_reshaped = output.view(b * c, -1)\n\n mean = out_reshaped.mean(1)\n var = out_reshaped.var(1, unbiased=False)\n\n self.assertEqual(torch.abs(mean.data).mean(), 0, atol=1e-5, rtol=0)\n self.assertEqual(torch.abs(var.data).mean(), 1, atol=1e-5, rtol=0)\n\n # check that eval mode doesn't change behavior\n grad_out = torch.randn_like(output)\n res1 = output.data.clone()\n output.backward(grad_out)\n grad1 = input_var.grad.data.clone()\n\n IN.eval()\n output = IN(input_var)\n input_var.grad = None\n output.backward(grad_out)\n res2 = output.data\n grad2 = input_var.grad.data\n self.assertEqual(res1, res2)\n self.assertEqual(grad1, grad2)\n\n # If track_running_stats=True and momentum=1, running_mean/var should be\n # equal to mean/var of the input (with unbias correction)\n IN = cls(c, momentum=1, eps=0, track_running_stats=True).to(device, dtype)\n\n output = IN(input_var)\n\n input_reshaped = input_var.transpose(1, 0).reshape(c, -1)\n mean = input_reshaped.mean(1)\n\n input_reshaped = input_var.transpose(1, 0).reshape(c, b, -1)\n var = input_reshaped.var(2, unbiased=True)[:, :]\n\n self.assertEqual(torch.abs(mean.data - IN.running_mean).mean(), 0, atol=1e-5, rtol=0)\n self.assertEqual(torch.abs(var.data.mean(1) - IN.running_var).mean(), 0, atol=1e-5, rtol=0)\n\n # in eval mode, adding X * std to a channel in input should make the\n # corresponding channel in output have mean X\n IN.eval()\n delta = IN.running_var.sqrt() * torch.arange(c, device=device, dtype=dtype)\n delta = delta.view(-1, *[1 for _ in range(2, input.dim())])\n output = IN(input_var + delta)\n # TODO(#38095): Replace assertEqualIgnoreType. See issue #38095\n self.assertEqualIgnoreType(output.transpose(0, 1).reshape(c, -1).mean(1), torch.arange(c))\n\n def _test_InstanceNorm_cuda_half(self, cls, input, device):\n # THNN\n input = input.to(device=device, dtype=torch.half).random_(1, 10).requires_grad_(True)\n m = cls(input.size(1), affine=True, track_running_stats=True).to(device, torch.half)\n thnn_output = m(input)\n thnn_output.sum().backward()\n thnn_input_grad = input.grad.data.clone()\n self.assertEqualTypeString(thnn_output, input)\n # cuDNN\n if TEST_CUDNN:\n input.grad = None\n m = m.float()\n cudnn_output = m(input)\n cudnn_output.sum().backward()\n cudnn_input_grad = input.grad.data.clone()\n self.assertEqualTypeString(cudnn_output, input)\n self.assertEqual(cudnn_output, thnn_output, atol=1e-4, rtol=0)\n self.assertEqual(cudnn_input_grad, thnn_input_grad, atol=1e-3, rtol=0)\n\n def _test_LayerNorm_general(self, device, dtype=torch.float):\n for i in range(2, 6):\n shape = torch.randint(3, 6, (i,), dtype=torch.long).tolist()\n x = torch.empty(*shape, device=device, dtype=dtype).uniform_(0, 10)\n normalized_ndim = random.randint(1, i - 1) # inclusive\n normalized_shape = shape[-normalized_ndim:]\n unnormalized_shape = shape[:-normalized_ndim]\n\n # test that LN normalizes to mean 0 and stddev 1\n ln = nn.LayerNorm(normalized_shape, eps=0).to(device, dtype)\n ln.weight.data.fill_(1)\n ln.bias.data.fill_(0)\n output = ln(x)\n out_reshaped = output.view(*(unnormalized_shape + [-1]))\n mean = out_reshaped.mean(-1)\n var = out_reshaped.var(-1, unbiased=False)\n\n delta = 1e-1 if dtype == torch.bfloat16 else 1e-5\n self.assertEqual(torch.abs(mean.data).mean(), 0, atol=delta, rtol=0)\n self.assertEqual(torch.abs(var.data).mean(), 1, atol=delta, rtol=0)\n\n # test that LN applies weight and bias correctly\n scale, bias = torch.empty(2).uniform_(0.2, 2).tolist()\n ln.weight.data.fill_(scale)\n ln.bias.data.fill_(bias)\n output = ln(x)\n out_reshaped = output.view(*(unnormalized_shape + [-1]))\n mean = out_reshaped.mean(-1)\n var = out_reshaped.var(-1, unbiased=False)\n self.assertEqual(torch.abs(mean.data).mean(), bias, atol=delta, rtol=0)\n self.assertEqual(torch.abs(var.data).mean(), scale ** 2, atol=delta, rtol=0)\n\n bad_norm_shape_input_shape = {\n (): (),\n (2, 3): (3,),\n (2,): (1, 2, 3),\n (10,): (2, 3),\n 10: (2, 3),\n }\n for norm_shape, input_shape in bad_norm_shape_input_shape.items():\n ln = nn.LayerNorm(norm_shape)\n input = torch.empty(input_shape, device=device, dtype=dtype).uniform_(0, 10)\n self.assertRaises(RuntimeError, lambda: ln(input))\n\n def _test_LayerNorm_cuda_half(self, device):\n input = torch.empty(2, 3, 3, 2, device=device, dtype=torch.half).random_(1, 10).requires_grad_(True)\n m = nn.LayerNorm([3, 2]).to(device, torch.half)\n output = m(input)\n output.sum().backward()\n self.assertEqualTypeString(output, input)\n\n def _test_GroupNorm_general(self, device, dtype=torch.float):\n good_shape_g = {\n (1, 2, 3, 4): 2,\n (2, 3, 10): 3,\n (3, 1, 1, 1, 2): 1,\n (2, 6, 4, 2, 2): 3,\n (1, 256, 1, 1): 32,\n }\n for shape_g, grad in product(good_shape_g.items(), [True, False]):\n shape, g = shape_g\n x = torch.empty(*shape, device=device, dtype=dtype).uniform_(0, 10)\n x.requires_grad_(grad)\n b = shape[0]\n c = shape[1]\n\n # test that GN normalizes to mean 0 and stddev 1\n gn = nn.GroupNorm(g, c, eps=0).to(device, dtype)\n gn.weight.data.fill_(1)\n gn.bias.data.fill_(0)\n output = gn(x)\n out_reshaped = output.view(b, g, -1)\n mean = out_reshaped.mean(-1)\n var = out_reshaped.var(-1, unbiased=False)\n # TODO: fix numerical issue. See #44863\n self.assertEqual(torch.abs(mean).mean(), 0, atol=1e-3, rtol=1e-3)\n self.assertEqual(torch.abs(var).mean(), 1, atol=1e-3, rtol=1e-3)\n\n output.backward(torch.randn_like(output))\n if output.is_cuda:\n torch.cuda.synchronize()\n\n # test that GN applies weight and bias correctly\n scale = torch.empty(c, device=device, dtype=dtype).uniform_(0.2, 2)\n bias = torch.empty(c, device=device, dtype=dtype).uniform_(0.2, 2)\n gn.weight.data.copy_(scale)\n gn.bias.data.copy_(bias)\n output = gn(x)\n out_reshaped = output.view(b, c, -1)\n out_normed = (out_reshaped - bias.view(c, 1)) / scale.view(c, 1)\n out_normed_reshaped = out_normed.view(b, g, -1)\n mean = out_normed_reshaped.mean(-1)\n var = out_normed_reshaped.var(-1, unbiased=False)\n # TODO: fix numerical issue. See #44863\n self.assertEqual(torch.abs(mean).mean(), 0, atol=1e-3, rtol=1e-3)\n self.assertEqual(torch.abs(var).mean(), 1, atol=1e-3, rtol=1e-3)\n\n bad_shape_g = {\n (1, 2, 3, 4): 3,\n (2, 3, 10): 2,\n (3, 1, 1, 1, 2): 10,\n (2, 6, 4, 2, 2): 4,\n }\n for shape, g in bad_shape_g.items():\n gn = nn.GroupNorm(g, shape[1])\n input = torch.empty(*shape, device=device, dtype=dtype).uniform_(0, 10)\n self.assertRaises(RuntimeError, lambda: gn(input))\n\n def _test_GroupNorm_cuda_half(self):\n input = torch.zeros(2, 4, 3, 2, requires_grad=True).cuda().half().random_(1, 10)\n m = nn.GroupNorm(2, 4).to(\"cuda\", torch.half)\n output = m(input)\n output.sum().backward()\n self.assertEqualTypeString(output, input)\n\n def _test_module_empty_input(self, module, inp, check_size=True):\n inp.requires_grad_(True)\n out = module(inp)\n gO = torch.rand_like(out)\n out.backward(gO)\n if check_size:\n self.assertEqual(out.size(), inp.size())\n for p in module.parameters():\n if p.requires_grad:\n self.assertEqual(p.grad, torch.zeros_like(p.grad))\n self.assertEqual(inp.grad, torch.zeros_like(inp))\n\n @unittest.skipIf((not TEST_NUMPY) or (not TEST_SCIPY) or (scipy.__version__ < '1.0.0'),\n \"Scipy v1.0 and/or numpy not found\")\n @tf32_on_and_off()\n def test_affine_2d_rotate0(self, device):\n # scipy before 1.0.0 do not support homogeneous coordinate\n # scipy.ndimage.affine_transform, so we need to skip.\n input_size = [1, 1, 3, 3]\n input_ary = np.array(np.random.random(input_size), dtype=np.float32)\n output_size = [1, 1, 5, 5]\n angle_rad = 0.\n\n transform_tensor, transform_ary, offset = \\\n _buildEquivalentAffineTransforms2d(device, input_size, output_size, angle_rad)\n\n scipy_ary = torch.from_numpy(scipy.ndimage.affine_transform(\n input_ary[0, 0],\n transform_ary,\n offset=offset,\n output_shape=output_size[2:],\n order=1,\n mode='nearest',\n prefilter=False))\n\n affine_tensor = torch.nn.functional.affine_grid(\n transform_tensor,\n torch.Size(output_size),\n align_corners=True\n )\n\n gridsample_ary = torch.nn.functional.grid_sample(\n torch.tensor(input_ary, device=device).to(device),\n affine_tensor,\n padding_mode='border',\n align_corners=True\n ).to('cpu')\n\n self.assertEqual(scipy_ary.mean(), gridsample_ary.mean())\n self.assertEqual(scipy_ary, gridsample_ary.reshape_as(scipy_ary))\n\n @unittest.skipIf((not TEST_NUMPY) or (not TEST_SCIPY) or (scipy.__version__ < '1.0.0'),\n \"Scipy v1.0 and/or numpy not found\")\n @tf32_on_and_off(0.001)\n def test_affine_2d_rotate90(self, device):\n # scipy before 1.0.0 do not support homogeneous coordinate\n # scipy.ndimage.affine_transform, so we need to skip.\n for input_size2dsq, output_size2dsq in \\\n itertools.product(input_size2dsq_(), output_size2dsq_()):\n input_size = input_size2dsq\n input_ary = np.array(np.random.random(input_size), dtype=np.float32)\n output_size = output_size2dsq\n angle_rad = 0.25 * math.pi * 2\n\n transform_tensor, transform_ary, offset = \\\n _buildEquivalentAffineTransforms2d(device, input_size, output_size, angle_rad)\n\n scipy_ary = torch.from_numpy(scipy.ndimage.affine_transform(\n input_ary[0, 0],\n transform_ary,\n offset=offset,\n output_shape=output_size[2:],\n order=1,\n mode='nearest',\n prefilter=True))\n\n if input_size2dsq == output_size2dsq:\n self.assertEqual(scipy_ary.mean(), input_ary.mean())\n self.assertEqual(scipy_ary[0, 0], input_ary[0, 0, 0, -1])\n self.assertEqual(scipy_ary[0, -1], input_ary[0, 0, -1, -1])\n self.assertEqual(scipy_ary[-1, -1], input_ary[0, 0, -1, 0])\n self.assertEqual(scipy_ary[-1, 0], input_ary[0, 0, 0, 0])\n\n affine_tensor = torch.nn.functional.affine_grid(\n transform_tensor,\n torch.Size(output_size),\n align_corners=True\n )\n\n gridsample_ary = torch.nn.functional.grid_sample(\n torch.tensor(input_ary, device=device).to(device),\n affine_tensor,\n padding_mode='border',\n align_corners=True\n ).to('cpu')\n\n self.assertEqual(scipy_ary.mean(), gridsample_ary.mean())\n self.assertEqual(scipy_ary, gridsample_ary.reshape_as(scipy_ary))\n\n @unittest.skipIf((not TEST_NUMPY) or (not TEST_SCIPY) or (scipy.__version__ < '1.0.0'),\n \"Scipy v1.0 and/or numpy not found\")\n @tf32_on_and_off(0.005)\n def test_affine_2d_rotate45(self, device):\n # scipy before 1.0.0 do not support homogeneous coordinate\n # scipy.ndimage.affine_transform, so we need to skip.\n input_size = [1, 1, 3, 3]\n input_ary = np.array(np.zeros(input_size), dtype=np.float32)\n input_ary[0, 0, 0, :] = 0.5\n input_ary[0, 0, 2, 2] = 1.0\n output_size = [1, 1, 3, 3]\n angle_rad = 0.125 * math.pi * 2\n\n transform_tensor, transform_ary, offset = \\\n _buildEquivalentAffineTransforms2d(device, input_size, output_size, angle_rad)\n\n scipy_ary = torch.from_numpy(scipy.ndimage.affine_transform(\n input_ary[0, 0],\n transform_ary,\n offset=offset,\n output_shape=output_size[2:],\n order=1,\n mode='nearest',\n prefilter=False))\n\n affine_tensor = torch.nn.functional.affine_grid(\n transform_tensor,\n torch.Size(output_size),\n align_corners=True\n )\n\n gridsample_ary = torch.nn.functional.grid_sample(\n torch.tensor(input_ary, device=device).to(device),\n affine_tensor,\n padding_mode='border',\n align_corners=True\n ).to('cpu')\n\n self.assertEqual(scipy_ary, gridsample_ary.reshape_as(scipy_ary))\n\n @unittest.skipIf((not TEST_NUMPY) or (not TEST_SCIPY) or (scipy.__version__ < '1.0.0'),\n \"Scipy v1.0 and/or numpy not found\")\n @tf32_on_and_off(0.005)\n def test_affine_2d_rotateRandom(self, device):\n # scipy before 1.0.0 do not support homogeneous coordinate\n # scipy.ndimage.affine_transform, so we need to skip.\n for angle_rad, input_size2d, output_size2d in \\\n itertools.product(angle_rad_(), input_size2d_(), output_size2d_()):\n\n input_size = input_size2d\n input_ary = np.array(np.random.random(input_size), dtype=np.float32).round(3)\n output_size = output_size2d\n\n input_ary[0, 0, 0, 0] = 2\n input_ary[0, 0, 0, -1] = 4\n input_ary[0, 0, -1, 0] = 6\n input_ary[0, 0, -1, -1] = 8\n\n transform_tensor, transform_ary, grid_ary = \\\n _buildEquivalentAffineTransforms2d(device, input_size, output_size, angle_rad)\n\n scipy_ary = torch.from_numpy(scipy.ndimage.affine_transform(\n input_ary[0, 0],\n transform_ary,\n output_shape=output_size[2:],\n order=1,\n mode='nearest',\n prefilter=False))\n\n affine_tensor = torch.nn.functional.affine_grid(\n transform_tensor,\n torch.Size(output_size),\n align_corners=True\n )\n\n gridsample_ary = torch.nn.functional.grid_sample(\n torch.tensor(input_ary, device=device).to(device),\n affine_tensor,\n padding_mode='border',\n align_corners=True\n ).to('cpu')\n\n affine_tensor = affine_tensor.to('cpu')\n\n for r in range(affine_tensor.size(1)):\n for c in range(affine_tensor.size(2)):\n grid_out = np.dot(grid_ary, [r, c, 1])\n self.assertEqual(affine_tensor[0, r, c], grid_out[:2])\n\n self.assertEqual(scipy_ary, gridsample_ary.reshape_as(scipy_ary))\n\n @unittest.skipIf((not TEST_NUMPY) or (not TEST_SCIPY) or (scipy.__version__ < '1.0.0'),\n \"Scipy v1.0 and/or numpy not found\")\n @tf32_on_and_off(0.005)\n def test_affine_3d_rotateRandom(self, device):\n # scipy before 1.0.0 do not support homogeneous coordinate\n # scipy.ndimage.affine_transform, so we need to skip.\n for angle_rad, axis_vector, input_size3d, output_size3d in \\\n itertools.product(angle_rad_(), axis_vector_(), input_size3d_(), output_size3d_()):\n input_size = input_size3d\n input_ary = np.array(np.random.random(input_size), dtype=np.float32)\n output_size = output_size3d\n\n input_ary[0, 0, 0, 0, 0] = 2\n input_ary[0, 0, 0, 0, -1] = 3\n input_ary[0, 0, 0, -1, 0] = 4\n input_ary[0, 0, 0, -1, -1] = 5\n input_ary[0, 0, -1, 0, 0] = 6\n input_ary[0, 0, -1, 0, -1] = 7\n input_ary[0, 0, -1, -1, 0] = 8\n input_ary[0, 0, -1, -1, -1] = 9\n\n transform_tensor, transform_ary, grid_ary = \\\n _buildEquivalentAffineTransforms3d(device, input_size, output_size, angle_rad, axis_vector)\n\n scipy_ary = torch.from_numpy(scipy.ndimage.affine_transform(\n input_ary[0, 0],\n transform_ary,\n output_shape=output_size[2:],\n order=1,\n mode='nearest',\n prefilter=False))\n\n affine_tensor = torch.nn.functional.affine_grid(\n transform_tensor,\n torch.Size(output_size),\n align_corners=True\n )\n\n gridsample_ary = torch.nn.functional.grid_sample(\n torch.tensor(input_ary, device=device).to(device),\n affine_tensor,\n padding_mode='border',\n align_corners=True\n ).to('cpu')\n\n affine_tensor = affine_tensor.to('cpu')\n\n for i in range(affine_tensor.size(1)):\n for r in range(affine_tensor.size(2)):\n for c in range(affine_tensor.size(3)):\n grid_out = np.dot(grid_ary, [i, r, c, 1])\n self.assertEqual(affine_tensor[0, i, r, c], grid_out[:3])\n\n self.assertEqual(scipy_ary, gridsample_ary.reshape_as(scipy_ary))\n\n def test_conv1d_same_padding(self, device):\n # Test padding='same' outputs the correct shape\n test_args = [\n # in_size\n range(50, 55),\n # kernel_size\n [1, 2, 3, 8],\n # dilation\n range(1, 4),\n # stride\n [1],\n ]\n for in_size, k_size, dilation, stride in itertools.product(*test_args):\n x = torch.rand(1, 1, in_size, device=device)\n y = torch.rand(1, 1, k_size, device=device)\n z = F.conv1d(x, y, padding='same', dilation=dilation, stride=stride)\n self.assertEqual(z.size(2), int(math.ceil(in_size / stride)))\n\n # Compare F.conv1d padding='same' output against manual padding\n # Without strides/dilation\n x = torch.rand(1, 1, 12, device=device)\n y = torch.rand(1, 1, 3, device=device)\n expect = F.conv1d(x, y, padding=1)\n actual = F.conv1d(x, y, padding='same')\n self.assertEqual(expect, actual)\n\n # With dilation\n x = torch.rand(1, 1, 12, device=device)\n y = torch.rand(1, 1, 4, device=device)\n expect = F.conv1d(x, y, padding=3, dilation=2)\n actual = F.conv1d(x, y, padding='same', dilation=2)\n self.assertEqual(expect, actual)\n\n # Dilation with asymmetric padding\n expect = F.conv1d(x, y, padding=5, dilation=3)[..., 1:]\n actual = F.conv1d(x, y, padding='same', dilation=3)\n self.assertEqual(expect, actual)\n\n\n def test_conv2d_same_padding(self, device):\n # Compare F.conv2d padding='same' output against manual padding\n # Without strides/dilation\n x = torch.rand(1, 1, 10, 11, device=device)\n y = torch.rand(1, 1, 4, 5, device=device)\n expect = F.conv2d(x, y, padding=(2, 2))[..., 1:, :]\n actual = F.conv2d(x, y, padding='same')\n self.assertEqual(expect, actual)\n\n # With dilation\n y = torch.rand(1, 1, 3, 4, device=device)\n expect = F.conv2d(x, y, padding=(2, 3), dilation=2)\n actual = F.conv2d(x, y, padding='same', dilation=2)\n self.assertEqual(expect, actual)\n\n # Dilation with asymmetric padding\n y = torch.rand(1, 1, 4, 4, device=device)\n expect = F.conv2d(x, y, padding=5, dilation=3)[..., 1:, 1:]\n actual = F.conv2d(x, y, padding='same', dilation=3)\n self.assertEqual(expect, actual)\n\n def test_conv3d_same_padding(self, device):\n # Compare F.conv3d padding='same' output against manual padding\n # Without strides/dilation\n x = torch.rand(1, 1, 10, 11, 12, device=device)\n y = torch.rand(1, 1, 1, 2, 5, device=device)\n expect = F.conv3d(x, y, padding=(0, 1, 2))[..., :, 1:, :]\n actual = F.conv3d(x, y, padding='same')\n self.assertEqual(expect, actual)\n\n # With dilation\n expect = F.conv3d(x, y, padding=(0, 1, 4), dilation=2)\n actual = F.conv3d(x, y, padding='same', dilation=2)\n self.assertEqual(expect, actual)\n\n # Dilation with asymmetric padding\n y = torch.rand(1, 1, 4, 4, 4, device=device)\n expect = F.conv3d(x, y, padding=5, dilation=3)[..., 1:, 1:, 1:]\n actual = F.conv3d(x, y, padding='same', dilation=3)\n self.assertEqual(expect, actual)\n\n def test_conv1d_valid_padding(self, device):\n # Test F.conv1d padding='valid' is the same as no padding\n x = torch.rand(1, 1, 10, device=device)\n y = torch.rand(1, 1, 4, device=device)\n expect = F.conv1d(x, y)\n actual = F.conv1d(x, y, padding='valid')\n self.assertEqual(expect, actual)\n\n def test_conv2d_valid_padding(self, device):\n # Test F.conv2d padding='valid' is the same as no padding\n x = torch.rand(1, 1, 1, 10, device=device)\n y = torch.rand(1, 1, 1, 4, device=device)\n expect = F.conv2d(x, y)\n actual = F.conv2d(x, y, padding='valid')\n self.assertEqual(expect, actual)\n\n def test_conv3d_valid_padding(self, device):\n # Test F.conv3d padding='valid' is the same as no padding\n x = torch.rand(1, 1, 1, 1, 10, device=device)\n y = torch.rand(1, 1, 1, 1, 4, device=device)\n expect = F.conv3d(x, y)\n actual = F.conv3d(x, y, padding='valid')\n self.assertEqual(expect, actual)\n\n def test_conv1d_same_padding_backward(self, device):\n # Test F.conv1d gradients work with padding='same'\n x = torch.rand(1, 1, 12, device=device, requires_grad=True)\n y = torch.rand(1, 1, 4, device=device, requires_grad=True)\n\n # Symmetric padding\n z = F.conv1d(x, y, padding=3, dilation=2)\n z.sum().backward()\n gx_expect, gy_expect = x.grad, y.grad\n x.grad, y.grad = None, None\n\n z = F.conv1d(x, y, padding='same', dilation=2)\n z.sum().backward()\n self.assertEqual(gx_expect, x.grad)\n self.assertEqual(gy_expect, y.grad)\n x.grad, y.grad = None, None\n\n # Asymmetric padding\n z = F.conv1d(x, y, padding=2)[..., 1:]\n z.sum().backward()\n gx_expect, gy_expect = x.grad, y.grad\n x.grad, y.grad = None, None\n\n z = F.conv1d(x, y, padding='same')\n z.sum().backward()\n self.assertEqual(gx_expect, x.grad)\n self.assertEqual(gy_expect, y.grad)\n\n def test_conv2d_same_padding_backward(self, device):\n # Test F.conv2d gradients work with padding='same'\n x = torch.rand(1, 1, 10, 11, device=device, requires_grad=True)\n y = torch.rand(1, 1, 4, 5, device=device, requires_grad=True)\n\n # Symmetric padding\n z = F.conv2d(x, y, padding=(3, 4), dilation=2)\n z.sum().backward()\n gx_expect, gy_expect = x.grad, y.grad\n x.grad, y.grad = None, None\n\n z = F.conv2d(x, y, padding='same', dilation=2)\n z.sum().backward()\n self.assertEqual(gx_expect, x.grad)\n self.assertEqual(gy_expect, y.grad)\n x.grad, y.grad = None, None\n\n # Asymmetric padding\n y = torch.rand(1, 1, 4, 4, device=device, requires_grad=True)\n z = F.conv2d(x, y, padding=2)[..., 1:, 1:]\n z.sum().backward()\n gx_expect, gy_expect = x.grad, y.grad\n x.grad, y.grad = None, None\n\n z = F.conv1d(x, y, padding='same')\n z.sum().backward()\n self.assertEqual(gx_expect, x.grad)\n self.assertEqual(gy_expect, y.grad)\n\n def test_conv3d_same_padding_backward(self, device):\n # Test F.conv3d gradients work with padding='same'\n x = torch.rand(1, 1, 1, 11, 12, device=device, requires_grad=True)\n y = torch.rand(1, 1, 1, 2, 5, device=device, requires_grad=True)\n\n # Symmetric padding\n z = F.conv3d(x, y, padding=(0, 1, 4), dilation=2)\n z.sum().backward()\n gx_expect, gy_expect = x.grad, y.grad\n x.grad, y.grad = None, None\n\n z = F.conv3d(x, y, padding='same', dilation=2)\n z.sum().backward()\n self.assertEqual(gx_expect, x.grad)\n self.assertEqual(gy_expect, y.grad)\n x.grad, y.grad = None, None\n\n # Asymmetric padding\n y = torch.rand(1, 1, 1, 4, 4, device=device, requires_grad=True)\n z = F.conv3d(x, y, padding=2)[..., 1:, 1:]\n z.sum().backward()\n gx_expect, gy_expect = x.grad, y.grad\n x.grad, y.grad = None, None\n\n z = F.conv3d(x, y, padding='same')\n z.sum().backward()\n self.assertEqual(gx_expect, x.grad)\n self.assertEqual(gy_expect, y.grad)\n\n def test_conv1d_valid_padding_backward(self, device):\n # Test F.conv1d gradients work with padding='valid'\n x = torch.rand(1, 1, 10, device=device, requires_grad=True)\n y = torch.rand(1, 1, 4, device=device, requires_grad=True)\n F.conv1d(x, y, padding=0).sum().backward()\n gx_expect, gy_expect = x.grad, y.grad\n x.grad, y.grad = None, None\n\n F.conv1d(x, y, padding='valid').sum().backward()\n gx_actual, gy_actual = x.grad, y.grad\n self.assertEqual(gx_expect, gx_actual)\n self.assertEqual(gy_expect, gy_actual)\n\n def test_conv2d_valid_padding_backward(self, device):\n # Test F.conv2d gradients work with padding='valid'\n x = torch.rand(1, 1, 1, 10, device=device, requires_grad=True)\n y = torch.rand(1, 1, 1, 4, device=device, requires_grad=True)\n F.conv2d(x, y, padding=0).sum().backward()\n gx_expect, gy_expect = x.grad, y.grad\n x.grad, y.grad = None, None\n\n F.conv2d(x, y, padding='valid').sum().backward()\n gx_actual, gy_actual = x.grad, y.grad\n self.assertEqual(gx_expect, gx_actual)\n self.assertEqual(gy_expect, gy_actual)\n\n def test_conv3d_valid_padding_backward(self, device):\n # Test F.conv3d gradients work with padding='valid'\n x = torch.rand(1, 1, 1, 1, 10, device=device, requires_grad=True)\n y = torch.rand(1, 1, 1, 1, 4, device=device, requires_grad=True)\n F.conv3d(x, y, padding=0).sum().backward()\n gx_expect, gy_expect = x.grad, y.grad\n x.grad, y.grad = None, None\n\n F.conv3d(x, y, padding='valid').sum().backward()\n gx_actual, gy_actual = x.grad, y.grad\n self.assertEqual(gx_expect, gx_actual)\n self.assertEqual(gy_expect, gy_actual)\n\n def test_Dropout(self, device):\n input = torch.empty(1000)\n self._test_dropout(nn.Dropout, device, input)\n\n self._test_dropout_discontiguous(nn.Dropout, device)\n self._test_dropout_discontiguous(nn.Dropout, device, memory_format=torch.channels_last)\n\n self._test_dropout_stride_mean_preserve(nn.Dropout, device)\n\n if self.device_type == 'cuda':\n input = input.bfloat16()\n self._test_dropout(nn.Dropout, device, input)\n\n def test_Dropout2d(self, device):\n b = random.randint(1, 5)\n w = random.randint(1, 5)\n h = random.randint(1, 5)\n num_features = 1000\n input = torch.empty(num_features, b, w, h)\n self._test_dropout(nn.Dropout2d, device, input)\n self._test_dropout(nn.Dropout2d, device, input, memory_format=torch.channels_last)\n\n self._test_dropout_discontiguous(nn.Dropout2d, device)\n self._test_dropout_discontiguous(nn.Dropout2d, device, memory_format=torch.channels_last)\n\n def test_Dropout3d(self, device):\n b = random.randint(1, 5)\n w = random.randint(1, 5)\n h = random.randint(1, 5)\n d = random.randint(1, 2)\n num_features = 1000\n input = torch.empty(num_features, b, d, w, h)\n self._test_dropout(nn.Dropout3d, device, input)\n\n self._test_dropout_discontiguous(nn.Dropout3d, device)\n self._test_dropout_discontiguous(nn.Dropout3d, device, memory_format=torch.channels_last)\n\n def test_InstanceNorm1d_general(self, device):\n b = random.randint(3, 5)\n c = random.randint(3, 5)\n d = random.randint(8, 10)\n\n input = torch.rand(b, c, d)\n self._test_InstanceNorm_general(nn.InstanceNorm1d, input, device)\n\n if self.device_type == 'cuda':\n self._test_InstanceNorm_cuda_half(nn.InstanceNorm1d, input, device)\n\n def test_InstanceNorm2d_general(self, device):\n b = random.randint(3, 5)\n c = random.randint(3, 5)\n w = random.randint(3, 6)\n h = random.randint(6, 8)\n\n input = torch.rand(b, c, h, w)\n self._test_InstanceNorm_general(nn.InstanceNorm2d, input, device)\n\n if self.device_type == 'cuda':\n self._test_InstanceNorm_cuda_half(nn.InstanceNorm2d, input, device)\n\n def test_InstanceNorm3d_general(self, device):\n b = random.randint(3, 5)\n c = random.randint(3, 5)\n w = random.randint(2, 5)\n h = random.randint(2, 5)\n d = random.randint(2, 5)\n\n input = torch.rand(b, c, h, w, d)\n self._test_InstanceNorm_general(nn.InstanceNorm3d, input, device)\n\n if self.device_type == 'cuda':\n self._test_InstanceNorm_cuda_half(nn.InstanceNorm3d, input, device)\n\n def test_instancenorm_raises_error_if_less_than_one_value_per_channel(self, device):\n x = torch.rand(10)[None, :, None]\n with self.assertRaises(ValueError):\n torch.nn.InstanceNorm1d(10)(x).to(device)\n\n def test_LayerNorm_general(self, device):\n self._test_LayerNorm_general(device)\n\n if self.device_type == 'cuda':\n self._test_LayerNorm_general(device, dtype=torch.bfloat16)\n\n if self.device_type == 'cuda':\n self._test_LayerNorm_cuda_half(device)\n\n @onlyOnCPUAndCUDA\n def test_GroupNorm_general(self, device):\n self._test_GroupNorm_general(device)\n\n if self.device_type == 'cuda':\n self._test_GroupNorm_cuda_half()\n\n def test_GroupNorm_raises_error_if_one_value_per_group(self, device):\n x = torch.rand(10)[None, :, None]\n with self.assertRaises(ValueError):\n torch.nn.GroupNorm(10, 10)(x).to(device)\n\n def test_GroupNorm_empty(self, device):\n mod = torch.nn.GroupNorm(2, 4).to(device)\n inp = torch.randn(0, 4, 2, 2, device=device)\n self._test_module_empty_input(mod, inp)\n if self.device_type == 'cuda' and self.has_cudnn():\n with torch.backends.cudnn.flags(enabled=False):\n self._test_module_empty_input(mod, inp)\n\n @onlyOnCPUAndCUDA\n @dtypes(torch.float64, torch.complex128)\n def test_pad(self, device, dtype):\n inputs = torch.randn(1, 3, 4, 4, device=device, dtype=dtype, requires_grad=True)\n _assertGradAndGradgradChecks(self, lambda x: F.pad(x, (1, 1, 1, 1)), (inputs,))\n _assertGradAndGradgradChecks(self, lambda x: F.pad(x, (-1, 1, -2, 1)), (inputs,))\n _assertGradAndGradgradChecks(self, lambda x: F.pad(x, (-1, 1, -2, 1), value=2), (inputs,))\n self.assertTrue(gradcheck(lambda x: F.pad(x, (-1, 1, -2, 1), mode='replicate'), (inputs,)))\n self.assertTrue(gradcheck(lambda x: F.pad(x, (-1, 1, -2, 1), mode='reflect'), (inputs,)))\n self.assertTrue(gradcheck(lambda x: F.pad(x, (-1, 1, -2, 1), mode='circular'), (inputs,)))\n\n inputs = torch.randn(1, 2, 3, 4, 4, device=device, dtype=dtype, requires_grad=True)\n self.assertTrue(gradcheck(lambda x: F.pad(x, (1, 1, 1, 1, 1, 1), mode='replicate'), (inputs,)))\n\n # Assert assertion errors are raised for invalid circular padding values\n inputs = torch.randn(1, 1, 4, device=device, dtype=dtype, requires_grad=True)\n # Should raise error when trying to wrap around more than once\n self.assertRaises(AssertionError, lambda: F.pad(inputs, (5, 4), mode='circular'))\n self.assertRaises(AssertionError, lambda: F.pad(inputs, (3, 6), mode='circular'))\n # Should raise error when negative padding results in negative output shape\n self.assertRaises(AssertionError, lambda: F.pad(inputs, (-3, -2), mode='circular'))\n\n # assert that relfection padding errors when pad >= input size\n expected_err_msg = r\"Padding size should be less than the corresponding input dimension\"\n inputs = torch.randn(1, 1, 2, 3, device=device, dtype=dtype)\n self.assertRaisesRegex(RuntimeError, expected_err_msg,\n lambda: F.pad(inputs, (1, 1, 3, 0), mode='reflect'))\n inputs = torch.randn(1, 1, 2, device=device, dtype=dtype)\n self.assertRaisesRegex(RuntimeError, expected_err_msg,\n lambda: F.pad(inputs, (2, 1), mode='reflect'))\n\n inputs = torch.rand(1, 3, 4, 4, device=device, dtype=dtype)\n # assert that pad doesn't return a view into the input tensor\n for mode in 'constant', 'reflect', 'replicate', 'circular':\n out = F.pad(inputs, (0, 0, 0, 0), mode=mode)\n out.fill_(4)\n self.assertTrue(torch.all(torch.abs(inputs) < 2))\n\n out = F.pad(inputs, (0, 0, -1, -1), mode=mode)\n out.fill_(4)\n self.assertTrue(torch.all(torch.abs(inputs) < 2))\n\n @onlyOnCPUAndCUDA\n @dtypes(torch.float64, torch.complex128)\n def test_ReplicationPad_empty(self, device, dtype):\n for mod, inp in [\n (torch.nn.ReplicationPad1d(3), torch.randn(0, 3, 10, device=device, dtype=dtype)),\n (torch.nn.ReplicationPad2d(3), torch.randn(0, 3, 10, 10, device=device, dtype=dtype)),\n (torch.nn.ReplicationPad3d(3), torch.randn(0, 3, 10, 10, 10, device=device, dtype=dtype))]:\n self._test_module_empty_input(mod, inp, check_size=False)\n\n with self.assertRaisesRegex(NotImplementedError, 'Only 3D'):\n mod = torch.nn.ReplicationPad1d(2)\n inp = torch.randn(3, 10, device=device, dtype=dtype)\n mod(inp)\n\n with self.assertRaisesRegex(RuntimeError, 'Expected 2D or 3D'):\n mod = torch.nn.ReplicationPad1d(2)\n inp = torch.randn(3, 0, 10, device=device, dtype=dtype)\n mod(inp)\n\n with self.assertRaisesRegex(RuntimeError, 'Expected 3D or 4D'):\n mod = torch.nn.ReplicationPad2d((2, 2, 2, 2))\n inp = torch.randn(43, 0, 10, 10, device=device, dtype=dtype)\n mod(inp)\n\n with self.assertRaisesRegex(RuntimeError, 'Expected 4D or 5D'):\n mod = torch.nn.ReplicationPad3d((2, 2, 2, 2, 2, 2))\n inp = torch.randn(3, 0, 10, 10, 10, device=device, dtype=dtype)\n mod(inp)\n\n def test_ReplicationPad1d_large(self, device):\n shapes = ([2, 65736, 4], [65736, 2, 4])\n pl, pr = 3, 4\n for shape in shapes:\n x = torch.randn(shape, device=device, requires_grad=True)\n model = torch.nn.ReplicationPad1d((pl, pr))\n\n # forward\n out = model(x)\n self.assertEqual(out[:, :, pl : -pr], x)\n\n left_padding = out[:, :, : pl]\n self.assertEqual(left_padding, x[:, :, :1].expand_as(left_padding))\n right_padding = out[:, :, -pr :]\n self.assertEqual(right_padding, x[:, :, -1:].expand_as(right_padding))\n\n # backward\n g = torch.randn_like(out)\n out.backward(g)\n self.assertEqual(x.grad[:, :, 1 : -1], g[:, :, pl + 1 : -pr - 1])\n\n self.assertEqual(x.grad[:, :, 0], g[:, :, : pl + 1].sum(-1))\n self.assertEqual(x.grad[:, :, -1], g[:, :, -pr - 1:].sum(-1))\n\n def test_ReplicationPad2d_large(self, device):\n shapes = ([2, 65736, 4, 4], [65736, 2, 4, 4])\n pl, pr, pt, pb = 3, 4, 5, 6\n for shape in shapes:\n x = torch.randn(shape, device=device, requires_grad=True)\n model = torch.nn.ReplicationPad2d((pl, pr, pt, pb))\n\n # forward center, edge\n out = model(x)\n self.assertEqual(out[:, :, pt : -pb, pl : -pr], x)\n\n left_padding = out[:, :, pt : -pb, : pl]\n self.assertEqual(left_padding, x[:, :, :, :1].expand_as(left_padding))\n right_padding = out[:, :, pt : -pb, -pr :]\n self.assertEqual(right_padding, x[:, :, :, -1:].expand_as(right_padding))\n top_padding = out[:, :, : pt, pl : -pr]\n self.assertEqual(top_padding, x[:, :, :1, :].expand_as(top_padding))\n bottom_padding = out[:, :, -pb : , pl : -pr]\n self.assertEqual(bottom_padding, x[:, :, -1:, :].expand_as(bottom_padding))\n\n # forward corner\n tl_padding = out[:, :, : pt + 1, : pl + 1]\n self.assertEqual(tl_padding, x[:, :, :1, :1].expand_as(tl_padding))\n tr_padding = out[:, :, : pt + 1, -pr - 1:]\n self.assertEqual(tr_padding, x[:, :, :1, -1:].expand_as(tr_padding))\n bl_padding = out[:, :, -pb - 1:, : pl + 1]\n self.assertEqual(bl_padding, x[:, :, -1:, :1].expand_as(bl_padding))\n br_padding = out[:, :, -pb - 1:, -pr - 1:]\n self.assertEqual(br_padding, x[:, :, -1:, -1:].expand_as(br_padding))\n\n # backward center, edge\n g = torch.randn_like(out)\n out.backward(g)\n self.assertEqual(x.grad[:, :, 1:-1, 1:-1], g[:, :, pt + 1 : -pb - 1, pl + 1 : -pr - 1])\n\n self.assertEqual(x.grad[:, :, 1:-1, 0], g[:, :, pt + 1 : -pb - 1, : pl + 1].sum(-1))\n self.assertEqual(x.grad[:, :, 1:-1, -1], g[:, :, pt + 1 : -pb - 1, -pr - 1 :].sum(-1))\n self.assertEqual(x.grad[:, :, 0, 1:-1], g[:, :, : pt + 1, pl + 1 : -pr - 1].sum(-2))\n self.assertEqual(x.grad[:, :, -1, 1:-1], g[:, :, -pb - 1 :, pl + 1 : -pr - 1].sum(-2))\n\n # backward corner\n self.assertEqual(x.grad[:, :, 0, 0], g[:, :, : pt + 1, : pl + 1].sum((-2, -1)))\n self.assertEqual(x.grad[:, :, 0, -1], g[:, :, : pt + 1, -pr - 1 :].sum((-2, -1)))\n self.assertEqual(x.grad[:, :, -1, 0], g[:, :, -pb - 1 :, : pl + 1].sum((-2, -1)))\n self.assertEqual(x.grad[:, :, -1, -1], g[:, :, -pb - 1 :, -pr - 1 :].sum((-2, -1)))\n\n @largeTensorTest(\"6GB\")\n def test_ReplicationPad3d_large(self, device):\n shapes = ([1, 65736, 2, 2, 2], [65736, 1, 2, 2, 2])\n pl, pr, pt, pbt, pf, pbk = 3, 4, 5, 6, 7, 8\n\n for shape in shapes:\n x = torch.randn(shape, device=device, requires_grad=True)\n model = torch.nn.ReplicationPad3d((pl, pr, pt, pbt, pf, pbk))\n\n # forward center\n out = model(x)\n self.assertEqual(out[:, :, pf : -pbk, pt : -pbt, pl : -pr], x)\n\n # backward center\n g = torch.randn_like(out)\n out.backward(g)\n self.assertEqual(x.grad[:, :, 1:-1, 1:-1, 1:-1], g[:, :, pf + 1 : -pbk - 1, pt + 1 : -pbt - 1, pl + 1 : -pr - 1])\n\n @onlyOnCPUAndCUDA\n @dtypes(torch.float32, torch.complex64)\n def test_ReflectionPad_empty(self, device, dtype):\n for mod, inp in [\n (torch.nn.ReflectionPad1d(2), torch.randn(0, 3, 10, device=device, dtype=dtype)),\n (torch.nn.ReflectionPad2d(2), torch.randn(0, 3, 10, 10, device=device, dtype=dtype))]:\n self._test_module_empty_input(mod, inp, check_size=False)\n\n with self.assertRaisesRegex(RuntimeError, '2D or 3D'):\n mod = torch.nn.ReflectionPad1d(2)\n inp = torch.randn(3, 0, 10, device=device, dtype=dtype)\n mod(inp)\n\n with self.assertRaisesRegex(RuntimeError, '3D or 4D'):\n mod = torch.nn.ReflectionPad2d(2)\n inp = torch.randn(3, 0, 10, 10, device=device, dtype=dtype)\n mod(inp)\n\n\n @onlyOnCPUAndCUDA\n @dtypes(torch.float, torch.double)\n def test_MarginLoss_empty(self, device, dtype):\n for mod, x, y in [\n (torch.nn.MultiMarginLoss().to(device),\n torch.randn(0, 10, requires_grad=True, device=device, dtype=dtype),\n torch.ones(0, device=device).type(torch.long)),\n (torch.nn.MultiLabelMarginLoss().to(device),\n torch.randn(0, 10, requires_grad=True, device=device, dtype=dtype),\n torch.ones(0, 10, device=device).type(torch.long))]:\n\n out = mod(x, y)\n out.sum().backward()\n\n self.assertEqual(x, torch.zeros_like(x))\n self.assertEqual(x.grad, torch.zeros_like(x))\n\n with self.assertRaisesRegex(RuntimeError, 'Expected'):\n x = torch.randn(0, requires_grad=True, device=device, dtype=dtype)\n y = torch.ones(10, device=device).type(torch.long)\n mod(x, y)\n\n with self.assertRaisesRegex(RuntimeError, 'Expected'):\n x = torch.randn(10, 0, requires_grad=True, device=device, dtype=dtype)\n y = torch.ones(10, 0, device=device).type(torch.long)\n mod(x, y)\n\n\n @onlyOnCPUAndCUDA\n def test_Unfold_empty(self, device):\n inp = torch.randn(0, 3, 3, 4, device=device)\n unfold = torch.nn.Unfold(kernel_size=(2, 3)).to(device)\n self._test_module_empty_input(unfold, inp, check_size=False)\n\n with self.assertRaisesRegex(RuntimeError, 'Expected 3D or 4D'):\n inp = torch.randn(3, 0, 3, 4, device=device)\n unfold = torch.nn.Unfold(kernel_size=(2, 3)).to(device)\n unfold(inp)\n\n @onlyCUDA\n @dtypes(torch.float, torch.double)\n @tf32_on_and_off(0.005)\n def test_rnn_fused(self, device, dtype):\n\n def copy_rnn(rnn1, rnn2):\n for x_layer, y_layer in zip(rnn1.all_weights, rnn2.all_weights):\n for x, y in zip(x_layer, y_layer):\n x.data.copy_(y.data)\n\n def check_rnn_grads(rnn1, rnn2):\n for x_layer, y_layer in zip(rnn1.all_weights, rnn2.all_weights):\n for x, y in zip(x_layer, y_layer):\n self.assertEqual(x.grad, y.grad, atol=5e-5, rtol=0)\n\n input_size = 10\n hidden_size = 6\n num_layers = 2\n seq_length = 7\n batch = 6\n input_val = torch.randn(seq_length, batch, input_size, dtype=dtype)\n grad_output = torch.randn(seq_length, batch, hidden_size, dtype=dtype)\n hx_val = torch.randn(num_layers, batch, hidden_size, dtype=dtype)\n grad_hy = torch.randn(num_layers, batch, hidden_size, dtype=dtype)\n with torch.backends.cudnn.flags(enabled=False, allow_tf32=None):\n for module in (nn.GRU, nn.LSTM):\n for bias in (True, False):\n rnn = module(input_size, hidden_size, num_layers, bias=bias).to(dtype)\n rnn_device = module(input_size, hidden_size, num_layers, bias=bias).to(device, dtype)\n copy_rnn(rnn, rnn_device)\n\n is_lstm = isinstance(rnn, nn.LSTM)\n if is_lstm:\n hx = (hx_val.clone().requires_grad_(True),\n hx_val.clone().add(1).requires_grad_(True))\n hx_device = (hx_val.clone().to(device).requires_grad_(True),\n hx_val.clone().to(device).add(1).requires_grad_(True))\n else:\n hx = hx_val.clone().requires_grad_(True)\n hx_device = hx_val.clone().to(device).requires_grad_(True)\n\n inp = input_val.clone().requires_grad_(True)\n inp_cu = input_val.clone().to(device).requires_grad_(True)\n output1, hy1 = rnn(inp, hx)\n output2, hy2 = rnn_device(inp_cu, hx_device)\n if is_lstm:\n torch.autograd.backward(\n [output1, hy1[0], hy1[1]], [grad_output, grad_hy, grad_hy + 1]\n )\n torch.autograd.backward(\n [output2, hy2[0], hy2[1]],\n [grad_output.to(device), grad_hy.to(device), (grad_hy + 1).to(device)]\n )\n else:\n torch.autograd.backward([output1, hy1], [grad_output, grad_hy])\n torch.autograd.backward([output2, hy2], [grad_output.to(device), grad_hy.to(device)])\n\n self.assertEqual(output1, output2)\n self.assertEqual(hy1, hy2)\n\n check_rnn_grads(rnn, rnn_device)\n self.assertEqual(inp.grad, inp_cu.grad)\n if is_lstm:\n self.assertEqual(hx[0].grad, hx_device[0].grad)\n self.assertEqual(hx[1].grad, hx_device[1].grad)\n else:\n self.assertEqual(hx.grad, hx_device.grad)\n\n def test_BatchNorm_empty(self, device):\n mod = torch.nn.BatchNorm2d(3).to(device)\n inp = torch.randn(0, 3, 2, 2, device=device)\n self._test_module_empty_input(mod, inp)\n if self.device_type == 'cuda' and self.has_cudnn():\n with torch.backends.cudnn.flags(enabled=False):\n self._test_module_empty_input(mod, inp)\n\n self.assertEqual(mod.running_mean, torch.tensor([0., 0, 0], device=device))\n self.assertEqual(mod.running_var, torch.tensor([1., 1, 1], device=device))\n self.assertEqual(mod.weight.grad, torch.tensor([0., 0, 0], device=device))\n self.assertEqual(mod.bias.grad, torch.tensor([0., 0, 0], device=device))\n\n def test_group_conv_empty(self, device):\n mod = torch.nn.Conv2d(4, 4, stride=2, kernel_size=3, padding=1, groups=4).to(device)\n inp = torch.randn(0, 4, 4, 4, device=device)\n self._test_module_empty_input(mod, inp, check_size=False)\n if self.device_type == 'cuda' and self.has_cudnn():\n with torch.backends.cudnn.flags(enabled=False):\n self._test_module_empty_input(mod, inp, check_size=False)\n\n def test_group_convTranspose_empty(self, device):\n mod = torch.nn.ConvTranspose2d(4, 4, stride=2, kernel_size=3, padding=1, groups=4).to(device)\n inp = torch.randn(0, 4, 4, 4, device=device)\n self._test_module_empty_input(mod, inp, check_size=False)\n if self.device_type == 'cuda' and self.has_cudnn():\n with torch.backends.cudnn.flags(enabled=False):\n self._test_module_empty_input(mod, inp, check_size=False)\n\n def test_convTranspose_empty(self, device):\n mod = torch.nn.ConvTranspose2d(4, 4, stride=2, kernel_size=3, padding=1).to(device)\n inp = torch.randn(0, 4, 4, 4, device=device)\n self._test_module_empty_input(mod, inp, check_size=False)\n if self.device_type == 'cuda' and self.has_cudnn():\n with torch.backends.cudnn.flags(enabled=False):\n self._test_module_empty_input(mod, inp, check_size=False)\n\n @onlyOnCPUAndCUDA\n def test_AvgPool2d_empty(self, device):\n avgpool = torch.nn.AvgPool2d(3, stride=2).to(device)\n inp = torch.randn(0, 16, 20, 32, device=device)\n self._test_module_empty_input(avgpool, inp, check_size=False)\n\n clast_inp = torch.randn(0, 16, 20, 32, device=device).contiguous(memory_format=torch.channels_last)\n self._test_module_empty_input(avgpool, clast_inp, check_size=False)\n\n # test with empty non-batch input\n with self.assertRaisesRegex(RuntimeError, '3D or 4D'):\n inp = torch.randn(16, 0, 20, 32, device=device)\n avgpool(inp)\n\n @onlyCUDA\n @largeTensorTest('16GB')\n def test_prelu_backward_32bit_indexing(self, device):\n m = torch.nn.PReLU().cuda().half()\n input_ = torch.ones((1024, 1024, 1024, 2), dtype=torch.half, device=device)\n output = m(input_)\n output.backward(input_)\n\n def test_linear_empty(self, device):\n mod = torch.nn.Linear(7, 7).to(device)\n inp = torch.randn(0, 7, device=device)\n self._test_module_empty_input(mod, inp)\n\n def test_one_hot(self, device):\n with self.assertRaises(RuntimeError):\n torch.nn.functional.one_hot(torch.tensor([3, 4, -1, 0], device=device), -1)\n\n with self.assertRaises(RuntimeError):\n torch.nn.functional.one_hot(torch.tensor([3, 4, 1, 0], device=device), 3)\n\n t = torch.nn.functional.one_hot(torch.tensor([3, 4, 1, 0], device=device))\n expected = torch.tensor([[0, 0, 0, 1, 0],\n [0, 0, 0, 0, 1],\n [0, 1, 0, 0, 0],\n [1, 0, 0, 0, 0]], device=device)\n self.assertEqual(t, expected)\n\n t = torch.nn.functional.one_hot(torch.tensor([3, 4, 1, 0], device=device), -1)\n expected = torch.tensor([[0, 0, 0, 1, 0],\n [0, 0, 0, 0, 1],\n [0, 1, 0, 0, 0],\n [1, 0, 0, 0, 0]], device=device)\n self.assertEqual(t, expected)\n\n t = torch.nn.functional.one_hot(torch.tensor([3, 4, 1, 0], device=device), 6)\n expected = torch.tensor([[0, 0, 0, 1, 0, 0],\n [0, 0, 0, 0, 1, 0],\n [0, 1, 0, 0, 0, 0],\n [1, 0, 0, 0, 0, 0]], device=device)\n self.assertEqual(t, expected)\n\n t = torch.nn.functional.one_hot(torch.tensor([[3, 4], [1, 0]], device=device))\n expected = torch.tensor([[[0, 0, 0, 1, 0],\n [0, 0, 0, 0, 1]],\n [[0, 1, 0, 0, 0],\n [1, 0, 0, 0, 0]]], device=device)\n self.assertEqual(t, expected)\n\n t = torch.nn.functional.one_hot(torch.tensor(4, device=device))\n expected = torch.tensor([0, 0, 0, 0, 1], device=device)\n self.assertEqual(t, expected)\n\n t = torch.nn.functional.one_hot(torch.empty([4, 0], dtype=torch.long, device=device), 100)\n expected = torch.empty([4, 0, 100])\n # TODO(#38095): Replace assertEqualIgnoreType. See issue #38095\n self.assertEqualIgnoreType(t, expected)\n\n with self.assertRaises(RuntimeError):\n torch.nn.functional.one_hot(torch.empty([4, 0], dtype=torch.long, device=device))\n\n with self.assertRaises(RuntimeError):\n torch.nn.functional.one_hot(torch.tensor([3, 4, 1, 0], device=device), -2)\n\n def test_nn_scalars(self, device):\n # One off tests to ensure scalars from nn.yaml are properly applied\n def verify_scalars(input, output):\n if input.dim() == 0:\n self.assertEqual((), output.shape)\n else:\n self.assertNotEqual((), output.shape)\n output.sum().backward()\n self.assertEqual(input.shape, input.grad.shape)\n\n for input_shape in [(5, 6), ()]:\n for module in [torch.nn.ELU, torch.nn.Hardtanh, torch.nn.LeakyReLU, torch.nn.LogSigmoid,\n torch.nn.RReLU, torch.nn.Softshrink, torch.nn.Softplus, torch.nn.Sigmoid,\n torch.nn.Tanh]:\n input = torch.randn(input_shape, device=device, requires_grad=True)\n m = module()\n output = m(input)\n verify_scalars(input, output)\n\n def test_nn_scalars_reductions(self, device):\n # One off tests to ensure scalars from nn.yaml are properly applied\n def verify_reduction_scalars(input, reduction, output):\n if reduction != 'none' or input.dim() == 0:\n self.assertEqual((), output.shape)\n else:\n self.assertNotEqual((), output.shape)\n output.sum().backward()\n self.assertEqual(input.shape, input.grad.shape)\n\n for input_shape in [(5, 6), ()]:\n for reduction in ['none', 'mean', 'sum']:\n for module in [torch.nn.BCELoss, torch.nn.L1Loss, torch.nn.MSELoss,\n torch.nn.SmoothL1Loss, torch.nn.SoftMarginLoss]:\n input = torch.randn(input_shape, device=device, requires_grad=True)\n target = torch.empty(input_shape, device=device).random_(2)\n sigmoid = nn.Sigmoid()\n\n input = torch.randn(input_shape, device=device, requires_grad=True)\n m = module(reduction=reduction)\n output = m(sigmoid(input), target)\n verify_reduction_scalars(input, reduction, output)\n\n # verify that bogus reduction strings are errors\n @onlyOnCPUAndCUDA\n def test_invalid_reduction_strings(self, device):\n input = torch.randn(3, 5, requires_grad=True, device=device)\n cinput = torch.randn(3, 5, requires_grad=True, device=device, dtype=torch.cfloat)\n target = torch.tensor([1, 0, 4], device=device)\n var = torch.ones(size=input.size(), requires_grad=True, device=device)\n\n for reduction in ['none', 'invalid']:\n def v(fn):\n if reduction == 'invalid':\n self.assertRaises(ValueError, lambda: fn())\n else:\n fn()\n\n v(lambda: F.nll_loss(input, target, reduction=reduction))\n v(lambda: F.cross_entropy(input, target, reduction=reduction))\n v(lambda: F.multi_margin_loss(input, target, reduction=reduction))\n\n v(lambda: F.kl_div(input, input, reduction=reduction))\n v(lambda: F.huber_loss(input, input, reduction=reduction))\n v(lambda: F.smooth_l1_loss(input, input, reduction=reduction))\n v(lambda: F.l1_loss(input, input, reduction=reduction))\n v(lambda: F.l1_loss(cinput, cinput, reduction=reduction))\n v(lambda: F.mse_loss(input, input, reduction=reduction))\n v(lambda: F.hinge_embedding_loss(input, input, reduction=reduction))\n v(lambda: F.poisson_nll_loss(input, input, reduction=reduction))\n v(lambda: F.gaussian_nll_loss(input, input, var, reduction=reduction))\n v(lambda: F.binary_cross_entropy_with_logits(input, input, reduction=reduction))\n\n zeros = torch.zeros_like(input).to(torch.int64)\n v(lambda: F.multilabel_soft_margin_loss(input, zeros, reduction=reduction))\n v(lambda: F.multilabel_margin_loss(input, zeros, reduction=reduction))\n\n v(lambda: F.triplet_margin_loss(input, input, input, reduction=reduction))\n v(lambda: F.triplet_margin_with_distance_loss(input, input, input, reduction=reduction))\n v(lambda: F.margin_ranking_loss(input, input, input.sign(), reduction=reduction))\n v(lambda: F.cosine_embedding_loss(input, input, input[:, 0].sign(), reduction=reduction))\n\n log_probs = torch.randn(50, 16, 20, requires_grad=True, device=device).log_softmax(2)\n targets = torch.randint(1, 20, (16, 30), dtype=torch.long, device=device)\n input_lengths = torch.full((16,), 50, dtype=torch.long, device=device)\n target_lengths = torch.randint(10, 30, (16,), dtype=torch.long, device=device)\n v(lambda: F.ctc_loss(log_probs, targets, input_lengths, target_lengths, reduction=reduction))\n\n # FIXME: should we allow derivatives on these?\n v(lambda: F.binary_cross_entropy(torch.sigmoid(input), input.detach(), reduction=reduction))\n v(lambda: F.soft_margin_loss(input, input.sign().detach(), reduction=reduction))\n\n @onlyOnCPUAndCUDA\n def test_smooth_l1_loss_vs_huber_loss(self, device):\n def _make_test_tensor(shape, contiguous=True):\n if contiguous:\n test_tensor = torch.randn(shape, device=device)\n else:\n # Select every other element in the innermost dimension to\n # make it non-contiguous.\n doubled_shape = list(shape)\n doubled_shape[-1] *= 2\n test_tensor = torch.randn(doubled_shape, device=device)\n test_tensor = test_tensor[..., ::2]\n return test_tensor\n\n def _test_smooth_l1_loss_vs_huber_loss_helper(input, target, beta, require_equal):\n for reduction in ['mean', 'sum', 'none']:\n smooth_l1 = torch.nn.SmoothL1Loss(beta=beta, reduction=reduction)\n # beta hyper-parameter is called delta for Huber\n huber = torch.nn.HuberLoss(delta=beta, reduction=reduction)\n smooth_l1_loss = smooth_l1(input, target)\n huber_loss = huber(input, target)\n\n if require_equal:\n self.assertEqual(smooth_l1_loss, huber_loss)\n else:\n # Huber loss should be larger than smooth L1 loss by a factor of beta.\n self.assertEqual(smooth_l1_loss * beta, huber_loss)\n\n def _test_smooth_l1_loss_vs_huber_loss_multi_input_helper(beta, require_equal):\n # Test the non-vectorized case.\n shape = (2, 2)\n _test_smooth_l1_loss_vs_huber_loss_helper(input=_make_test_tensor(shape),\n target=_make_test_tensor(shape),\n beta=beta,\n require_equal=require_equal)\n\n # Test the vectorized case (innermost dim > 32).\n shape = (64, 64)\n _test_smooth_l1_loss_vs_huber_loss_helper(input=_make_test_tensor(shape),\n target=_make_test_tensor(shape),\n beta=beta,\n require_equal=require_equal)\n\n # Test the non-contiguous case.\n _test_smooth_l1_loss_vs_huber_loss_helper(input=_make_test_tensor(shape, contiguous=False),\n target=_make_test_tensor(shape, contiguous=False),\n beta=beta,\n require_equal=require_equal)\n\n def test_equal_when_beta_is_one():\n _test_smooth_l1_loss_vs_huber_loss_multi_input_helper(beta=1.0, require_equal=True)\n\n def test_unequal_when_beta_is_less_than_one():\n _test_smooth_l1_loss_vs_huber_loss_multi_input_helper(beta=0.5, require_equal=False)\n\n def test_unequal_when_beta_is_greater_than_one():\n _test_smooth_l1_loss_vs_huber_loss_multi_input_helper(beta=1.5, require_equal=False)\n\n test_equal_when_beta_is_one()\n test_unequal_when_beta_is_less_than_one()\n test_unequal_when_beta_is_greater_than_one()\n\n # We don't want to make propagating NaN a hard requirement on ops, but for\n # these easy ones, we should make them do so.\n def test_nonlinearity_propagate_nan(self, device):\n def test(nonlinearity, *args, **kwargs):\n x = torch.tensor([nan], device=device)\n fn = getattr(F, nonlinearity)\n try:\n self.assertTrue(math.isnan(fn(x, *args, **kwargs).item()))\n except Exception as e:\n if 'not implemented' not in str(e):\n raise\n\n test('relu')\n test('relu', inplace=True)\n test('relu6')\n test('elu')\n test('selu')\n test('celu')\n test('rrelu')\n test('rrelu', inplace=True)\n test('hardtanh')\n test('tanh')\n test('sigmoid')\n test('logsigmoid')\n test('hardshrink')\n test('tanhshrink')\n test('softsign')\n test('softmin', 0)\n test('softmax', 0)\n test('log_softmax', 0)\n test('leaky_relu', 0.2)\n test('threshold', 3, 2)\n test('threshold', 3, 2, inplace=True)\n\n def test_pooling_shape(self, device):\n ''' Test the output shape calculation for pooling functions '''\n\n # Checks output shape against expected for 1D, 2D and 3D\n def check(expected_out_shape, sizes, *args, **kwargs):\n for kernel in ['max', 'avg']:\n for i in [1, 2, 3]:\n if hasattr(torch.nn.functional, f'{kernel}_pool{i}d'):\n op = getattr(torch.nn.functional, f'{kernel}_pool{i}d')\n t = torch.randn(sizes[:i + 2], device=device)\n self.assertEqual(op(t, *args, **kwargs).shape, expected_out_shape[:i + 2])\n\n check((1, 1, 3, 3, 4), (1, 1, 5, 6, 7), kernel_size=1, stride=2, padding=0, ceil_mode=True)\n check((1, 1, 2, 3, 3), (1, 1, 3, 4, 5), kernel_size=2, stride=2, padding=1, ceil_mode=False)\n check((1, 1, 2, 3, 3), (1, 1, 3, 4, 5), kernel_size=2, stride=2, padding=1, ceil_mode=True)\n\n # Test case from issue https://github.com/pytorch/pytorch/issues/45357\n x = torch.randn(1, 1, 6, 7, device=device)\n y = torch.nn.functional.max_pool2d(x, 1, stride=(2, 2), padding=0, ceil_mode=True)\n self.assertEqual(y.size(), (1, 1, 3, 4))\n\n @onlyOnCPUAndCUDA # TODO: fix on XLA\n def test_adaptive_avg_pool2d_output_size_one(self, device):\n def helper(size, memory_format):\n x = torch.randint(1, 10, size, dtype=torch.float, device=device, requires_grad=True)\n if memory_format == 'non_contiguous':\n x = x[::2, ::2, ::2, ::2]\n else:\n x = x.to(memory_format=memory_format)\n\n net = torch.nn.AdaptiveAvgPool2d((1, 1))\n out = net(x)\n ref_out = x.contiguous().mean((-1, -2)).view((x.size(0), x.size(1), 1, 1))\n\n out.sum().backward() # make sure it doesn't crash\n\n self.assertEqual(out, ref_out)\n if memory_format == torch.channels_last:\n self.assertTrue(out.is_contiguous(memory_format=torch.channels_last))\n c = out.size(1)\n self.assertEqual(out.stride(), [c, 1, c, c])\n else:\n self.assertTrue(out.is_contiguous())\n c = out.size(1)\n self.assertEqual(out.stride(), [c, 1, 1, 1])\n\n for mf in (torch.contiguous_format, torch.channels_last, 'non_contiguous'):\n helper((2, 3, 6, 6), mf)\n\n @onlyOnCPUAndCUDA\n def test_adaptive_avg_pool3d_output_size_one(self, device):\n x = torch.randn((2, 3, 6, 6, 6) , dtype=torch.float, device=device, requires_grad=True)\n\n net = torch.nn.AdaptiveAvgPool3d(1)\n out = net(x)\n ref_out = x.contiguous().mean((-1, -2, -3)).view(out.shape)\n\n out.sum().backward() # make sure it doesn't crash\n\n self.assertEqual(out, ref_out)\n self.assertTrue(out.is_contiguous())\n c = out.size(1)\n self.assertEqual(out.stride(), [c, 1, 1, 1, 1])\n\n\n @onlyOnCPUAndCUDA\n @dtypes(torch.uint8, torch.int8, torch.short, torch.int, torch.long)\n def test_adaptive_pooling_no_suppot_input(self, device, dtype):\n for numel in (2, 3):\n for pool_type in ('Max', 'Avg'):\n cls_name = 'Adaptive{}Pool{}d'.format(pool_type, numel)\n module_cls = getattr(nn, cls_name)\n output_size = (2,) * numel\n module = module_cls(output_size)\n input = torch.randn((4,) * (numel + 1), device=device).to(dtype)\n with self.assertRaisesRegex(RuntimeError, \"not implemented\"):\n output = module(input)\n\n @onlyCUDA\n @dtypesIfCUDA(torch.half, torch.float, torch.double)\n def test_avg_pool2d_nhwc(self, device, dtype):\n def helper(n, c, h, w, kernel_size, stride=None,\n count_include_pad=True, divisor_override=None, padding=0):\n if stride is None:\n stride = kernel_size\n input = torch.randn(n, c, h, w, dtype=dtype, device=device)\n input = input.contiguous(memory_format=torch.channels_last).requires_grad_()\n grad = torch.randn(n, c, (h - kernel_size) // stride + 1, (w - kernel_size) // stride + 1,\n dtype=dtype, device=device)\n pool = torch.nn.AvgPool2d(kernel_size, stride=stride, count_include_pad=count_include_pad,\n divisor_override=divisor_override).to(device)\n\n ref_input = input.detach().clone().contiguous().requires_grad_(True)\n ref_grad = grad.detach().clone().contiguous()\n ref_pool = torch.nn.AvgPool2d(kernel_size, stride=stride, count_include_pad=count_include_pad,\n divisor_override=divisor_override).to(device)\n\n out = pool(input)\n out.backward(grad)\n ref_out = ref_pool(ref_input)\n ref_out.backward(ref_grad)\n\n self.assertTrue(out.is_contiguous(memory_format=torch.channels_last))\n self.assertTrue(ref_out.is_contiguous())\n self.assertTrue(torch.allclose(out, ref_out))\n self.assertTrue(torch.allclose(input.grad, ref_input.grad))\n\n helper(4, 8, 8, 8, 3)\n helper(4, 8, 8, 8, 3, count_include_pad=False, padding=1)\n helper(4, 8, 8, 8, 3, count_include_pad=False, padding=2, stride=2)\n helper(4, 8, 8, 8, 3, divisor_override=42)\n helper(4, 8, 8, 8, 7)\n helper(200, 512, 28, 28, 2)\n helper(4, 8, 7, 7, 3, stride=1)\n helper(4, 8, 7, 7, 3, padding=2, stride=1)\n helper(10, 512, 31, 31, 3, stride=2)\n helper(1, 129, 8, 8, 3, stride=2)\n\n @onlyCPU\n @dtypes(torch.float)\n def test_max_pool1d_errors(self, device, dtype):\n def check(x, args, message):\n model = torch.nn.MaxPool1d(*args)\n with self.assertRaisesRegex(RuntimeError, r'max_pool1d\\(\\) ' + message):\n model(torch.tensor(x, device=device, dtype=dtype))\n\n # Pooling args: (kernel_size, stride, padding, dilation, return_indices, ceil_mode)\n check(0, (1,), \"input tensor must have 2 or 3 dimensions but got 0\")\n check([], (1,), \"input tensor must have 2 or 3 dimensions but got 1\")\n check([[]], (1, 0), \"stride must be greater than zero, but got 0\")\n check([[]], (1, 1, -1), \"padding must be non-negative, but got -1\")\n check([[]], (1, 1, 2), \"padding should be at most half of kernel size, but got padding=2 and kernel_size=1\")\n check([[]], (1, 1, 0, 0), \"dilation must be greater than zero, but got 0\")\n check([[]], (5, 1, 0, 1), \"Invalid computed output size: -4\")\n\n @onlyCPU\n @dtypes(torch.float, torch.double)\n def test_max_pool1d_corner_cases(self, device, dtype):\n def check(x, args, expected):\n model = torch.nn.MaxPool1d(*args)\n if isinstance(x, list):\n x = torch.tensor(x, device=device, dtype=dtype)\n expected = torch.tensor(expected, device=device, dtype=dtype)\n self.assertEqual(model(x), expected)\n\n # Pooling args: (kernel_size, stride, padding, dilation, return_indices, ceil_mode)\n check([[]], (1, None, 0, 1, False, False), [[]])\n check([[[]]], (1, None, 0, 1, False, False), [[[]]])\n check([[[]]], (2, 1, 1, 2, False, True), [[[]]])\n check([[1]], (1, None, 0, 1, False, False), [[1]])\n check([[1]], (2, None, 1, 2, False, False), [[float('-inf')]])\n check([[1], [1]], (2, None, 1, 2, False, False), [[float('-inf')], [float('-inf')]])\n check([[1, 2]], (2, 1, 1, 2, False, False), [[2, 1]])\n check([[1, 2]], (2, 2, 1, 2, False, True), [[2, 2]])\n\n empty_tensor = torch.empty((2, 0, 1), device=device, dtype=dtype)\n check(empty_tensor, (1, None, 0, 1, False, False), empty_tensor)\n\n @onlyCPU\n @dtypes(torch.float, torch.double)\n def test_max_pool1d(self, device, dtype):\n # FIXME For now compare against max_pool1d with indices\n def check(x, *args, **kwargs):\n model = torch.nn.MaxPool1d(*args, **kwargs)\n ref_model = torch.nn.MaxPool1d(*args, **kwargs, return_indices=True)\n self.assertEqual(model(x), ref_model(x)[0])\n\n sizes = [random.sample(range(8, 128), 3) for _ in range(3)]\n kernel_sizes = random.sample(range(1, 5), 3)\n strides = random.sample(range(1, 5), 3)\n dilations = random.sample(range(1, 5), 3)\n ceil_modes = [True, False]\n\n for size, kernel_size, stride, dilation, ceil_mode in \\\n itertools.product(sizes, kernel_sizes, strides, dilations, ceil_modes):\n padding = random.sample(range(0, math.floor(kernel_size / 2) + 1), 1)\n check(torch.randn(size, device=device, dtype=dtype),\n kernel_size, stride, padding, dilation, ceil_mode=ceil_mode)\n\n # Non-contiguous test\n tensor = torch.randn(5, 151, 33, device=device, dtype=dtype)[::2, ::3, ::2]\n check(tensor, 3, 2, 1, 2, ceil_mode=True)\n check(tensor.transpose(1, 2), 3, 2, 1, 2, ceil_mode=True)\n\n @onlyCUDA\n def test_max_pool2d(self, device):\n def helper(n, c, h, w, ks):\n x = torch.randn(n, c, h, w, device='cuda', dtype=torch.float, requires_grad=True)\n ref_x = x.detach().clone().cpu().requires_grad_()\n\n pool = torch.nn.MaxPool2d(kernel_size=ks)\n\n y = pool(x)\n ref_y = pool(ref_x)\n\n y.sum().backward()\n ref_y.sum().backward()\n\n self.assertEqual(y, ref_y)\n self.assertEqual(x.grad, ref_x.grad)\n\n helper(2, 8, 4, 4, ks=2)\n helper(1, 100000, 32, 32, ks=4)\n helper(1, 100000, 1, 4, ks=(1, 4)) # test for max_pool1d\n\n @onlyCUDA\n @dtypesIfCUDA(torch.half, torch.float, torch.double)\n def test_max_pool2d_nhwc(self, device, dtype):\n def helper(n, c, h, w, kernel_size, stride=None):\n if stride is None:\n stride = kernel_size\n input = torch.randn(n, c, h, w, dtype=dtype, device=device)\n input = input.contiguous(memory_format=torch.channels_last).requires_grad_()\n grad = torch.randn(n, c, (h - kernel_size) // stride + 1, (w - kernel_size) // stride + 1,\n dtype=dtype, device=device)\n pool = torch.nn.MaxPool2d(kernel_size, stride).to(device)\n\n ref_input = input.detach().clone().contiguous().requires_grad_(True)\n ref_grad = grad.detach().clone().contiguous()\n ref_pool = torch.nn.MaxPool2d(kernel_size, stride).to(device)\n\n out = pool(input)\n out.backward(grad)\n ref_out = ref_pool(ref_input)\n ref_out.backward(ref_grad)\n\n self.assertTrue(out.is_contiguous(memory_format=torch.channels_last))\n self.assertTrue(ref_out.is_contiguous())\n self.assertTrue(torch.allclose(out, ref_out))\n self.assertTrue(torch.allclose(input.grad, ref_input.grad))\n\n helper(4, 8, 8, 8, 7)\n helper(200, 512, 28, 28, 2)\n helper(4, 8, 7, 7, 3, stride=1)\n helper(10, 512, 31, 31, 3, stride=2)\n helper(1, 129, 8, 8, 3, stride=2)\n\n @onlyCUDA\n def test_max_pool2d_indices(self, device):\n def helper(n, c, h, w, ks):\n if n is None:\n x = torch.randn(c, h, w, device='cuda', dtype=torch.float, requires_grad=True)\n else:\n x = torch.randn(n, c, h, w, device='cuda', dtype=torch.float, requires_grad=True)\n\n ref_x = x.detach().clone().cpu().requires_grad_()\n\n pool = torch.nn.MaxPool2d(kernel_size=ks, return_indices=True)\n\n y, idx = pool(x)\n ref_y, ref_idx = pool(ref_x)\n\n y.sum().backward()\n ref_y.sum().backward()\n\n self.assertEqual(y, ref_y)\n self.assertEqual(idx, ref_idx) # assertEqual implicitly compares shape for tensors\n self.assertEqual(x.grad, ref_x.grad)\n\n helper(2, 8, 4, 4, ks=2)\n helper(None, 3, 50, 50, ks=5)\n\n def test_embedding_dense_grad(self, device):\n embd = nn.Embedding(20, 20).to(device)\n weight = embd.weight\n\n def fn_wrapper(device):\n def fn(weight):\n inp = torch.tensor([[0, 1, 1, 2], [3, 5, 7, 11]], dtype=torch.long).to(device)\n return torch.nn.functional.embedding(inp, weight)\n return fn\n\n fn = fn_wrapper(device)\n _assertGradAndGradgradChecks(self, fn, (weight, ))\n\n def test_embedding_scalar_weight_error(self, device):\n indices = torch.rand(2, 2, device=device).long()\n weight = torch.tensor(1.0, device=device)\n with self.assertRaisesRegex(RuntimeError, \"'weight' must be at least 1-D\"):\n torch.nn.functional.embedding(indices, weight)\n\n @dtypesIfCUDA(torch.float16, torch.float64)\n @dtypes(torch.float64)\n def test_embedding_backward(self, device, dtype):\n embedding = nn.Embedding(10, 3, sparse=True)\n tensor = torch.tensor([[7, 1, 3]])\n ones = torch.tensor(1.).expand(3, 3)\n tensorTwice = tensor.repeat(1, 2)\n onesTwice = torch.cat((ones, ones))\n\n embedding = embedding.to(dtype=dtype).to(device)\n tensor = tensor.to(device)\n ones = ones.to(device)\n tensorTwice = tensorTwice.to(device)\n onesTwice = onesTwice.to(device)\n\n embedding.zero_grad()\n embedding(tensor[0]).sum().backward()\n self.assertEqual(embedding.weight.grad._indices(), tensor)\n # TODO(#38095): Replace assertEqualIgnoreType. See issue #38095\n self.assertEqualIgnoreType(embedding.weight.grad._values(), ones)\n\n embedding.zero_grad()\n embedding(tensor[0]).sum().backward()\n embedding(tensor[0]).sum().backward()\n self.assertEqual(embedding.weight.grad._indices(), tensorTwice)\n # TODO(#38095): Replace assertEqualIgnoreType. See issue #38095\n self.assertEqualIgnoreType(embedding.weight.grad._values(), onesTwice)\n\n embedding.zero_grad()\n embedding(tensor[0]).sum().backward()\n tensor[0, 0] = 8\n embedding(tensor[0]).sum().backward()\n tensorTwice[0, 3] = 8\n self.assertEqual(embedding.weight.grad._indices(), tensorTwice)\n # TODO(#38095): Replace assertEqualIgnoreType. See issue #38095\n self.assertEqualIgnoreType(embedding.weight.grad._values(), onesTwice)\n\n @dtypesIfCUDA(*ALL_TENSORTYPES2)\n @dtypes(torch.float32)\n def test_embedding_padding_idx(self, device, dtype):\n embedding = nn.Embedding(10, 20, padding_idx=0).to(device, dtype)\n input = torch.tensor([[0, 2, 4, 5], [4, 3, 0, 9]], dtype=torch.long).to(device)\n output = embedding(input)\n self.assertEqual(output[0][0].sum(), 0)\n self.assertEqual(output[1][2].sum(), 0)\n\n embedding = nn.Embedding(10, 20, padding_idx=0, sparse=True).to(device, dtype)\n input = torch.tensor([[0, 2, 4, 5], [4, 3, 0, 9]], dtype=torch.long).to(device)\n output = embedding(input)\n self.assertEqual(output[0][0].sum(), 0)\n self.assertEqual(output[1][2].sum(), 0)\n\n # negative indexing check for padding_idx\n # padding_idx=-2, num_embeddings=10 ==> index 8 padded\n embedding = nn.Embedding(10, 20, padding_idx=-2).to(device, dtype)\n input = torch.tensor([[0, 2, 8, 5], [4, 8, 0, 9]], dtype=torch.long).to(device)\n output = embedding(input)\n self.assertEqual(output[0][2].sum(), 0)\n self.assertEqual(output[1][1].sum(), 0)\n\n embedding = nn.Embedding(10, 20, padding_idx=-2, sparse=True).to(device, dtype)\n input = torch.tensor([[0, 2, 8, 5], [4, 8, 0, 9]], dtype=torch.long).to(device)\n output = embedding(input)\n self.assertEqual(output[0][2].sum(), 0)\n self.assertEqual(output[1][1].sum(), 0)\n\n # change padding vector\n padding_vector = torch.ones(20, dtype=dtype, device=device)\n embedding = nn.Embedding(10, 20, padding_idx=2, sparse=True).to(device, dtype)\n with torch.no_grad():\n embedding.weight[2] = padding_vector\n input = torch.tensor([0, 2], dtype=torch.long).to(device)\n output = embedding(input)\n self.assertEqual(output[1], padding_vector)\n\n # out of bounds check for padding_idx\n self.assertRaises(AssertionError, nn.Embedding, num_embeddings=10, embedding_dim=20, padding_idx=25)\n self.assertRaises(AssertionError, nn.Embedding, num_embeddings=10, embedding_dim=20, padding_idx=-25)\n\n padding_idx = 0\n embedding = nn.Embedding(5, 2, padding_idx=padding_idx).to(device, dtype)\n for n in (1, 2, 1000): # Need large N to trigger all the methods we have implemented\n for other_indices in ([], [1, 3], [2]):\n indices = torch.tensor(other_indices + [padding_idx] * n, dtype=torch.long).to(device)\n pre = embedding.weight[padding_idx].clone()\n embedding(indices).sum().backward()\n after = (embedding.weight + embedding.weight.grad)[padding_idx]\n embedding.zero_grad()\n self.assertEqual(after, pre)\n\n # test double backward\n emb_sum = embedding(indices).sum()\n emb_grad = torch.autograd.grad(outputs=emb_sum, inputs=list(embedding.parameters()), retain_graph=True)\n scalar = emb_grad[0].sum() + emb_sum\n scalar.backward()\n after = (embedding.weight + embedding.weight.grad)[padding_idx]\n embedding.zero_grad()\n self.assertEqual(after, pre)\n\n # Test fails on Vg20\n @skipCUDAIfRocm\n @dtypesIfCUDA(torch.half, torch.float)\n @dtypes(torch.float)\n def test_softmax_results(self, device, dtype):\n # Non-even sizes and non-zero shifts test fallback paths in vectorized kernel\n # Note: dim1 > 1024 is needed to exercise the vectorized (non-persistent) path, (16, 30576) is BERT-esque\n sizes = [(0, 10), (32, 20), (10, 0), (31, 20), (32, 21), (31, 23), (32, 1536), (31, 2048), (33, 2049), (16, 30576)]\n shifts = [(0, 0), (1, 0), (0, 1), (1, 1)]\n for fn in [F.softmax, F.log_softmax]:\n for size in sizes:\n for shift in shifts:\n input = torch.rand(size, device=device, dtype=dtype)\n # Note: With the largest tests we can hit upper limit of fp16 when we\n # sum, so scale the input down to stay in a nicer range.\n if dtype == torch.float16:\n input = input / 100.\n input = input[shift[0]:, shift[1]:]\n # Note; Don't want to bprop back through slice op\n input = input.detach().requires_grad_(True)\n ref_input = input.clone().cpu().detach().requires_grad_(True)\n for dim in [0, 1]:\n ref_output = fn(ref_input, dtype=torch.float, dim=dim)\n output = fn(input, dtype=torch.float, dim=dim)\n grad_output = torch.rand_like(output)\n ref_grad_output = grad_output.clone().cpu().detach()\n grad_input, = torch.autograd.grad(output, input, grad_outputs=(grad_output), create_graph=True)\n ref_grad_input, = torch.autograd.grad(ref_output, ref_input,\n grad_outputs=(ref_grad_output), create_graph=True)\n grad_input.sum().backward()\n ref_grad_input.sum().backward()\n\n self.assertEqual(output, ref_output)\n self.assertEqual(grad_input, ref_grad_input)\n self.assertEqual(input.grad, ref_input.grad)\n\n @onlyCUDA\n @dtypesIfCUDA(torch.float, torch.half)\n @largeTensorTest(\"20GB\")\n @precisionOverride({torch.half: 0.001})\n def test_softmax_64bit_indexing(self, device, dtype):\n def run_test(*shape):\n x = torch.randn(shape, device=\"cuda\", dtype=torch.float16, requires_grad=True)\n y = F.log_softmax(x, dim=-1, dtype=dtype)\n y.backward(y)\n with torch.no_grad():\n xx = x.cpu().requires_grad_()\n yy = F.log_softmax(xx.float(), dim=-1).to(dtype)\n yy.backward(yy)\n self.assertEqual(y, yy)\n self.assertEqual(x.grad, xx.grad)\n\n run_test(1100000000, 2) # Illegal memory access https://github.com/pytorch/pytorch/issues/52715\n run_test(2200000000, 1) # invalid configuration argument https://github.com/pytorch/pytorch/issues/52716\n\n @dtypes(torch.float)\n @dtypesIfCUDA(torch.float, torch.half)\n def test_log_softmax_big(self, device, dtype):\n def _test_helper(shape):\n # generate a tensor with big numbers that are exactly representable in dtype\n # and are at a constant offset from tensor with small numbers\n # the logsoftmax of a small and big tensors should be equal\n x_small = torch.randint(100, shape, dtype=dtype, device=device)\n offset = 1.5e3 if dtype == torch.half else 1e7\n x_big = x_small + offset\n self.assertEqual(F.log_softmax(x_small, -1), F.log_softmax(x_big, -1))\n _test_helper((16, 4))\n if self.device_type == 'cuda':\n # test non-persistent softmax kernel\n _test_helper((4, 1536))\n\n @onlyCUDA\n @largeTensorTest('12GB')\n def test_conv_large_nosplit(self, device):\n # Here we just test the convolution correctly route to the fallback implementation\n # that is, it does not crash. The correctness of fallback implementation should be\n # covered in other tests\n dtype = torch.half if self.device_type == 'cuda' else torch.float\n conv1 = nn.Conv2d(2, 2, 8, 8).to(device).to(dtype)\n input_large = torch.randn(1, 2, 1024, 1024 * 1024, dtype=dtype, device=device)\n conv1(input_large)\n conv2 = torch.nn.Conv2d(1, 1024, 1, 1).to(device).to(dtype)\n input_large = torch.randn(1, 1, 2048, 1024 , dtype=dtype, device=device)\n conv2(input_large)\n\n def test_conv_noncontig_weights(self, device):\n for dim in (1, 2, 3):\n for grouped in (False, True):\n nc = 3\n groups = 3 if grouped else 1\n w = torch.randn([3] * dim, device=device)\n w = w.expand([nc, int(nc / groups)] + list(w.shape))\n w = w.detach().requires_grad_()\n x = torch.randn([1, nc] + ([5] * dim), device=device, requires_grad=True)\n y = getattr(F, 'conv{}d'.format(dim))(x, w, groups=groups)\n y.sum().backward()\n y = getattr(F, 'conv_transpose{}d'.format(dim))(x, w, groups=groups)\n y.sum().backward()\n\n def test_conv_noncontig_weights_and_bias(self, device):\n # need floats to exercise https://github.com/pytorch/pytorch/issues/16018\n for bias in [True, False]:\n conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3,\n bias=bias).to(device, torch.float)\n\n input_nc = torch.randn((1, 3, 224, 224, 2), device=device, dtype=torch.float)[:, :, :, :, 1]\n input_c = input_nc.contiguous()\n\n weight_nc = torch.randn((64, 3, 7, 7, 2), device=device, dtype=torch.float)[:, :, :, :, 1]\n conv1.weight = nn.Parameter(weight_nc)\n weight_c = conv1.weight.contiguous()\n\n if bias:\n bias_nc = torch.randn((64, 2), device=device, dtype=torch.float)[:, 1]\n conv1.bias = nn.Parameter(bias_nc)\n bias_c = conv1.bias.contiguous()\n\n out1 = conv1(input_nc)\n conv1.weight = nn.Parameter(weight_c)\n if bias:\n conv1.bias = nn.Parameter(bias_c)\n out2 = conv1(input_c)\n self.assertEqual(out1, out2)\n\n @onlyCUDA\n @tf32_on_and_off(0.005)\n def test_grid_sample_large(self, device):\n def issue_35202():\n input_tensor = torch.rand(1, 1, 480, 640, dtype=torch.float, device=device, requires_grad=True)\n coords = torch.tensor([[-10059144, 67680944], [67680944, 67680944]], dtype=torch.float, device=device)\n coords = coords.unsqueeze(0).unsqueeze(0).repeat(1, 1, 1, 1)\n result = torch.nn.functional.grid_sample(input_tensor, coords)\n self.assertEqual(result, torch.tensor([[[[0., 0.]]]], dtype=torch.float, device=device))\n result.backward(torch.ones_like(result))\n torch.cuda.synchronize()\n issue_35202()\n\n def issue_24823_1(dtype):\n image = torch.arange(27, 0, -1, dtype=dtype, device=device).view(1, 1, 3, 3, 3)\n image.requires_grad_()\n grid = torch.nn.functional.affine_grid(\n torch.tensor([[[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0]]], dtype=dtype, device=device),\n (1, 1, 3, 3, 3))\n grid[:, 1, 1, 1, 0] = float('inf')\n result = torch.nn.functional.grid_sample(image, grid, padding_mode='zeros')\n self.assertEqual(result, torch.tensor([[[[[27., 26., 25.], [24., 23., 22.], [21., 20., 19.]],\n [[18., 17., 16.], [15., 0., 13.], [12., 11., 10.]],\n [[9., 8., 7.], [6., 5., 4.], [3., 2., 1.]]]]],\n device=device, dtype=dtype))\n result.backward(torch.ones_like(result))\n expected_grad = torch.ones_like(image)\n expected_grad[0, 0, 1, 1, 1] = 0\n self.assertEqual(image.grad, expected_grad, atol=0.005, rtol=0)\n issue_24823_1(torch.half)\n issue_24823_1(torch.float)\n issue_24823_1(torch.double)\n\n def issue_24823_2():\n param = torch.tensor([[[-1.0e+20, 0.0, 0.0], [0.0, -1.0e+20, 0.0]]], dtype=torch.float, device=device)\n img = torch.zeros((1, 1, 4, 4), dtype=torch.float, device=device, requires_grad=True)\n grid = torch.nn.functional.affine_grid(param, img.size())\n result = torch.nn.functional.grid_sample(img, grid)\n self.assertEqual(result, torch.zeros(1, 1, 4, 4, device=device, dtype=torch.float))\n result.backward(torch.ones_like(result))\n torch.cuda.synchronize()\n issue_24823_2()\n\n @onlyCUDA\n @expectedAlertNondeterministic('grid_sampler_2d_backward_cuda', fn_has_device_arg=False)\n def test_grid_sample_2d_alert_nondeterministic(self, device):\n input = torch.empty(1, 1, 2, 2, device=device)\n grid = torch.empty(1, 1, 1, 2, device=device)\n input.requires_grad = True\n output = F.grid_sample(input, grid, align_corners=False)\n output.sum().backward()\n\n @onlyCUDA\n @expectedAlertNondeterministic('grid_sampler_3d_backward_cuda', fn_has_device_arg=False)\n def test_grid_sample_3d_alert_nondeterministic(self, device):\n input = torch.empty(1, 1, 2, 2, 2, device=device)\n grid = torch.empty(1, 1, 1, 2, 3, device=device)\n input.requires_grad = True\n output = F.grid_sample(input, grid, align_corners=False)\n output.sum().backward()\n\n @dtypes(torch.float, torch.double)\n @largeTensorTest(lambda self, device, dtype:\n # Compute sum of the large tensor sizes:\n # (im.numel() + small_image.numel() + small_image.grad.numel() +\n # large_view.grad.numel()) * sizeof(dtype)\n 32769 * (65536 + 3 * 65536 / 128) *\n torch.tensor([], dtype=dtype).element_size())\n def test_grid_sample_large_index_2d(self, device, dtype):\n # Test 64-bit indexing with grid_sample (gh-41656)\n # Try accessing the corners, there should be no segfault\n coords = torch.tensor([[[-1., -1.],\n [+1., -1.]],\n\n [[-1., +1.],\n [+1., +1.]]], device=device, dtype=dtype)\n coords = coords.expand(1, 2, 2, 2)\n im = torch.zeros([1, 1, 32769, 65536], device=device, dtype=dtype)\n\n # Compare sampling with large strides to the same op on a contiguous tensor\n coords = torch.rand(1, 4, 4, 2, device=device, dtype=dtype)\n large_view = im[..., 127::128]\n small_image = torch.rand_like(large_view)\n large_view[...] = small_image\n large_view.requires_grad, small_image.requires_grad = True, True\n self.assertTrue(\n sum(i * s for i, s in zip(large_view.size(), large_view.stride())) >= 2 ** 31,\n msg=\"View must use 64-bit indexing\")\n for mode, padding_mode, align_corners in itertools.product(\n ('nearest', 'bilinear', 'bicubic'), ('zeros', 'border', 'reflection'), (True, False)):\n a = F.grid_sample(\n small_image, coords, mode=mode,\n padding_mode=padding_mode, align_corners=align_corners)\n a.sum().backward()\n\n b = F.grid_sample(\n large_view, coords, mode=mode,\n padding_mode=padding_mode, align_corners=align_corners)\n b.sum().backward()\n\n self.assertEqual(a, b)\n self.assertEqual(small_image.grad, large_view.grad)\n\n small_image.grad.zero_()\n large_view.grad.zero_()\n\n @dtypes(torch.float, torch.double)\n @largeTensorTest(lambda self, device, dtype:\n # Compute sum of the large tensor sizes:\n # (im.numel() + small_image.numel() + small_image.grad.numel() +\n # large_view.grad.numel()) * sizeof(dtype)\n 2 * 32769 * (32768 + 3 * 32768 / 128) *\n torch.tensor([], dtype=dtype).element_size())\n def test_grid_sample_large_index_3d(self, device, dtype):\n # Test 64-bit indexing with grid_sample (gh-41656)\n # Try accessing the corners, there should be no segfault\n coords = torch.full((1, 2, 2, 2, 3), 1., device=device, dtype=dtype)\n im = torch.zeros([1, 1, 2, 32769, 32768], device=device, dtype=dtype)\n\n result = F.grid_sample(im, coords, align_corners=False)\n self.assertEqual(result, torch.zeros((1, 1, 2, 2, 2), device=device, dtype=dtype))\n\n # Compare sampling with large strides to the same op on a contiguous tensor\n coords = torch.rand(1, 1, 4, 4, 3, device=device, dtype=dtype)\n large_view = im[..., 127::128]\n small_image = torch.rand_like(large_view)\n large_view[...] = small_image\n small_image.requires_grad, large_view.requires_grad = True, True\n self.assertTrue(\n sum(i * s for i, s in zip(large_view.size(), large_view.stride())) >= 2 ** 31,\n msg=\"View must use 64-bit indexing\")\n for mode, padding_mode, align_corners in itertools.product(\n ('nearest', 'bilinear'), ('zeros', 'border', 'reflection'), (True, False)):\n a = F.grid_sample(\n small_image, coords, mode=mode,\n padding_mode=padding_mode, align_corners=align_corners)\n a.sum().backward()\n\n b = F.grid_sample(\n large_view, coords, mode=mode,\n padding_mode=padding_mode, align_corners=align_corners)\n b.sum().backward()\n\n self.assertEqual(a, b)\n self.assertEqual(small_image.grad, large_view.grad)\n\n small_image.grad.zero_()\n large_view.grad.zero_()\n\n @onlyCUDA\n @largeTensorTest('12GB')\n def test_conv_transposed_large(self, device):\n dtype = torch.half if self.device_type == 'cuda' else torch.float\n conv = nn.ConvTranspose2d(1, 1, 1, 1, bias=False).to(device).to(dtype)\n input_large = torch.randn(4096, 1, 512, 1024, dtype=dtype, device=device)\n # forward\n ret = conv(input_large)\n maxdiff0 = (ret.narrow(0, 0, 1024) - conv(input_large.narrow(0, 0, 1024))).abs_().max().item()\n maxdiff1 = (ret.narrow(0, 1024, 1024) - conv(input_large.narrow(0, 1024, 1024))).abs_().max().item()\n maxdiff2 = (ret.narrow(0, 2048, 1024) - conv(input_large.narrow(0, 2048, 1024))).abs_().max().item()\n maxdiff3 = (ret.narrow(0, 3072, 1024) - conv(input_large.narrow(0, 3072, 1024))).abs_().max().item()\n self.assertEqual(maxdiff0, 0)\n self.assertEqual(maxdiff1, 0)\n self.assertEqual(maxdiff2, 0)\n self.assertEqual(maxdiff3, 0)\n\n @onlyCUDA\n @skipCUDAIfRocm\n @largeTensorTest('12GB')\n def test_conv_large(self, device):\n dtype = torch.half if self.device_type == 'cuda' else torch.float\n conv = nn.Conv2d(2, 2, 8, 8, bias=False).to(device).to(dtype)\n input_large = torch.randn(4097, 2, 512, 512, dtype=dtype, device=device)\n # forward\n ret = conv(input_large)\n self.assertEqual(ret[:2048], conv(input_large[:2048]))\n self.assertEqual(ret[2048:4096], conv(input_large[2048:4096]))\n self.assertEqual(ret[4096:], conv(input_large[4096:]))\n\n # backward\n conv.zero_grad()\n # When computing the backward, we are using the `max(dim=1)`` to create\n # some sparsity. Without this sparsity, the rounding error would be\n # too large (as large as 1e-5) to satisfy the creterion (1e-6) of `assertEqual`\n ret.view(4097, -1).max(dim=1).values.sum().backward()\n del ret\n grad1 = conv.weight.grad.detach().clone()\n conv.zero_grad()\n conv(input_large[:2048]).view(2048, -1).max(dim=1).values.sum().backward()\n conv(input_large[2048:4096]).view(2048, -1).max(dim=1).values.sum().backward()\n conv(input_large[4096:]).view(1, -1).max(dim=1).values.sum().backward()\n grad2 = conv.weight.grad.detach().clone()\n # gradients are at the order of hundreds, we need to scale it to\n # the order of one so that we can compare\n scale = 1 / grad1.abs().mean()\n grad1 = grad1 * scale\n grad2 = grad2 * scale\n self.assertEqual(grad1, grad2)\n\n def _test_gumbel_softmax_st_shapes(self, device, dtype, shape, dim, count_expected):\n logits = torch.randn(shape, dtype=torch.float, device=device)\n logits = logits.to(dtype)\n\n y_draw = F.gumbel_softmax(logits, hard=True, dim=dim)\n\n # All values positive\n self.assertGreaterEqual(y_draw.min(), 0)\n # Shape unchanged\n self.assertTrue(y_draw.shape == logits.shape)\n # One choice per draw\n self.assertEqual(y_draw.sum(), count_expected, atol=torch.finfo(y_draw.dtype).eps, rtol=0)\n\n def _test_gumbel_softmax_straight_through(self, device, dtype):\n num_draws = 100\n\n logits = torch.tensor([[0.2, 0.8, 0.1]], device=device)\n logits = logits.reshape([1, 3])\n logits = logits.to(dtype).requires_grad_()\n probs = logits.softmax(dim=-1)\n\n counts = torch.zeros_like(logits)\n for _ in range(num_draws):\n y_draw = F.gumbel_softmax(logits, hard=True)\n counts = counts + y_draw\n\n # All values positive\n self.assertGreaterEqual(y_draw.min(), 0)\n # Each experiment should result in 1 draw.\n self.assertEqual(counts.sum(), num_draws, atol=torch.finfo(counts.dtype).eps, rtol=0)\n\n # check results is asymptotically as expected.\n expected = probs * num_draws\n # ~z is approximately N(0,1) for unbiased count\n z = (counts - expected) / (expected * (1 - probs)).sqrt()\n # A (lazy) approximate 99% two-sided test:\n # occurs with prob alpha~>=0.01 if unbiased\n self.assertLess(z.abs().max().item(), 2.58)\n\n def _test_gumbel_softmax_grad(self, device, dtype):\n # \"hard\" and \"not hard\" should propagate same gradient.\n logits_soft = torch.zeros(10, 10, dtype=dtype, device=device, requires_grad=True)\n logits_hard = torch.zeros(10, 10, dtype=dtype, device=device, requires_grad=True)\n\n seed = torch.random.get_rng_state()\n y_soft = F.gumbel_softmax(logits_soft, hard=False)\n torch.random.set_rng_state(seed)\n y_hard = F.gumbel_softmax(logits_hard, hard=True)\n\n y_soft.sum().backward()\n y_hard.sum().backward()\n\n # 2eps = 1x addition + 1x subtraction.\n tol = 2 * torch.finfo(dtype).eps\n self.assertEqual(logits_soft.grad, logits_hard.grad, atol=tol, rtol=0)\n\n @dtypesIfCUDA(torch.half, torch.float, torch.double)\n @dtypes(torch.float, torch.double)\n def test_gumbel_softmax(self, device, dtype):\n self._test_gumbel_softmax_st_shapes(device, dtype, shape=[5], dim=0, count_expected=1)\n self._test_gumbel_softmax_st_shapes(device, dtype, shape=[5], dim=-1, count_expected=1)\n self._test_gumbel_softmax_st_shapes(device, dtype, shape=[5, 4], dim=1, count_expected=5)\n self._test_gumbel_softmax_st_shapes(device, dtype, shape=[5, 4, 3], dim=1, count_expected=5 * 3)\n self._test_gumbel_softmax_st_shapes(device, dtype, shape=[5, 4, 3], dim=-1, count_expected=5 * 4)\n self._test_gumbel_softmax_straight_through(device, dtype)\n self._test_gumbel_softmax_grad(device, dtype)\n\n def _test_rnn_retain_variables(self, device, dtype):\n rnns = [nn.LSTM(10, 20, num_layers=2).to(device, dtype),\n nn.GRU(10, 20, num_layers=2).to(device, dtype),\n nn.RNN(10, 20, num_layers=2).to(device, dtype)]\n for rnn in rnns:\n input = torch.randn(5, 6, 10, device=device, dtype=dtype, requires_grad=True)\n output = rnn(input)\n output[0].sum().backward(retain_graph=True)\n grads = [input.grad.data.clone()] + [p.grad.data.clone() for p in rnn.parameters()]\n for _ in range(4):\n rnn.zero_grad()\n input.grad.data.zero_()\n output[0].sum().backward(retain_graph=True)\n grads2 = [input.grad.data] + [p.grad.data for p in rnn.parameters()]\n self.assertEqual(grads, grads2)\n\n @dtypesIfCUDA(torch.half, torch.float, torch.double)\n @dtypes(torch.double)\n def test_rnn_retain_variables(self, device, dtype):\n self._test_rnn_retain_variables(device, dtype)\n\n if self.device_type == 'cuda' and self.has_cudnn():\n with torch.backends.cudnn.flags(enabled=False):\n self._test_rnn_retain_variables(device, dtype)\n\n @onlyCUDA\n def test_upsamplingNearest1d_launch_config(self, device):\n m = nn.Upsample(scale_factor=2)\n inp = torch.rand(2**25, 1, 1, device=device)\n out = m(inp)\n inp_ref = inp.cpu()\n out_ref = m(inp_ref)\n self.assertEqual(out_ref, out)\n\n @onlyCUDA\n def test_upsamplingNearest2d_launch_config(self, device):\n m = nn.Upsample(scale_factor=2)\n inp = torch.rand(2**25, 1, 1, 1, device=device)\n out = m(inp)\n inp_ref = inp.cpu()\n out_ref = m(inp_ref)\n self.assertEqual(out_ref, out)\n\n @onlyCUDA\n def test_upsamplingNearest3d_launch_config(self, device):\n m = nn.Upsample(scale_factor=2)\n inp = torch.rand(2**25, 1, 1, 1, 1, device=device)\n out = m(inp)\n inp_ref = inp.cpu()\n out_ref = m(inp_ref)\n self.assertEqual(out_ref, out)\n\n @unittest.expectedFailure\n @skipIfRocm\n @onlyCUDA\n def test_upsamplingNearest2d_launch_fail(self, device):\n m = nn.Upsample(scale_factor=2)\n # launch grid_y == 2**16 (larger than maximum y-dimension limit 65535)\n inp = torch.rand(1, 1, 2**15, 2**8, device=device)\n out = m(inp)\n\n @onlyCUDA\n @skipCUDAIfNotRocm\n def test_upsamplingNearest2d_launch_rocm(self, device):\n # test_upsamplingNearest2d_launch_fail should run OK on ROCm\n m = nn.Upsample(scale_factor=2)\n inp = torch.rand(1, 1, 2**15, 2**8, device=device)\n out = m(inp)\n\n @onlyCUDA\n @skipCUDAIfCudnnVersionLessThan(7600)\n def test_CTCLoss_cudnn(self, device):\n target_lengths = [30, 25, 20]\n input_lengths = [50, 50, 50]\n targets = torch.randint(1, 15, (sum(target_lengths),), dtype=torch.int)\n log_probs = torch.randn(50, 3, 15, dtype=torch.float, device=device).log_softmax(2)\n res = torch.nn.functional.ctc_loss(log_probs, targets, input_lengths, target_lengths)\n expected = ctcloss_reference(log_probs, targets.cuda(), input_lengths, target_lengths).float()\n with torch.backends.cudnn.flags(enabled=False):\n res2 = torch.nn.functional.ctc_loss(log_probs, targets.cuda().long(), input_lengths, target_lengths)\n self.assertEqual(res, expected)\n self.assertEqual(res2, res)\n\n @onlyCUDA\n @skipCUDAIfNoCudnn\n def test_contig_wrong_stride_cudnn(self, device):\n # x has to have batch_size 1 to test contiguous checks\n x = torch.randn(1, 16, 5, 5, device=device)\n stride = list(x.stride())\n stride[0] = 20\n # change the stride in dimension 0. the tensor is still contiguous because size[0] is 1\n x.set_(x.storage(), 0, x.size(), stride)\n self.assertTrue(x.is_contiguous())\n F.conv_transpose2d(x, torch.randn(16, 1, 1, 1, device=device))\n F.conv2d(x, torch.randn(1, 16, 1, 1, device=device))\n\n @onlyCUDA\n def test_Conv2d_size_1_kernel(self, device):\n x_cpu = torch.randn(2, 3, 5, 5)\n conv_cpu = torch.nn.Conv2d(3, 3, kernel_size=1)\n y_cpu = conv_cpu(x_cpu)\n y = torch.rand_like(y_cpu)\n y_cpu.backward(y)\n\n with cudnn.flags(enabled=False):\n conv_cuda = torch.nn.Conv2d(3, 3, kernel_size=1).to(device)\n conv_cuda.bias.data.copy_(conv_cpu.bias.data)\n conv_cuda.weight.data.copy_(conv_cpu.weight.data)\n y_cuda = conv_cuda(x_cpu.to(device))\n y_cuda.backward(y.to(device))\n\n self.assertEqual(y_cpu, y_cuda, atol=1e-5, rtol=0, exact_device=False)\n self.assertEqual(conv_cpu.bias.grad.data, conv_cuda.bias.grad.data, atol=1e-5, rtol=0, exact_device=False)\n self.assertEqual(conv_cpu.weight.grad.data, conv_cuda.weight.grad.data, atol=1e-5, rtol=0, exact_device=False)\n\n @onlyCUDA\n def test_ConvTranspose2d_size_1_kernel(self, device):\n x_cpu = torch.randn(2, 3, 5, 5)\n conv_cpu = torch.nn.ConvTranspose2d(3, 3, kernel_size=1)\n y_cpu = conv_cpu(x_cpu)\n y = torch.rand_like(y_cpu)\n y_cpu.backward(y)\n\n with cudnn.flags(enabled=False):\n conv_cuda = torch.nn.ConvTranspose2d(3, 3, kernel_size=1).to(device)\n conv_cuda.bias.data.copy_(conv_cpu.bias.data)\n conv_cuda.weight.data.copy_(conv_cpu.weight.data)\n y_cuda = conv_cuda(x_cpu.to(device))\n y_cuda.backward(y.to(device))\n\n self.assertEqual(y_cpu, y_cuda, atol=1e-5, rtol=0, exact_device=False)\n self.assertEqual(conv_cpu.bias.grad.data, conv_cuda.bias.grad.data, atol=1e-5, rtol=0, exact_device=False)\n self.assertEqual(conv_cpu.weight.grad.data, conv_cuda.weight.grad.data, atol=1e-5, rtol=0, exact_device=False)\n\n @onlyCUDA\n def test_ConvTranspose3d_size_1_kernel(self, device):\n x_cpu = torch.randn(2, 3, 3, 5, 5)\n conv_cpu = torch.nn.ConvTranspose3d(3, 3, kernel_size=1)\n y_cpu = conv_cpu(x_cpu)\n y = torch.rand_like(y_cpu)\n y_cpu.backward(y)\n\n with cudnn.flags(enabled=False):\n conv_cuda = torch.nn.ConvTranspose3d(3, 3, kernel_size=1).to(device)\n conv_cuda.bias.data.copy_(conv_cpu.bias.data)\n conv_cuda.weight.data.copy_(conv_cpu.weight.data)\n y_cuda = conv_cuda(x_cpu.to(device))\n y_cuda.backward(y.to(device))\n\n self.assertEqual(y_cpu, y_cuda, atol=1e-5, rtol=0, exact_device=False)\n self.assertEqual(conv_cpu.bias.grad.data, conv_cuda.bias.grad.data, atol=1e-5, rtol=0, exact_device=False)\n self.assertEqual(conv_cpu.weight.grad.data, conv_cuda.weight.grad.data, atol=1e-5, rtol=0, exact_device=False)\n\n def _ordered_sequence(self, device, dtype):\n \"\"\"Create ordered list of random sequences\"\"\"\n seqs = [torch.empty(random.randint(1, 6), device=device, dtype=dtype)\n for _ in range(5)]\n seqs = [s.random_(-128, 128) for s in seqs]\n ordered = sorted(seqs, key=len, reverse=True)\n return ordered\n\n def _padded_sequence(self, device, dtype):\n \"\"\"Create Tensor of random padded sequences\"\"\"\n ordered = self._ordered_sequence(device, dtype)\n lengths = [len(i) for i in ordered]\n padded_tensor = rnn_utils.pad_sequence(ordered)\n return padded_tensor, lengths\n\n @onlyCUDA\n def test_device_mask(self, device):\n for enforce_sorted in [True, False]:\n padded, lengths = self._padded_sequence('cpu', torch.float)\n packed = rnn_utils.pack_padded_sequence(\n padded, lengths, enforce_sorted=enforce_sorted)\n self.assertFalse(packed.is_cuda)\n packed = packed.to(device)\n self.assertTrue(packed.is_cuda)\n unpacked, _ = rnn_utils.pad_packed_sequence(packed)\n self.assertTrue(unpacked.is_cuda)\n self.assertEqual(unpacked.dtype, torch.float)\n\n @onlyCUDA\n def test_overwrite_module_params_on_conversion_cpu_device(self, device):\n # Test that under the current default settings\n # (`torch.__future__.get_overwrite_module_params_on_conversion() == False`),\n # a view to a module's parameters is not pointing to the same storage as\n # its base variable after converting the module to a different device.\n m = nn.Linear(20, 10)\n mw = m.weight[:]\n m.to(device)\n with torch.no_grad():\n # Without using `torch.no_grad()`, this will leak CUDA memory.\n # (Issue is filed at https://github.com/pytorch/pytorch/issues/21875)\n mw[0][0] = 5\n self.assertTrue(mw[0][0].device.type == \"cpu\")\n self.assertTrue(mw._base[0][0].device.type == \"cuda\")\n\n try:\n torch.__future__.set_overwrite_module_params_on_conversion(True)\n\n # Test that if `torch.__future__.get_overwrite_module_params_on_conversion() == True`,\n # a view to a module's parameters is still pointing to the same storage as\n # its base variable after converting the module to a different device.\n m = nn.Linear(20, 10)\n mw = m.weight[:]\n m.to(device)\n with torch.no_grad():\n mw[0][0] = 5\n self.assertTrue(mw[0][0] == mw._base[0][0])\n\n # Test that if `torch.__future__.get_overwrite_module_params_on_conversion() == True`,\n # `cpu_module.to(\"cuda\")` doesn't preserve previous references to\n # `cpu_module`'s parameters or gradients.\n m = nn.Linear(20, 10)\n m.weight.grad = torch.randn(10, 20)\n weight_ref = m.weight\n weight_grad_ref = m.weight.grad\n m.to(device)\n self.assertNotEqual(weight_ref.device, m.weight.device)\n self.assertNotEqual(weight_grad_ref.device, m.weight.grad.device)\n finally:\n torch.__future__.set_overwrite_module_params_on_conversion(False)\n\n @onlyCUDA\n @dtypes(*ALL_TENSORTYPES2)\n def test_embedding_max_norm_device(self, device, dtype):\n embedding = nn.Embedding(22, 5, max_norm=1.0).to(device, dtype=dtype)\n # nn.Embedding only takes LongTensor as input\n input = torch.tensor([2, 8, 8, 6], device=device, dtype=torch.long)\n output = embedding(input)\n self.assertEqual(output[1], output[2])\n self.assertTrue(output.data.norm(p=2, dim=1).le(1).all())\n\n # Test fails on Vg20\n @skipCUDAIfRocm\n @onlyCUDA\n @dtypes(torch.half, torch.float)\n def test_softmax(self, device, dtype):\n input = torch.rand(32, 100, device=device, dtype=dtype, requires_grad=True)\n inputf = input.to(torch.float).detach().requires_grad_(True)\n out = F.softmax(input, dim=-1, dtype=torch.float)\n outf = F.softmax(inputf, dim=-1)\n # should be bitwise equal\n self.assertEqual(out, outf, atol=0, rtol=0)\n gO = torch.empty_like(outf).uniform_()\n out.backward(gO)\n outf.backward(gO)\n # should be bitwise equal\n self.assertEqual(input.grad, inputf.grad.to(dtype), atol=0, rtol=0)\n\n @onlyCUDA\n def test_pool3d_size_one_feature_dim(self, device):\n # Tests crazy strides for feature dim of size 1\n x = torch.randn(7, 1, 5, 3, 2, device=device)\n strange_strides = [30, 1234, 6, 2, 1]\n y = x.as_strided(x.size(), strange_strides)\n x = x.cpu().as_strided(x.size(), strange_strides)\n\n to_test = {\n 'max_pool3d': lambda t: F.max_pool3d(t, (5, 1, 1), stride=(5, 1, 1)),\n 'avg_pool3d': lambda t: F.avg_pool3d(t, (5, 1, 1), stride=(5, 1, 1)),\n }\n\n for test, fn in to_test.items():\n # Should not crash\n out_y = fn(y)\n out_x = fn(x)\n self.assertEqual(out_y, out_x.to(device), msg=test)\n\n @onlyCUDA\n @largeTensorTest('6GB')\n def test_pool3d_large_size_int64(self, device):\n # See https://github.com/pytorch/pytorch/issues/52822\n x = torch.randn(70, 32, 100, 100, 100, dtype=torch.half, device=device)\n y = torch.nn.functional.max_pool3d(x, 5)\n torch.cuda.synchronize()\n\n ref_x = x.cpu().float() # max_pool3d_cpu is not implemented for half\n ref_y = torch.nn.functional.max_pool3d(ref_x, 5)\n\n self.assertEqual(y, ref_y, exact_dtype=False)\n\n @onlyCUDA\n def test_AvgPool3d_backward_after_cat_dim1_device(self, device):\n # x has to have batch_size 1 to test contiguous checks\n x = torch.randn(1, 3, 4, 4, 4, device=device, requires_grad=True)\n y = F.avg_pool3d(x, kernel_size=3, padding=1, stride=2)\n\n grad = torch.randn(y.size(), device=device)\n # increase the stride in dimension 0. the tensor is still contiguous because size[0] is 1\n stride = list(grad.stride())\n stride[0] = stride[0] * 2\n grad.set_(grad.storage(), 0, grad.size(), stride)\n assert grad.is_contiguous()\n\n y.backward(grad)\n\n def test_pooling_size_empty(self, device):\n t = torch.rand([1, 2, 3, 4], device=device)\n self.assertRaises(RuntimeError, lambda: F.adaptive_avg_pool1d(t, []))\n self.assertRaises(RuntimeError, lambda: F.adaptive_avg_pool2d(t, []))\n self.assertRaises(RuntimeError, lambda: F.adaptive_avg_pool3d(t, []))\n self.assertRaises(RuntimeError, lambda: F.adaptive_max_pool1d(t, []))\n self.assertRaises(RuntimeError, lambda: F.adaptive_max_pool2d(t, []))\n self.assertRaises(RuntimeError, lambda: F.adaptive_max_pool3d(t, []))\n\n @dtypes(torch.int, torch.long)\n def test_embedding_bag_empty_input(self, device, dtype):\n m = 4\n n = 3\n x = torch.tensor([], device=device, dtype=dtype)\n for sparse in [True, False]:\n Embed = torch.nn.EmbeddingBag(m, n, sparse=sparse)\n Embed.to(device)\n\n output = Embed(input=x, offsets=torch.tensor([0], device=device, dtype=dtype))\n self.assertEqual(output, torch.zeros_like(output))\n\n output = Embed(input=x, offsets=torch.tensor([0, 0], device=device, dtype=dtype))\n self.assertEqual(output, torch.zeros_like(output))\n\n @dtypes(torch.int, torch.long)\n def test_EmbeddingBag_per_sample_weights_failures(self, device, dtype):\n # Failure 1: mismatched embeddings / per_sample_weights dtype\n es = nn.EmbeddingBag(5, 2, mode='sum').to(dtype=torch.float, device=device)\n input = torch.tensor([3, 1, 1, 1, 4, 0], dtype=dtype, device=device)\n offsets = torch.tensor([0, 0, 3, 3, 6], dtype=dtype, device=device)\n per_sample_weights = torch.randn_like(input, dtype=torch.double, device=device)\n if device == 'cpu':\n with self.assertRaisesRegex(RuntimeError, 'have the same type as'):\n es(input, offsets, per_sample_weights)\n else:\n with self.assertRaisesRegex(RuntimeError, 'expected scalar type'):\n es(input, offsets, per_sample_weights)\n\n # Failure 2.1: input/per_sample_weights have different sizes (1d input)\n input = torch.tensor([3, 1, 1, 1, 4, 0], dtype=dtype, device=device)\n offsets = torch.tensor([0, 0, 3, 3, 6], dtype=dtype, device=device)\n per_sample_weights = torch.randn(5, dtype=torch.float, device=device)\n with self.assertRaisesRegex(ValueError, 'same shape as the input'):\n es(input, offsets, per_sample_weights)\n\n # Failure 2.2: input/per_sample_weights have different sizes (2d input)\n input = torch.randint(5, (7, 3), dtype=dtype, device=device)\n offsets = None\n per_sample_weights = torch.randn(7 * 3, dtype=torch.float, device=device)\n with self.assertRaisesRegex(ValueError, 'same shape as the input'):\n es(input, offsets, per_sample_weights)\n\n # Failure 3: Unsupported per_sample_weights and mode=('max', 'mean')\n for unsupported_mode in ('max', 'mean'):\n es = nn.EmbeddingBag(5, 2, mode=unsupported_mode).to(\n dtype=torch.float, device=device)\n input = torch.randint(5, (7, 3), dtype=dtype, device=device)\n offsets = None\n per_sample_weights = torch.randn(7, 3, dtype=torch.float, device=device)\n with self.assertRaisesRegex(NotImplementedError,\n \"only supported for mode='sum'\"):\n es(input, offsets, per_sample_weights)\n\n def _embedding_bag_reference_impl(self, input, weight, offsets=None, mode='sum',\n per_sample_weights=None, include_last_offset=False):\n assert mode == 'sum' or per_sample_weights is None\n assert offsets is not None\n if per_sample_weights is None:\n per_sample_weights = torch.ones(input.size()).to(\n dtype=weight.dtype, device=weight.device\n )\n assert input.numel() == per_sample_weights.numel()\n\n bags = []\n long_input = input.to(torch.long)\n embeddings = weight.index_select(0, long_input) * per_sample_weights.unsqueeze(1)\n if include_last_offset:\n for index in range(len(offsets) - 1):\n offset = offsets[index]\n next_offset = offsets[index + 1]\n length = next_offset - offset\n if length == 0:\n bags.append(\n torch.Tensor([0] * weight.size(1)).to(\n dtype=embeddings.dtype, device=embeddings.device\n )\n )\n else:\n if mode == 'sum':\n bags.append(embeddings.narrow(0, offset, length).sum(0))\n elif mode == 'mean':\n bags.append(embeddings.narrow(0, offset, length).sum(0).div(length))\n else:\n assert mode == 'max'\n bags.append(embeddings.narrow(0, offset, length).max(0)[0])\n else:\n for index, offset in enumerate(offsets):\n if index + 1 < len(offsets):\n next_offset = offsets[index + 1]\n else:\n next_offset = len(long_input)\n length = next_offset - offset\n if length == 0:\n bags.append(\n torch.Tensor([0] * weight.size(1)).to(\n dtype=embeddings.dtype, device=embeddings.device\n )\n )\n else:\n if mode == 'sum':\n bags.append(embeddings.narrow(0, offset, length).sum(0))\n elif mode == 'mean':\n bags.append(embeddings.narrow(0, offset, length).sum(0).div(length))\n else:\n assert mode == 'max'\n bags.append(embeddings.narrow(0, offset, length).max(0)[0])\n return torch.stack(bags)\n\n @dtypesIfCUDA(*itertools.product((torch.int, torch.long), (torch.float, torch.double, torch.half)))\n @dtypes(*itertools.product((torch.int, torch.long), (torch.float, torch.double)))\n def test_EmbeddingBag_empty_per_sample_weights_and_offsets(self, device, dtypes):\n # Test empty input and per sample weight, and backward pass. There was a CUDA\n # invalid configuration bug (more context in #46572)\n def test_per_sample_weights(mode, trainable_scale):\n es = nn.EmbeddingBag(5, 2, mode=mode).to(dtype=dtypes[1], device=device)\n es.weight.data.copy_(\n torch.arange(1, 11, device=device, dtype=dtypes[1]).view_as(es.weight))\n input = torch.tensor([], device=device, dtype=dtypes[0])\n offsets = torch.tensor([0, 0, 0, 0, 0], device=device, dtype=dtypes[0])\n per_sample_weights = torch.randn_like(input, dtype=dtypes[1]) \\\n .requires_grad_(trainable_scale)\n ref_per_sample_weights = \\\n per_sample_weights.detach().requires_grad_(trainable_scale)\n reference_weights = es.weight.detach().requires_grad_()\n\n expected = self._embedding_bag_reference_impl(\n input, reference_weights, offsets, mode, ref_per_sample_weights)\n result = es(input, offsets, per_sample_weights)\n self.assertEqual(result, expected, atol=dtype2prec_DONTUSE[dtypes[1]], rtol=0)\n\n grad = torch.randn_like(expected)\n result.backward(grad)\n # the reference impl doesn't have grad fn for empty input; but the grad should\n # simply be a zero tensor\n ref_weights_grad = torch.zeros_like(es.weight)\n self.assertEqual(es.weight.grad, ref_weights_grad,\n atol=dtype2prec_DONTUSE[dtypes[1]], rtol=0)\n if trainable_scale:\n ref_per_sample_weights_grad = torch.empty_like(per_sample_weights)\n self.assertEqual(per_sample_weights.grad, ref_per_sample_weights_grad,\n atol=dtype2prec_DONTUSE[dtypes[1]], rtol=0)\n\n modes = ('sum',)\n trainable_scale = (True, False)\n for mode, trainable in itertools.product(modes, trainable_scale):\n test_per_sample_weights(mode, trainable)\n\n @dtypesIfCUDA(*itertools.product((torch.int, torch.long), (torch.float, torch.double, torch.half)))\n @dtypes(*itertools.product((torch.int, torch.long), (torch.float, torch.double)))\n def test_EmbeddingBag_per_sample_weights_and_offsets(self, device, dtypes):\n def test_per_sample_weights(mode, trainable_scale):\n es = nn.EmbeddingBag(5, 2, mode=mode).to(dtype=dtypes[1], device=device)\n es.weight.data.copy_(\n torch.arange(1, 11, device=device, dtype=dtypes[1]).view_as(es.weight))\n input = torch.tensor([3, 1, 1, 1, 4, 0], device=device, dtype=dtypes[0])\n offsets = torch.tensor([0, 0, 3, 3, 6], device=device, dtype=dtypes[0])\n per_sample_weights = torch.randn_like(input, dtype=dtypes[1]) \\\n .requires_grad_(trainable_scale)\n ref_per_sample_weights = \\\n per_sample_weights.detach().requires_grad_(trainable_scale)\n reference_weights = es.weight.detach().requires_grad_()\n\n expected = self._embedding_bag_reference_impl(\n input, reference_weights, offsets, mode, ref_per_sample_weights)\n result = es(input, offsets, per_sample_weights)\n self.assertEqual(result, expected, atol=dtype2prec_DONTUSE[dtypes[1]], rtol=0)\n\n grad = torch.randn_like(expected)\n result.backward(grad)\n expected.backward(grad)\n self.assertEqual(es.weight.grad, reference_weights.grad,\n atol=dtype2prec_DONTUSE[dtypes[1]], rtol=0)\n if trainable_scale:\n self.assertEqual(per_sample_weights.grad, ref_per_sample_weights.grad,\n atol=dtype2prec_DONTUSE[dtypes[1]], rtol=0)\n\n modes = ('sum',)\n trainable_scale = (True, False)\n for mode, trainable in itertools.product(modes, trainable_scale):\n test_per_sample_weights(mode, trainable)\n\n @dtypesIfCUDA(*itertools.product((torch.int, torch.long), (torch.float, torch.double, torch.half)))\n @dtypes(*itertools.product((torch.int, torch.long), (torch.float, torch.double)))\n def test_EmbeddingBag_per_sample_weights_and_new_offsets(self, device, dtypes):\n def test_per_sample_weights_new_offsets(mode, trainable_scale, include_last_offset, has_weight=True):\n es = nn.EmbeddingBag(5, 2, mode=mode, include_last_offset=include_last_offset).to(dtype=dtypes[1], device=device)\n es.weight.data.copy_(\n torch.arange(1, 11, device=device, dtype=dtypes[1]).view_as(es.weight))\n input = torch.tensor([3, 1, 1, 1, 4, 0], device=device, dtype=dtypes[0])\n offsets = torch.tensor([0, 0, 3, 3, 6], device=device, dtype=dtypes[0])\n\n if include_last_offset:\n offsets = torch.cat((offsets, torch.tensor([input.size(0)], device=device, dtype=dtypes[0])), 0)\n\n if has_weight:\n per_sample_weights = torch.randn_like(input, device=device, dtype=dtypes[1]) \\\n .requires_grad_(trainable_scale)\n ref_per_sample_weights = \\\n per_sample_weights.detach().requires_grad_(trainable_scale)\n else:\n per_sample_weights = None\n ref_per_sample_weights = None\n\n reference_weights = es.weight.detach().requires_grad_()\n\n expected = self._embedding_bag_reference_impl(\n input, reference_weights, offsets, mode, ref_per_sample_weights, include_last_offset)\n result = es(input, offsets, per_sample_weights)\n self.assertEqual(result, expected, atol=dtype2prec_DONTUSE[dtypes[1]], rtol=0)\n\n grad = torch.randn_like(expected)\n result.backward(grad)\n expected.backward(grad)\n self.assertEqual(es.weight.grad, reference_weights.grad,\n atol=dtype2prec_DONTUSE[dtypes[1]], rtol=0)\n if has_weight and trainable_scale:\n self.assertEqual(per_sample_weights.grad, ref_per_sample_weights.grad,\n atol=dtype2prec_DONTUSE[dtypes[1]], rtol=0)\n\n trainable_scale = (True, False)\n include_last_offset = (True, False)\n modes = (('sum', False), ('sum', True), ('max', False), ('mean', False))\n for (mode, has_weight), trainable, include_last_offset in itertools.product(\n modes, trainable_scale, include_last_offset\n ):\n test_per_sample_weights_new_offsets(\n mode, trainable, include_last_offset, has_weight\n )\n\n def _test_EmbeddingBag_vs_Embedding(self, N, D, B, L, max_norm=None,\n mode='mean',\n device='cpu',\n wdtype=torch.float,\n dtype=torch.long,\n test_per_sample_weights=False,\n trainable_per_sample_weights=False,\n sparse=False,\n test_backward=True,\n backward_prec=None):\n es = nn.EmbeddingBag(N, D, mode=mode, sparse=sparse, max_norm=max_norm).to(device, wdtype)\n e = nn.Embedding(N, D, max_norm=max_norm).to(device, wdtype)\n e.weight.data.copy_(es.weight)\n input = torch.randint(N, (B, L), device=device, dtype=dtype)\n offsets = torch.arange(0, B, device=device, dtype=dtype).mul_(L)\n grad_output = torch.rand(B, D, device=device, dtype=wdtype)\n\n if test_per_sample_weights:\n # To prevent large gradients, weights should sum to 1 for each bag\n per_sample_weights = \\\n torch.randn(B, L, device=device, dtype=wdtype).softmax(dim=-1)\n per_sample_weights_reference = \\\n per_sample_weights.clone().requires_grad_(trainable_per_sample_weights)\n per_sample_weights.requires_grad_(trainable_per_sample_weights)\n output = es(input.view(-1), offsets, per_sample_weights.view(-1))\n else:\n output = es(input.view(-1), offsets)\n per_sample_weights = None\n per_sample_weights_reference = None\n\n if mode == 'sum':\n if test_per_sample_weights:\n ref_output = (e(input) * per_sample_weights_reference.unsqueeze(-1)).sum(1)\n else:\n ref_output = e(input).sum(1)\n elif mode == 'mean':\n assert not test_per_sample_weights\n ref_output = e(input).mean(1)\n elif mode == 'max':\n assert not test_per_sample_weights\n ref_output = e(input).max(1)[0]\n\n self.assertEqual(output, ref_output, atol=dtype2prec_DONTUSE[wdtype], rtol=0)\n\n if not test_backward:\n return\n\n output.backward(grad_output)\n ref_output.backward(grad_output)\n es_weight_grad = es.weight.grad.data\n if sparse:\n es_weight_grad = es.weight.grad.data.to_dense()\n\n # We have more floating point error here because we are dealing with larger numbers\n if backward_prec is None:\n needed_prec = dtype2prec_DONTUSE[wdtype] * 3\n else:\n needed_prec = backward_prec\n\n self.assertEqual(es_weight_grad, e.weight.grad, atol=needed_prec, rtol=0)\n\n if test_per_sample_weights and trainable_per_sample_weights:\n self.assertEqual(per_sample_weights.grad, per_sample_weights_reference.grad,\n atol=dtype2prec_DONTUSE[wdtype], rtol=0)\n\n @skipCUDAIf(True, \"Temporarily disabled. See t54369166\")\n @dtypesIfCUDA(*itertools.product((torch.int, torch.long), (torch.half, torch.float, torch.double)))\n @dtypes(*itertools.product((torch.int, torch.long), (torch.float, torch.double)))\n def test_EmbeddingBag_per_sample_weights_and_no_offsets(self, device, dtypes):\n def run_tests(mode, sparse, trainable_per_sample_weights):\n kwargs = dict(test_per_sample_weights=True, device=device,\n mode=mode, wdtype=dtypes[1], dtype=dtypes[0], sparse=sparse,\n trainable_per_sample_weights=trainable_per_sample_weights)\n\n # Simple case\n self._test_EmbeddingBag_vs_Embedding(2, 3, 5, 7, **kwargs)\n\n # B * L > 1000\n self._test_EmbeddingBag_vs_Embedding(2, 5, 53, 23, **kwargs)\n\n # Large num_embedding\n self._test_EmbeddingBag_vs_Embedding(101, 5, 3, 7, **kwargs)\n\n # Large embedding_dim\n self._test_EmbeddingBag_vs_Embedding(2, 101, 3, 7, **kwargs)\n\n modes = ('sum',)\n sparsity = (True, False)\n trainable_scale = (True, False)\n for mode, sparse, trainable_per_sample_weights in \\\n itertools.product(modes, sparsity, trainable_scale):\n run_tests(mode, sparse, trainable_per_sample_weights)\n\n # Test CUDA Dense on half precision\n if device == 'cuda':\n modes = ('sum',)\n sparsity = (False,)\n trainable_scale = (True, False)\n for mode, sparse, trainable_per_sample_weights in \\\n itertools.product(modes, sparsity, trainable_scale):\n run_tests(mode, sparse, trainable_per_sample_weights)\n\n def _test_EmbeddingBag(self, device, mode, sparse, wdtype=torch.double, dtype=torch.long, test_backward=True):\n # check a known test example\n es = nn.EmbeddingBag(5, 2, mode=mode, sparse=sparse).to(device, wdtype)\n es.weight.data.copy_(torch.arange(1, 11, device=device, dtype=wdtype).view_as(es.weight))\n input = torch.tensor([3, 1, 1, 1, 4, 0], device=device, dtype=dtype)\n offsets = torch.tensor([0, 0, 3, 3, 6], device=device, dtype=dtype)\n\n grad_output = torch.tensor(\n [1, 2,\n 3, 4], device=device, dtype=wdtype).view(2, 2)\n grad_output_with_empty = torch.tensor(\n [99, 99,\n 1, 2,\n 99, 99,\n 3, 4,\n 99, 99], device=device, dtype=wdtype).view(5, 2)\n\n if mode == \"sum\" or mode == \"mean\":\n denominator = 1 if mode == \"sum\" else 3\n expected_output = torch.tensor(\n [[13, 16],\n [13, 16]], device=device, dtype=wdtype) / denominator\n\n expected_output_with_empty = torch.tensor(\n [[0, 0],\n [13, 16],\n [0, 0],\n [13, 16],\n [0, 0]], device=device, dtype=wdtype) / denominator\n\n expected_grad_weight = torch.tensor(\n [[3, 4],\n [5, 8],\n [0, 0],\n [1, 2],\n [3, 4]], device=device, dtype=wdtype) / denominator\n elif mode == \"max\":\n expected_output = torch.tensor(\n [[7, 8],\n [9, 10]], device=device, dtype=wdtype)\n\n expected_output_with_empty = torch.tensor(\n [[0, 0],\n [7, 8],\n [0, 0],\n [9, 10],\n [0, 0]], device=device, dtype=wdtype)\n\n expected_grad_weight = torch.tensor(\n [[0, 0],\n [0, 0],\n [0, 0],\n [1, 2],\n [3, 4]], device=device, dtype=wdtype)\n output = es(input, offsets)\n output.backward(grad_output_with_empty)\n\n es_weight_grad = es.weight.grad.data\n if sparse:\n es_weight_grad = es.weight.grad.to_dense()\n self.assertEqual(output, expected_output_with_empty)\n self.assertEqual(es_weight_grad, expected_grad_weight, atol=dtype2prec_DONTUSE[wdtype], rtol=0)\n\n # check same example except as 2D (2 x 3)\n input = input.view(2, -1)\n es.zero_grad()\n output = es(input)\n output.backward(grad_output)\n\n es_weight_grad = es.weight.grad\n if sparse:\n es_weight_grad = es.weight.grad.to_dense()\n self.assertEqual(output, expected_output)\n self.assertEqual(es_weight_grad, expected_grad_weight, atol=dtype2prec_DONTUSE[wdtype], rtol=0)\n\n # test all empty bags\n es.zero_grad()\n inputs = torch.tensor([], dtype=dtype, device=device)\n offsets = torch.tensor([0, 0, 0, 0], dtype=dtype, device=device)\n es(inputs, offsets).sum().backward()\n dense_grad = es.weight.grad\n if dense_grad.is_sparse:\n dense_grad = dense_grad.to_dense()\n self.assertEqual(dense_grad, torch.zeros_like(es.weight))\n\n # now compare EmbeddingBag vs Embedding + Sum/Mean, for constant bag length\n N, D, B, L = random.randint(1, 100), random.randint(1, 100), random.randint(1, 50), random.randint(1, 50)\n kwargs = dict(mode=mode, sparse=sparse, device=device, wdtype=wdtype, dtype=dtype, test_backward=test_backward)\n self._test_EmbeddingBag_vs_Embedding(N, D, B, L, **kwargs)\n for max_norm in (None, 3):\n for p in itertools.product([1, 2], repeat=4):\n self._test_EmbeddingBag_vs_Embedding(*p, max_norm=max_norm, **kwargs)\n\n # check that giving illegal input combos raises error\n es = nn.EmbeddingBag(10, 20, mode=mode, sparse=sparse)\n input = torch.ones(3, 4, dtype=dtype)\n offset = torch.arange(0, 3, dtype=dtype)\n self.assertRaises(ValueError, lambda: es(input, offset))\n self.assertRaises(ValueError, lambda: es(input.view(-1)))\n offset[0] = 1\n if self.device_type == \"cpu\":\n self.assertRaises(RuntimeError, lambda: es(input.view(-1), offset))\n offset[0] = 0\n offset[-1] = 100\n self.assertRaises(RuntimeError, lambda: es(input.view(-1), offset))\n\n @dtypesIfCUDA(*itertools.product((torch.int, torch.long), (torch.float, torch.double, torch.half)))\n @dtypes(*itertools.product((torch.int, torch.long), (torch.float, torch.double)))\n def test_embedding_bag_device(self, device, dtypes):\n self._test_EmbeddingBag(device, 'sum', False, wdtype=dtypes[1], dtype=dtypes[0])\n self._test_EmbeddingBag(device, 'mean', False, wdtype=dtypes[1], dtype=dtypes[0])\n self._test_EmbeddingBag(device, 'max', False, wdtype=dtypes[1], dtype=dtypes[0])\n\n test_backward = False\n if self.device_type == 'cuda':\n # see 'todo' in test_embedding_bag.\n test_backward = dtypes[1] is not torch.float16\n elif self.device_type == 'cpu':\n # TODO: figure out why precision on sparse embeddings isn't the\n # same as for dense.\n test_backward = dtypes[1] is not torch.float\n\n self._test_EmbeddingBag(device, 'sum', True, wdtype=dtypes[1], dtype=dtypes[0], test_backward=test_backward)\n self._test_EmbeddingBag(device, 'mean', True, wdtype=dtypes[1], dtype=dtypes[0], test_backward=test_backward)\n\n @dtypesIfCUDA(*itertools.product((torch.int, torch.long), (torch.float, torch.double, torch.half)))\n @dtypes(*itertools.product((torch.int, torch.long), (torch.float, torch.double)))\n def test_embedding_bag_non_contiguous_weight(self, device, dtypes):\n weight_tensor = torch.randn(3, 4, dtype=dtypes[1], device=device)\n\n weight_tensor_non_contig = weight_tensor[:, :3] # This is non-contiguous strided.\n weight_tensor_contig = weight_tensor_non_contig.clone().contiguous() # Contig-strided.\n\n index = torch.tensor([0, 1, 2], dtype=dtypes[0], device=device)\n offsets = torch.tensor([0, 2], dtype=dtypes[0], device=device)\n for mode in ['sum', 'mean', 'max']:\n output_non_contig = F.embedding_bag(\n input=index,\n weight=weight_tensor_non_contig,\n offsets=offsets,\n mode=mode,\n )\n output_contig = F.embedding_bag(\n input=index,\n weight=weight_tensor_contig,\n offsets=offsets,\n mode=mode,\n )\n self.assertEqual(output_non_contig, output_contig)\n\n\n @onlyCUDA\n @dtypes(torch.int, torch.long)\n def test_embedding_bag_bfloat16(self, device, dtype):\n self._test_EmbeddingBag(device, 'sum', True, wdtype=torch.bfloat16, dtype=dtype, test_backward=True)\n self._test_EmbeddingBag(device, 'mean', True, wdtype=torch.bfloat16, dtype=dtype, test_backward=True)\n\n\n @onlyCUDA\n @dtypes(torch.half, torch.float, torch.double)\n def test_multihead_attention_dtype(self, device, dtype):\n embed_dim = 128\n num_heads = 8\n sl = 10\n bs = 8\n model = nn.MultiheadAttention(embed_dim, num_heads).cuda().to(dtype)\n q = torch.randn(sl, bs, embed_dim, device=device, dtype=dtype)\n k = torch.randn(sl, bs, embed_dim, device=device, dtype=dtype)\n v = torch.randn(sl, bs, embed_dim, device=device, dtype=dtype)\n out = model(q, k, v)\n self.assertEqual(q.size(), out[0].size())\n self.assertEqual(dtype, out[0].dtype)\n\n @dtypesIfCUDA(*get_all_fp_dtypes(include_bfloat16=AMPERE_OR_ROCM))\n @dtypes(torch.float)\n def test_Conv2d_naive_groups(self, device, dtype):\n # Check that grouped convolutions matches two half convolutions\n m = nn.Conv2d(4, 4, kernel_size=3, groups=2).to(device, dtype)\n i = torch.randn(2, 4, 6, 6, device=device, dtype=dtype, requires_grad=True)\n output = m(i)\n grad_output = torch.randn(2, 4, 4, 4, device=device, dtype=dtype)\n output.backward(grad_output)\n\n m1 = nn.Conv2d(2, 2, kernel_size=3).to(device, dtype)\n m1.weight.data.copy_(m.weight.data[:2])\n m1.bias.data.copy_(m.bias.data[:2])\n i1 = i.data[:, :2].contiguous().requires_grad_(True)\n output1 = m1(i1)\n output1.backward(grad_output[:, :2].contiguous())\n\n m2 = nn.Conv2d(2, 2, kernel_size=3).to(device, dtype)\n m2.weight.data.copy_(m.weight.data[2:])\n m2.bias.data.copy_(m.bias.data[2:])\n i2 = i.data[:, 2:].contiguous().requires_grad_(True)\n output2 = m2(i2)\n output2.backward(grad_output[:, 2:].contiguous())\n\n self.assertEqual(output, torch.cat([output1, output2], 1))\n self.assertEqual(i.grad.data,\n torch.cat([i1.grad.data, i2.grad.data], 1),\n atol=dtype2prec_DONTUSE[dtype], rtol=0)\n self.assertEqual(m.bias.grad.data,\n torch.cat([m1.bias.grad.data, m2.bias.grad.data], 0),\n atol=dtype2prec_DONTUSE[dtype], rtol=0)\n self.assertEqual(m.weight.grad.data,\n torch.cat([m1.weight.grad.data, m2.weight.grad.data], 0),\n atol=dtype2prec_DONTUSE[dtype], rtol=0)\n\n def _test_batchnorm_grad(self, device, dtype=torch.double):\n bs, n_feat, size_feat = 4, 5, 6\n input = torch.arange(bs * n_feat * size_feat, device=device,\n requires_grad=True, dtype=dtype).view(bs, n_feat, size_feat)\n weight = torch.arange(1, n_feat + 1, device=device, requires_grad=True, dtype=dtype)\n bias = torch.arange(n_feat, device=device, requires_grad=True, dtype=dtype)\n running_mean = 1 - torch.arange(n_feat, device=device, dtype=dtype)\n running_var = 2 * torch.arange(n_feat, device=device, dtype=dtype)\n for training in [False, True]:\n _assertGradAndGradgradChecks(self, F.batch_norm, (input, running_mean, running_var, weight, bias,\n training, 0.1, 0.0001))\n\n def test_batchnorm_grad(self, device):\n self._test_batchnorm_grad(device)\n\n if self.device_type == 'cuda' and self.has_cudnn():\n with torch.backends.cudnn.flags(enabled=False):\n self._test_batchnorm_grad(device)\n\n\n def test_hardsigmoid_grad(self, device):\n inputs = (torch.randn(4, 16, 16, device=device) - 0.5) * 10\n inputs.requires_grad = True\n self.assertTrue(gradcheck(F.hardsigmoid, (inputs,)))\n\n # currently fails on XLA\n @onlyOnCPUAndCUDA\n def test_hardswish_grad(self, device):\n inputs = (torch.randn(4, 16, 16, device=device) - 0.5) * 10\n inputs.requires_grad = True\n self.assertTrue(gradcheck(F.hardswish, (inputs,)))\n\n\n def _test_batchnorm_eval(self, device, dtype=torch.float):\n module = nn.BatchNorm1d(3).to(device, dtype)\n module.eval()\n\n data = torch.rand(4, 3, device=device, dtype=dtype, requires_grad=True)\n grad = torch.rand(4, 3, device=device, dtype=dtype)\n\n # 1st pass\n res1 = module(data)\n res1.backward(grad)\n grad1 = data.grad.clone()\n\n # 2nd pass\n if data.grad is not None:\n data.grad.data.zero_()\n\n res2 = module(data)\n res2.backward(grad)\n grad2 = data.grad.clone()\n self.assertEqual(res1, res2)\n self.assertEqual(grad1, grad2)\n\n # track_running_stats=False\n module = nn.BatchNorm1d(3, track_running_stats=False).to(device, dtype)\n\n data = torch.rand(4, 3, device=device, dtype=dtype, requires_grad=True)\n grad = torch.rand(4, 3, device=device, dtype=dtype)\n\n # 1st pass\n res1 = module(data)\n res1.backward(grad)\n grad1 = data.grad.clone()\n\n # set eval\n module.eval()\n\n # 2nd pass\n if data.grad is not None:\n data.grad.data.zero_()\n\n res2 = module(data)\n res2.backward(grad)\n grad2 = data.grad.clone()\n self.assertEqual(res1, res2)\n self.assertEqual(grad1, grad2)\n\n def test_batchnorm_eval(self, device):\n self._test_batchnorm_eval(device)\n\n if self.device_type == 'cuda' and self.has_cudnn():\n with torch.backends.cudnn.flags(enabled=False):\n self._test_batchnorm_eval(device)\n\n @onlyCUDA\n def test_batchnorm_eval_bfloat16(self, device):\n self._test_batchnorm_eval(device, torch.bfloat16)\n\n def _test_batchnorm_simple_average(self, device, dtype):\n module = nn.BatchNorm1d(3, momentum=None).to(dtype=dtype, device=device)\n zeros = torch.zeros(3, dtype=dtype, device=device)\n ones = torch.ones(3, dtype=dtype, device=device)\n self.assertEqual(module.running_mean, zeros)\n self.assertEqual(module.running_var, ones)\n\n data1 = torch.rand(4, 3, dtype=dtype, device=device)\n data2 = torch.rand(4, 3, dtype=dtype, device=device)\n\n # 1st pass\n res1 = module(data1)\n running_mean1 = module.running_mean.clone()\n running_var1 = module.running_var.clone()\n self.assertNotEqual(running_mean1, zeros)\n self.assertNotEqual(running_var1, ones)\n\n # reset stats\n module.reset_running_stats()\n self.assertEqual(module.running_mean, zeros)\n self.assertEqual(module.running_var, ones)\n\n # 2nd pass\n res2 = module(data2)\n running_mean2 = module.running_mean.clone()\n running_var2 = module.running_var.clone()\n self.assertNotEqual(running_mean2, zeros)\n self.assertNotEqual(running_var2, ones)\n\n # reset stats\n module.reset_running_stats()\n self.assertEqual(module.running_mean, zeros)\n self.assertEqual(module.running_var, ones)\n\n # 3rd (combined) pass\n res3 = module(data1)\n res4 = module(data2)\n self.assertEqual(res3, res1)\n self.assertEqual(res4, res2)\n self.assertEqual(module.running_mean, (running_mean1 + running_mean2) / 2)\n self.assertEqual(module.running_var, (running_var1 + running_var2) / 2)\n\n @dtypes(torch.float)\n def test_batchnorm_simple_average(self, device, dtype):\n self._test_batchnorm_simple_average(device, dtype)\n\n if self.device_type == 'cuda' and self.has_cudnn():\n with torch.backends.cudnn.flags(enabled=False):\n self._test_batchnorm_simple_average(device, dtype)\n\n def _test_maxpool_indices(self, num_dim, adaptive=False, device=\"cpu\", dtype=torch.float):\n def expected_indices(dim):\n if dim == 1:\n return torch.tensor([1, 3], dtype=torch.double).repeat(2, 2, 1)\n if dim == 2:\n return torch.tensor([[5, 7], [13, 15]], dtype=torch.double).repeat(2, 2, 1, 1)\n\n def expected_grad(dim):\n if dim == 1:\n return torch.tensor([0, 1, 0, 1], dtype=torch.double).repeat(2, 2, 1)\n grad = expected_grad(dim - 1)\n zero = torch.zeros(grad.size())\n return torch.stack((zero, grad, zero, grad), 2)\n\n def expected_output(dim):\n if dim == 1:\n return torch.arange(2, 17, 2).view(2, 2, 2)\n if dim == 2:\n col = torch.arange(6, 63, 8)\n return torch.stack([col, col + 2], 1).view(2, 2, 2, 2)\n\n if adaptive:\n cls_name = 'AdaptiveMaxPool{}d'.format(num_dim)\n else:\n cls_name = 'MaxPool{}d'.format(num_dim)\n module_cls = getattr(nn, cls_name)\n module = module_cls(2, return_indices=True).to(device, dtype=dtype)\n numel = 4 ** (num_dim + 1)\n input = torch.arange(1, numel + 1).view(2, 2, *repeat(4, num_dim)).to(device, dtype=dtype)\n input_var = input.clone().detach().requires_grad_()\n\n # Check forward\n output, indices = module(input_var)\n if num_dim != 3:\n expected_indices = expected_indices(num_dim)\n expected_output = expected_output(num_dim)\n self.assertEqual(indices.dim(), input.dim())\n # TODO(#38095): Replace assertEqualIgnoreType. See issue #38095\n self.assertEqualIgnoreType(indices.data.squeeze(), expected_indices)\n # TODO(#38095): Replace assertEqualIgnoreType. See issue #38095\n self.assertEqualIgnoreType(output.data.squeeze(), expected_output)\n self.assertTrue(output.requires_grad)\n self.assertFalse(indices.requires_grad)\n\n # Make sure backward works\n grad_output = torch.ones(output.size(), device=device, dtype=dtype)\n output.backward(grad_output, retain_graph=True)\n expected_grad = expected_grad(num_dim)\n # TODO(#38095): Replace assertEqualIgnoreType. See issue #38095\n self.assertEqualIgnoreType(input_var.grad.data, expected_grad.view_as(input))\n\n # Make sure backward after changing indices will result in an error\n indices.add_(1)\n self.assertRaises(RuntimeError, lambda: output.backward(grad_output))\n\n # Make sure -Infinity is handled correctly\n t = torch.tensor([[[float(\"-inf\")]]])\n m = nn.MaxPool1d(kernel_size=1, return_indices=True)\n output, indices = m(t)\n self.assertEqual(output[0, 0, 0], float(\"-inf\"))\n self.assertEqual(indices[0, 0, 0], 0)\n\n t = torch.tensor([[[float(\"-inf\")]]])\n m = nn.MaxPool2d(kernel_size=1, return_indices=True)\n output, indices = m(t)\n self.assertEqual(output[0, 0, 0], float(\"-inf\"))\n self.assertEqual(indices[0, 0, 0], 0)\n\n t = torch.tensor([[[[float(\"-inf\")]]]])\n m = nn.MaxPool3d(kernel_size=1, return_indices=True)\n output, indices = m(t)\n self.assertEqual(output[0, 0, 0, 0], float(\"-inf\"))\n self.assertEqual(indices[0, 0, 0, 0], 0)\n\n @dtypesIfCUDA(*get_all_fp_dtypes())\n @dtypes(torch.float)\n def test_MaxPool1d_indices(self, device, dtype):\n self._test_maxpool_indices(1, device=device, dtype=dtype)\n\n @dtypesIfCUDA(*get_all_fp_dtypes())\n @dtypes(torch.float)\n def test_MaxPool2d_indices(self, device, dtype):\n self._test_maxpool_indices(2, device=device, dtype=dtype)\n\n @dtypesIfCUDA(*get_all_fp_dtypes())\n @dtypes(torch.float)\n def test_MaxPool3d_indices(self, device, dtype):\n self._test_maxpool_indices(3, device=device, dtype=dtype)\n\n @dtypesIfCUDA(*get_all_fp_dtypes())\n @dtypes(torch.float)\n def test_AdaptiveMaxPool1d_indices(self, device, dtype):\n self._test_maxpool_indices(1, adaptive=True, device=device, dtype=dtype)\n\n @dtypesIfCUDA(*get_all_fp_dtypes())\n @dtypes(torch.float)\n def test_AdaptiveMaxPool2d_indices(self, device, dtype):\n self._test_maxpool_indices(2, adaptive=True, device=device, dtype=dtype)\n\n @dtypesIfCUDA(*get_all_fp_dtypes())\n @dtypes(torch.float)\n def test_AdaptiveMaxPool3d_indices(self, device, dtype):\n self._test_maxpool_indices(3, adaptive=True, device=device, dtype=dtype)\n\n @dtypesIfCUDA(torch.half, torch.float, torch.double)\n @dtypes(torch.float)\n @onlyOnCPUAndCUDA # TODO: Fails on XLA\n def test_max_pool_nan_inf(self, device, dtype):\n for adaptive in ['', 'adaptive_']:\n for num_dim in [1, 2, 3]:\n fn_name = '{}max_pool{}d'.format(adaptive, num_dim)\n fn = getattr(F, fn_name)\n\n x = torch.full([1, 1] + num_dim * [3], nan, device=device, dtype=dtype, requires_grad=True)\n res = fn(x, 1 if adaptive else 3)\n res.backward(torch.randn_like(res))\n self.assertTrue(math.isnan(res.item()))\n x.requires_grad_(False)\n res = fn(x, 1 if adaptive else 3)\n self.assertTrue(math.isnan(res.item()))\n\n x2 = torch.full([1, 1] + num_dim * [3], -inf, device=device, dtype=dtype, requires_grad=True)\n res2 = fn(x2, 1 if adaptive else 3)\n res2.backward(torch.randn_like(res2))\n self.assertTrue(math.isinf(res2.item()))\n x2.requires_grad_(False)\n res2 = fn(x2, 1 if adaptive else 3)\n self.assertTrue(math.isinf(res2.item()))\n\n @onlyOnCPUAndCUDA\n @dtypes(torch.float, torch.double)\n def test_grid_sample_nan_inf(self, device, dtype):\n input = torch.zeros([1, 1, 3, 3], device=device, dtype=dtype)\n grid = torch.tensor([[[[nan, 0], [0, inf]]]], device=device, dtype=dtype)\n for padding_mode in ('reflection', 'border', 'zeros'):\n sample = torch.nn.functional.grid_sample(input=input, grid=grid, mode='nearest',\n padding_mode=padding_mode, align_corners=False)\n self.assertEqual(sample, torch.zeros([1, 1, 1, 2], device=device, dtype=dtype))\n\n @onlyOnCPUAndCUDA\n def test_fractional_max_pool2d(self, device):\n x = torch.randn(1, 2, 7, 7, requires_grad=True, device=device)\n samples = x.new(1, 2, 2).uniform_()\n\n def func(x):\n return F.fractional_max_pool2d(\n x, (2, 2), output_size=(3, 3), _random_samples=samples)\n\n self.assertEqual(func(x).shape, (1, 2, 3, 3))\n gradcheck(func, [x])\n gradgradcheck(func, [x])\n\n x = torch.randn(2, 7, 7, requires_grad=True, device=device)\n self.assertEqual(func(x).shape, (2, 3, 3))\n if self.device_type != 'cuda':\n # Reference: https://github.com/pytorch/pytorch/issues/52427\n # Raises -> RuntimeError: TensorAccessor expected 4 dims but tensor has 3\n # on CUDA in gradcheck\n gradcheck(func, [x])\n gradgradcheck(func, [x])\n\n for kernel_size in [(), (1,)]:\n with self.assertRaisesRegex(RuntimeError, \"kernel_size must either\"):\n # Incorrect kernel_size\n F.fractional_max_pool2d(x, kernel_size=kernel_size, output_size=(3, 3), _random_samples=samples)\n\n err_large_msg = \"too large relative to input \"\n err_out_size_msg = \"output_size must either\"\n for output_size, msg in [((9, 3), err_large_msg + \"height\"),\n ((3, 9), err_large_msg + \"width\"),\n ((3,), err_out_size_msg),\n ((), err_out_size_msg)]:\n with self.assertRaisesRegex(RuntimeError, msg):\n # Incorrect output_size\n F.fractional_max_pool2d(x, (2, 2), output_size=output_size, _random_samples=samples)\n\n @onlyOnCPUAndCUDA\n def test_fractional_max_pool3d(self, device):\n x = torch.randn(1, 2, 7, 7, 7, requires_grad=True, device=device)\n samples = x.new(1, 2, 3).uniform_()\n\n def func(x):\n return F.fractional_max_pool3d(\n x, (2, 2, 2), output_size=(3, 3, 3), _random_samples=samples)\n\n self.assertEqual(func(x).shape, (1, 2, 3, 3, 3))\n gradcheck(func, [x])\n gradgradcheck(func, [x])\n\n x = torch.randn(2, 7, 7, 7, requires_grad=True, device=device)\n self.assertEqual(func(x).shape, (2, 3, 3, 3))\n gradcheck(func, [x])\n gradgradcheck(func, [x])\n\n for kernel_size in [(), (1,), (1, 1)]:\n with self.assertRaisesRegex(RuntimeError, \"kernel_size must either\"):\n # Incorrect kernel_size\n F.fractional_max_pool3d(x, kernel_size=kernel_size, output_size=(3, 3, 3), _random_samples=samples)\n\n err_large_msg = \"too large relative to input \"\n err_out_size_msg = \"output_size must either\"\n for output_size, msg in [((9, 3, 3), err_large_msg + \"time\"),\n ((3, 9, 3), err_large_msg + \"height\"),\n ((3, 3, 9), err_large_msg + \"width\"),\n ((3, 3), err_out_size_msg),\n ((3,), err_out_size_msg),\n ((), err_out_size_msg)]:\n with self.assertRaisesRegex(RuntimeError, msg):\n # Incorrect output_size\n F.fractional_max_pool3d(x, (2, 2, 2), output_size=output_size, _random_samples=samples)\n\n @dtypesIfCUDA(torch.half, torch.float, torch.double)\n @dtypes(torch.float)\n @onlyOnCPUAndCUDA # TODO: Fails on XLA\n def test_fractional_max_pool_nan_inf(self, device, dtype):\n for num_dim in [2, 3]:\n fn_name = 'FractionalMaxPool{}d'.format(num_dim)\n fn = getattr(nn, fn_name)(kernel_size=2, output_size=1)\n x = torch.full([1, 1] + num_dim * [3], nan, device=device, dtype=dtype, requires_grad=True)\n res = fn(x)\n res.backward(torch.randn_like(res))\n self.assertTrue(math.isnan(res.item()))\n\n x2 = torch.full([1, 1] + num_dim * [3], -inf, device=device, dtype=dtype, requires_grad=True)\n res2 = fn(x2)\n res2.backward(torch.randn_like(res2))\n self.assertTrue(math.isinf(res2.item()))\n\n @onlyOnCPUAndCUDA # TODO: RuntimeError message different on XLA\n def test_pooling_zero_stride(self, device):\n for op in ('max', 'avg'):\n for num_dim in [1, 2, 3]:\n fn_name = '{}_pool{}d'.format(op, num_dim)\n fn = getattr(F, fn_name)\n x = torch.ones([1, 2] + num_dim * [4], device=device, dtype=torch.float)\n self.assertRaisesRegex(RuntimeError, r\"stride should not be zero|stride must be greater than zero\",\n lambda: fn(x, kernel_size=2, stride=0))\n\n fn_module_name = '{}Pool{}d'.format(op.title(), num_dim)\n fn_module = getattr(nn, fn_module_name)(kernel_size=2, stride=0)\n self.assertRaisesRegex(RuntimeError, r\"stride should not be zero|stride must be greater than zero\",\n lambda: fn_module(x))\n\n @dtypesIfCUDA(*get_all_fp_dtypes())\n @dtypes(torch.float)\n def test_pool_large_size(self, device, dtype):\n for op in ('max', 'avg'):\n for num_dim in [1, 2, 3]:\n fn_name = '{}_pool{}d'.format(op, num_dim)\n fn = getattr(F, fn_name)\n # 16777217 is the smallest integer not expressible in float32\n x = torch.ones([1, 1, 16777217] + (num_dim - 1) * [1],\n device=device, dtype=dtype)\n res = fn(x, 1, stride=1, padding=0)\n # check if the output shape was still computed correctly\n self.assertEqual(x.shape[2], res.shape[2])\n\n @dtypesIfCUDA(*get_all_fp_dtypes())\n @dtypes(torch.float)\n def test_pool_invalid_size(self, device, dtype):\n for op in ('max', 'avg'):\n for num_dim in [1, 2, 3]:\n fn_name = '{}_pool{}d'.format(op, num_dim)\n if op == 'max':\n # New implementation without indices supports empty tensors\n # TODO(Heitor) change once with_indices code is updated\n fn_name += '_with_indices'\n fn = getattr(F, fn_name)\n # use a configuration that gives zero outputs only\n # when doing a correct floor division by the stride\n x = torch.ones([1, 1] + num_dim * [4],\n device=device, dtype=dtype)\n with self.assertRaisesRegex(RuntimeError, r\"too small|smaller than\"):\n try:\n res = fn(x, 3, stride=2, padding=0, dilation=2)\n except TypeError:\n # some implementations do not support dilation\n res = fn(x, 6, stride=2, padding=0)\n\n def test_CTCLoss_empty_target(self, device):\n target_lengths = [0, 0, 0]\n input_lengths = [50, 50, 50]\n targets = torch.randint(1, 15, (0,), dtype=torch.long, device=device)\n log_probs = torch.randn(50, 3, 15, dtype=torch.double, device=device).log_softmax(2)\n loss = torch.nn.functional.ctc_loss(log_probs, targets, input_lengths, target_lengths, reduction='none')\n self.assertTrue((loss >= 0).all().item())\n self.assertEqual(-log_probs.sum(0)[:, 0], loss)\n\n target_lengths = [0, 9, 0]\n input_lengths = [50, 50, 50]\n targets = torch.randint(1, 15, (9,), dtype=torch.long, device=device)\n log_probs = torch.randn(50, 3, 15, dtype=torch.double, device=device).log_softmax(2)\n loss = torch.nn.functional.ctc_loss(log_probs, targets, input_lengths, target_lengths, reduction='none')\n self.assertTrue((loss >= 0).all().item())\n self.assertEqual(-log_probs.sum(0)[[0, 2], 0], loss[[0, 2]])\n\n def test_empty_dropout(self, device):\n x = torch.Tensor([]).to(device)\n out = torch.nn.functional.dropout(x)\n self.assertEqual(out.size(), x.size())\n\n @dtypesIfCUDA(torch.half, torch.float, torch.double)\n @dtypes(torch.float)\n @tf32_on_and_off(0.005)\n def test_variable_sequence(self, device, dtype):\n def pad(var, length):\n if var.size(0) == length:\n return var\n return torch.cat([var, var.new_zeros(length - var.size(0), *var.size()[1:])])\n\n def maybe_index_tuple(maybe_tuple_of_tensors, index):\n if maybe_tuple_of_tensors is None:\n return None\n return tuple(maybe_tuple_of_tensors[j][:, index:index + 1, :].contiguous()\n for j in range(2))\n\n def check_lengths(lengths, enforce_sorted, use_default_hiddens, proj_size):\n input_size = 3\n hidden_size = 4\n num_layers = 2\n bidirectional = True\n\n max_length = max(lengths)\n x_leaf = torch.randn(max_length, len(lengths), input_size, device=device,\n dtype=dtype, requires_grad=True)\n num_directions = 2 if bidirectional else 1\n lstm = nn.LSTM(input_size, hidden_size, bidirectional=bidirectional,\n num_layers=num_layers, proj_size=proj_size).to(device, dtype)\n lstm2 = deepcopy(lstm).to(device, dtype)\n x = x_leaf\n\n hidden0 = None\n if not use_default_hiddens:\n real_hidden_size = hidden_size if proj_size == 0 else proj_size\n hidden0 = (torch.randn(num_directions * num_layers, len(lengths), real_hidden_size,\n device=device, dtype=dtype),\n torch.randn(num_directions * num_layers, len(lengths), hidden_size,\n device=device, dtype=dtype))\n\n # Compute sequences separately\n seq_outs = []\n seq_hiddens = []\n for i, l in enumerate(lengths):\n hidden_i = maybe_index_tuple(hidden0, i)\n out, hid = lstm2(x[:l, i:i + 1], hidden_i)\n out_pad = pad(out, max_length)\n seq_outs.append(out_pad)\n seq_hiddens.append(hid)\n seq_out = torch.cat(seq_outs, 1)\n seq_hidden = tuple(torch.cat(hids, 1) for hids in zip(*seq_hiddens))\n\n # Use packed format\n packed = rnn_utils.pack_padded_sequence(x, lengths, enforce_sorted=enforce_sorted)\n packed_out, packed_hidden = lstm(packed, hidden0)\n unpacked, unpacked_len = rnn_utils.pad_packed_sequence(packed_out)\n\n # Check forward\n prec = dtype2prec_DONTUSE[dtype]\n self.assertEqual(packed_hidden, seq_hidden, atol=prec, rtol=0)\n self.assertEqual(unpacked, seq_out, atol=prec, rtol=0)\n self.assertEqual(unpacked_len, lengths, atol=prec, rtol=0)\n\n # Check backward\n seq_out.sum().backward()\n grad_x = x_leaf.grad.data.clone()\n x_leaf.grad.data.zero_()\n unpacked.sum().backward()\n\n self.assertEqual(x_leaf.grad, grad_x, atol=dtype2prec_DONTUSE[dtype], rtol=0)\n for p1, p2 in zip(lstm.parameters(), lstm2.parameters()):\n prec = dtype2prec_DONTUSE[dtype]\n if dtype == torch.float16:\n prec = 4e-2\n self.assertEqual(p1.grad, p2.grad, atol=prec, rtol=0)\n\n tests = [\n # enforce_sorted, lengths\n [True, [5]],\n [False, [5]],\n [True, [10, 10, 6, 2, 2, 1, 1]],\n [False, [10, 10, 6, 2, 2, 1, 1]],\n [False, [2, 1, 3, 2, 10, 5, 3]],\n ]\n\n for enforce_sorted, seq_lens, in tests:\n for use_default_hiddens in (True, False):\n for proj_size in [0, 2]:\n check_lengths(seq_lens, enforce_sorted, use_default_hiddens, proj_size)\n\n def _test_batchnorm_update_stats(self, device, dtype=torch.float):\n module = nn.BatchNorm1d(3).to(device, dtype)\n\n data = torch.rand(4, 3, device=device, dtype=dtype)\n\n # training pass\n old_running_mean = module.running_mean.clone()\n old_running_var = module.running_var.clone()\n old_num_batches_tracked = module.num_batches_tracked.clone()\n module(data)\n self.assertNotEqual(old_running_mean, module.running_mean)\n self.assertNotEqual(old_running_var, module.running_var)\n self.assertEqual(old_num_batches_tracked + 1, module.num_batches_tracked)\n\n # eval pass\n module.eval()\n old_running_mean = module.running_mean.clone()\n old_running_var = module.running_var.clone()\n old_num_batches_tracked = module.num_batches_tracked.clone()\n module(data)\n self.assertEqual(old_running_mean, module.running_mean)\n self.assertEqual(old_running_var, module.running_var)\n self.assertEqual(old_num_batches_tracked, module.num_batches_tracked)\n\n def test_batchnorm_update_stats(self, device):\n self._test_batchnorm_update_stats(device)\n\n if self.device_type == 'cuda' and self.has_cudnn():\n with torch.backends.cudnn.flags(enabled=False):\n self._test_batchnorm_update_stats(device)\n\n def test_multi_margin_loss_errors(self, device):\n self.assertRaises(RuntimeError,\n lambda: nn.functional.multi_margin_loss(torch.randn(5, device=device),\n torch.zeros(3, device=device)))\n\n def _test_bfloat16_ops(self, op, device, inp_dims=(), prec=1e-2):\n # fp32 compute\n input1 = torch.randn(inp_dims, dtype=torch.float32, device=device, requires_grad=True)\n out1 = op(input1)\n grad_input1 = torch.randn_like(out1, device=device)\n out1.backward(grad_input1)\n\n # bfloat16 compute\n op_bfp16 = op.bfloat16()\n input2 = input1.detach().bfloat16().requires_grad_()\n grad_input2 = grad_input1.bfloat16()\n out2 = op_bfp16(input2)\n out2.backward(grad_input2)\n\n self.assertEqual(out1, out2, atol=prec, rtol=0, exact_dtype=False)\n self.assertEqual(input1.grad.data, input2.grad.data, atol=prec, rtol=0, exact_dtype=False)\n\n @onlyCUDA\n def test_activations_bfloat16(self, device):\n self._test_bfloat16_ops(torch.nn.ReLU(), device, inp_dims=(5), prec=1e-2)\n self._test_bfloat16_ops(torch.nn.Threshold(0.1, 20), device, inp_dims=(5), prec=1e-2)\n self._test_bfloat16_ops(torch.nn.ELU(), device, inp_dims=(5), prec=1e-2)\n self._test_bfloat16_ops(torch.nn.Softplus(), device, inp_dims=(5), prec=1e-2)\n self._test_bfloat16_ops(torch.nn.Hardshrink(), device, inp_dims=(5), prec=1e-2)\n self._test_bfloat16_ops(torch.nn.Softshrink(), device, inp_dims=(5), prec=1e-2)\n self._test_bfloat16_ops(torch.nn.LeakyReLU(), device, inp_dims=(5), prec=1e-2)\n\n @onlyCUDA\n def test_pooling_bfloat16(self, device):\n self._test_bfloat16_ops(torch.nn.AvgPool1d(3, stride=2), device, inp_dims=(8, 4, 16), prec=0.05)\n self._test_bfloat16_ops(torch.nn.AvgPool2d(3, stride=2), device, inp_dims=(8, 4, 16, 16), prec=0.05)\n self._test_bfloat16_ops(torch.nn.AvgPool3d(3, stride=2), device, inp_dims=(8, 4, 16, 16, 16), prec=0.05)\n self._test_bfloat16_ops(torch.nn.AdaptiveAvgPool1d(3), device, inp_dims=(8, 4, 16), prec=0.05)\n self._test_bfloat16_ops(torch.nn.AdaptiveAvgPool2d((3, 5)), device, inp_dims=(8, 4, 16, 16), prec=0.05)\n self._test_bfloat16_ops(torch.nn.AdaptiveAvgPool3d((3, 5, 7)), device, inp_dims=(8, 4, 16, 16, 16), prec=0.05)\n\n @onlyCUDA\n def test_softmax_bfloat16(self, device):\n self._test_bfloat16_ops(torch.nn.Softmax(dim=1), device, inp_dims=(16, 32), prec=1e-2)\n\n @onlyCUDA\n @skipCUDAIfRocm\n @skipCUDAIfCudnnVersionLessThan(7603)\n @dtypes(torch.half, torch.float)\n def test_conv_cudnn_nhwc(self, device, dtype):\n def helper(n, c, h, w, out_channels, kernel_size, groups):\n input = torch.randint(-3, 3, (n, c, h, w), dtype=dtype, device=device)\\\n .to(memory_format=torch.channels_last)\n input.requires_grad_()\n conv = nn.Conv2d(c, out_channels, kernel_size, groups=groups)\\\n .to(device='cuda', dtype=dtype, memory_format=torch.channels_last)\n for p in conv.parameters():\n p.data = torch.randint_like(p, -3, 3)\n\n # use FP64 channels-first conv as reference\n ref_input = input.detach().clone().contiguous().double().requires_grad_()\n ref_conv = nn.Conv2d(c, out_channels, kernel_size, groups=groups)\n # load_state_dict will restore the stride & memory_layout on ref_conv.weight.\n ref_conv.load_state_dict(conv.state_dict())\n ref_conv = ref_conv.to(device='cuda', dtype=torch.double, memory_format=torch.contiguous_format)\n\n out = conv(input)\n ref_out = ref_conv(ref_input)\n\n grad = torch.randint_like(out, -3, 3)\n ref_grad = grad.detach().clone().double().contiguous()\n\n out.backward(grad)\n ref_out.backward(ref_grad)\n\n self.assertTrue(out.is_contiguous(memory_format=torch.channels_last))\n self.assertTrue(input.grad.is_contiguous(memory_format=torch.channels_last))\n self.assertTrue(conv.weight.grad.is_contiguous(memory_format=torch.channels_last))\n\n self.assertTrue(ref_out.is_contiguous())\n self.assertTrue(ref_input.grad.is_contiguous())\n self.assertTrue(ref_conv.weight.grad.is_contiguous())\n\n self.assertEqual(out, ref_out, exact_dtype=False)\n self.assertEqual(conv.weight.grad, ref_conv.weight.grad, exact_dtype=False)\n self.assertEqual(conv.bias.grad, ref_conv.bias.grad, exact_dtype=False)\n self.assertEqual(input.grad, ref_input.grad, exact_dtype=False)\n\n helper(2, 8, 4, 4, out_channels=4, kernel_size=3, groups=1)\n helper(2, 8, 4, 4, out_channels=8, kernel_size=3, groups=8)\n helper(1, 16, 56, 56, out_channels=16, kernel_size=3, groups=1)\n helper(1, 16, 56, 56, out_channels=16, kernel_size=3, groups=16)\n\n @onlyCUDA\n @skipCUDAIfRocm\n @skipCUDAIfCudnnVersionLessThan(8005)\n @dtypes(torch.half, torch.float)\n def test_conv_cudnn_ndhwc(self, device, dtype):\n def helper(n, c, d, h, w, out_channels, kernel_size, groups):\n input = torch.randint(-2, 2, (n, c, d, h, w), dtype=dtype, device=device)\\\n .to(memory_format=torch.channels_last_3d)\n input.requires_grad_()\n conv = nn.Conv3d(c, out_channels, kernel_size, groups=groups)\\\n .to(device='cuda', dtype=dtype, memory_format=torch.channels_last_3d)\n for p in conv.parameters():\n p.data = torch.randint_like(p, -2, 2)\n\n # use FP64 channels-first conv as reference\n ref_input = input.detach().clone().contiguous().double().requires_grad_()\n ref_conv = nn.Conv3d(c, out_channels, kernel_size, groups=groups)\n # load_state_dict will restore the stride & memory_layout on ref_conv.weight.\n ref_conv.load_state_dict(conv.state_dict())\n ref_conv = ref_conv.to(device='cuda', dtype=torch.double, memory_format=torch.contiguous_format)\n\n out = conv(input)\n ref_out = ref_conv(ref_input)\n\n grad = torch.randint_like(out, -2, 2)\n ref_grad = grad.detach().clone().double().contiguous()\n\n out.backward(grad)\n ref_out.backward(ref_grad)\n\n self.assertTrue(out.is_contiguous(memory_format=torch.channels_last_3d))\n self.assertTrue(input.grad.is_contiguous(memory_format=torch.channels_last_3d))\n self.assertTrue(conv.weight.grad.is_contiguous(memory_format=torch.channels_last_3d))\n\n self.assertTrue(ref_out.is_contiguous())\n self.assertTrue(ref_input.grad.is_contiguous())\n self.assertTrue(ref_conv.weight.grad.is_contiguous())\n\n self.assertEqual(out, ref_out, exact_dtype=False)\n self.assertEqual(conv.weight.grad, ref_conv.weight.grad, exact_dtype=False)\n self.assertEqual(conv.bias.grad, ref_conv.bias.grad, exact_dtype=False)\n self.assertEqual(input.grad, ref_input.grad, exact_dtype=False)\n\n helper(2, 8, 4, 4, 4, out_channels=4, kernel_size=3, groups=1)\n helper(2, 8, 4, 4, 4, out_channels=8, kernel_size=3, groups=8)\n helper(1, 16, 18, 18, 18, out_channels=16, kernel_size=3, groups=1)\n helper(1, 16, 18, 18, 18, out_channels=16, kernel_size=3, groups=16)\n\n def _run_conv(self, layer, device, inp, grad, ref_conv, ref_input, ref_out,\n input_format, weight_format, grad_format, output_format):\n conv = layer(inp.size(1), grad.size(1),\n ref_conv.weight.size(2)).float().to(device)\n # load_state_dict will restore the stride & memory_layout on ref_conv.weight.\n conv.load_state_dict(ref_conv.state_dict())\n weight_data = conv.weight.detach().clone().contiguous(memory_format=weight_format)\n conv.weight.data = weight_data.resize_(weight_data.size(), memory_format=weight_format)\n input = inp.clone().contiguous(memory_format=input_format)\n input.resize_(input.size(), memory_format=input_format)\n input = input.requires_grad_()\n grad = grad.contiguous(memory_format=grad_format)\n grad.resize_(grad.size(), memory_format=grad_format)\n out = conv(input)\n out.backward(grad)\n self.assertTrue(out.is_contiguous(memory_format=output_format))\n self.assertEqual(out, ref_out)\n self.assertEqual(conv.weight.grad, ref_conv.weight.grad)\n self.assertEqual(conv.bias.grad, ref_conv.bias.grad)\n self.assertEqual(input.grad, ref_input.grad)\n\n def _test_conv_cudnn_nhwc_nchw(self, layer, n, c, h, w, k, filter_size, device):\n data = torch.randint(1, 10, (n, c, h, w), dtype=torch.float32, device=device)\n ref_input = data.clone().contiguous().requires_grad_(True)\n ref_conv = layer(c, k, filter_size).float().to(device)\n ref_out = ref_conv(ref_input)\n grad = torch.randint(1, 10, ref_out.size(), dtype=torch.float32, device=\"cuda\")\n ref_out.backward(grad)\n\n for w_f in [torch.contiguous_format, torch.channels_last]:\n for g_f in [torch.contiguous_format, torch.channels_last]:\n for input_format in [torch.contiguous_format, torch.channels_last]:\n output_format = torch.contiguous_format\n # Older versions of CudNN have Channels Last support disabled\n if torch.backends.cudnn.version() >= 7603:\n if input_format == torch.channels_last:\n output_format = torch.channels_last\n # This is because we have N111 weight that cannot handle\n # the ambiguous memory_format\n if w_f == torch.channels_last:\n if layer == nn.Conv2d and filter_size * c != 1:\n output_format = torch.channels_last\n if layer == nn.ConvTranspose2d and filter_size * k != 1:\n output_format = torch.channels_last\n self._run_conv(layer, device, data, grad, ref_conv, ref_input,\n ref_out, input_format, w_f, g_f, output_format)\n\n @onlyCUDA\n @skipCUDAIfRocm\n @skipCUDAIfCudnnVersionLessThan(7603)\n @tf32_on_and_off(0.05)\n def test_conv_cudnn_mismatch_memory_format(self, device):\n configs = [\n [4, 2, 8, 8, 4, 2],\n [4, 1, 8, 8, 4, 2],\n [1, 1, 8, 8, 4, 2],\n [4, 2, 2, 8, 4, 1],\n [4, 2, 1, 8, 4, 1],\n [4, 2, 8, 8, 4, 1],\n [4, 1, 8, 8, 4, 1],\n ]\n for n, c, h, w, k, filter_size in configs:\n self._test_conv_cudnn_nhwc_nchw(nn.Conv2d, n, c, h, w, k, filter_size, device)\n self._test_conv_cudnn_nhwc_nchw(nn.ConvTranspose2d, n, c, h, w, k, filter_size, device)\n\n # torch.half is erroring out on Windows with CUDA 10.1 + cuDNN 7.6.4\n # returning CUDNN_STATUS_BAD_PARAM\n # Disabling that specific test for now [see issue # 33918]\n @onlyCUDA\n @skipCUDAIfNoCudnn\n @dtypes(torch.float, torch.double)\n def test_conv_cudnn_nhwc_support(self, device, dtype):\n input = torch.randn((1, 16, 1, 1), dtype=dtype, device=\"cuda\", requires_grad=True)\n weight = torch.randn((8, 16, 3, 3), dtype=dtype, device=\"cuda\", requires_grad=True)\n weight = weight.to(memory_format=torch.channels_last)\n o = torch.conv2d(input, weight, None, (2, 1), (1, 1), (1, 1), 1)\n self.assertTrue(o.is_contiguous(memory_format=torch.channels_last))\n o.sum().backward()\n\n\n @onlyCUDA\n @skipCUDAIfRocm\n @skipCUDAIfCudnnVersionLessThan(7603)\n def test_convert_conv2d_weight_memory_format(self, device):\n input = torch.randint(1, 10, (2, 8, 4, 4), dtype=torch.float32, device=device)\n model = nn.Sequential(\n nn.Conv2d(8, 4, 3),\n nn.BatchNorm2d(4)).to(device).float()\n for memory_format in [torch.channels_last, torch.contiguous_format]:\n model = nn.utils.convert_conv2d_weight_memory_format(model, memory_format)\n out = model(input)\n self.assertTrue(out.is_contiguous(memory_format=memory_format))\n\n model = nn.Sequential(\n nn.ConvTranspose2d(8, 4, 3),\n nn.BatchNorm2d(4)).to(device).float()\n for memory_format in [torch.channels_last, torch.contiguous_format]:\n model = nn.utils.convert_conv2d_weight_memory_format(model, memory_format)\n out = model(input)\n self.assertTrue(out.is_contiguous(memory_format=memory_format))\n\n def test_nll_loss_mismatched_batch(self, device):\n x = torch.randn((10, 3), requires_grad=True, device=device)\n # t should have size (10,)\n t = torch.zeros((3,), dtype=torch.int64, device=device)\n with self.assertRaisesRegex(ValueError, 'Expected.*batch_size'):\n F.nll_loss(x, t)\n\n def test_nll_loss_out_of_bounds_ignore_index(self, device):\n x = torch.randn(6, 3, requires_grad=True, device=device)\n t = torch.tensor([0, 1, 255, 0, 1, 2], dtype=torch.int64, device=device)\n for reduction in ['mean', 'none']:\n F.nll_loss(x, t, ignore_index=255, reduction=reduction).sum().backward()\n\n def _nll_loss_helper(self, input_size, reduction, expected, device):\n input = torch.rand(input_size, requires_grad=True, device=device)\n num_channels = input_size[1]\n target_size = (input_size[0], ) + tuple(input_size[2:])\n target = torch.randint(num_channels, target_size, device=device)\n\n output = F.nll_loss(input, target, reduction=reduction)\n # TODO(#38095): Replace assertEqualIgnoreType. See issue #38095\n self.assertEqualIgnoreType(output, expected)\n\n output.sum().backward()\n self.assertEqual(input.grad.size(), input.size())\n\n def test_nll_loss_empty_tensor_reduction_none(self, device):\n self._nll_loss_helper([0, 3], \"none\", torch.empty([0], device=device), device)\n self._nll_loss_helper([0, 3, 5, 7], \"none\", torch.empty([0, 5, 7], device=device), device)\n self._nll_loss_helper([2, 3, 0, 7], \"none\", torch.empty([2, 0, 7], device=device), device)\n self._nll_loss_helper([2, 3, 5, 0], \"none\", torch.empty([2, 5, 0], device=device), device)\n self._nll_loss_helper([2, 3, 5, 7, 0], \"none\", torch.empty([2, 5, 7, 0], device=device), device)\n\n @unittest.skipIf(TEST_WITH_UBSAN, \"division-by-zero error with UBSAN\")\n def test_nll_loss_empty_tensor_reduction_mean(self, device):\n nan = torch.tensor(float('nan'), device=device)\n self._nll_loss_helper([0, 3], \"mean\", nan, device)\n self._nll_loss_helper([0, 3, 5, 7], \"mean\", nan, device)\n self._nll_loss_helper([2, 3, 0, 7], \"mean\", nan, device)\n self._nll_loss_helper([2, 3, 5, 0], \"mean\", nan, device)\n self._nll_loss_helper([2, 3, 5, 7, 0], \"mean\", nan, device)\n\n def test_nll_loss_empty_tensor_reduction_sum(self, device):\n zero = torch.tensor(0, device=device)\n self._nll_loss_helper([0, 3], \"sum\", zero, device)\n self._nll_loss_helper([0, 3, 5, 7], \"sum\", zero, device)\n self._nll_loss_helper([2, 3, 0, 7], \"sum\", zero, device)\n self._nll_loss_helper([2, 3, 5, 0], \"sum\", zero, device)\n self._nll_loss_helper([2, 3, 5, 7, 0], \"sum\", zero, device)\n\n def test_nll_loss_total_weight_is_zero(self, device):\n\n def helper(input_size):\n input = torch.ones(input_size, requires_grad=True, device=device)\n num_channels = input_size[1]\n target_size = (input_size[0], ) + tuple(input_size[2:])\n target = torch.zeros(target_size, dtype=torch.long, device=device)\n weight = torch.zeros([num_channels], device=device)\n self.assertEqual(F.nll_loss(input, target, weight).item(), 0)\n\n helper([2, 3])\n helper([2, 3, 5, 7])\n helper([2, 3, 5, 7, 9])\n\n def test_softshrink_negative(self, device):\n input = torch.randn(5, device=device, requires_grad=True)\n m = torch.nn.Softshrink(-1)\n with self.assertRaisesRegex(RuntimeError,\n r'lambda must be greater or equal to 0, but found to be -1\\.'):\n m(input)\n\n def test_unfold(self, device):\n def func(x):\n return F.unfold(x, kernel_size=(3, 3))\n seeds = (13, 256, 811, 43, 7)\n for sd in seeds:\n torch.manual_seed(sd)\n x = torch.randn(1, 1, 5, 5, device=device, requires_grad=True)\n gradcheck(func, [x])\n gradgradcheck(func, [x])\n\n def test_fold(self, device):\n def func(x):\n return F.fold(x, output_size=(4, 5), kernel_size=(2, 2))\n seeds = (44, 83, 71, 25, 999)\n for sd in seeds:\n torch.manual_seed(sd)\n x = torch.randn(1, 12, 12, device=device, requires_grad=True)\n gradcheck(func, [x])\n gradgradcheck(func, [x])\n\n def test_logsigmoid_out(self, device):\n # this isn't actually documented, but was broken previously:\n # https://github.com/pytorch/pytorch/issues/36499\n x = torch.randn(2, 3, device=device).t()\n empty_out = torch.randn(0, device=device)\n self.assertEqual(F.logsigmoid(x), F.logsigmoid(x, out=empty_out))\n\n noncontig_out = torch.randn(2, 3, device=device).t()\n self.assertEqual(F.logsigmoid(x), F.logsigmoid(x, out=noncontig_out))\n\n def test_maxpool3d_non_square_backward(self, device):\n # previous CUDA routine of this backward calculates kernel launch grid size\n # with last two dimensions interchanged, so the tailing along the longer dim\n # get ignored. Here we test whether every position gets gradient.\n for dim in (2, 3, 4):\n shape = tuple(32 if i != dim else 256 for i in range(4))\n x = torch.randn(shape, device=device, requires_grad=True)\n F.max_pool3d(x, kernel_size=(1, 1, 1)).sum().backward()\n self.assertTrue(torch.allclose(x.grad, torch.ones_like(x.grad)))\n\n # Check that clip_grad_norm_ raises an error if the total norm of the\n # parameters' gradients is non-finite\n def test_clip_grad_norm_error_if_nonfinite(self, device):\n norms_pos = [0.1, 1, 2, 3.5, inf]\n norms_neg = [-0.1, -1, -2, -3.5]\n norms_except_0 = norms_pos + norms_neg\n norms_all = norms_except_0 + [0]\n\n # Each entry in test_cases has the following values, in this order:\n #\n # grad_only_one_elem If True, only one element of the parameter's\n # gradient is set to the scalar grad, and the\n # rest of the elements are 0. If False, all grad\n # elements are equal to the scalar.\n #\n # prefix_finite_grad_param If True, prefix a parameter that has a grad\n # of 1.\n #\n # scalars Scalars to use as the parameter's grad, through\n # multiplication\n #\n # norms_nonfinite Norm types that should produce nonfinite total norm\n #\n # norms_finite Norm types that should produce finite total norm\n test_cases = [\n # Test errors from an infinite grad\n (False, False, [inf, -inf], norms_except_0, [0]),\n (False, True, [inf, -inf], norms_pos, norms_neg + [0]),\n (True, False, [inf, -inf], norms_pos, norms_neg + [0]),\n (True, True, [inf, -inf], norms_pos, norms_neg + [0]),\n\n # Test errors from a NaN grad\n (False, False, [nan], norms_except_0, [0]),\n (False, True, [nan], norms_except_0, [0]),\n (True, False, [nan], norms_except_0, [0]),\n (True, True, [nan], norms_except_0, [0]),\n\n # Test a grad that should never error\n (False, False, [2e22, -2e22], [], norms_all),\n (False, True, [2e22, -2e22], [], norms_all),\n (True, False, [2e22, -2e22], [], norms_all),\n (True, True, [2e22, -2e22], [], norms_all),\n\n # Test a grad that will overflow to inf for only some norm orders\n (False, False, [2e200, -2e200], [3.5, 2, -2, -3.5], [inf, 1, 0.1, 0, -1, -0.1]),\n (False, True, [2e200, -2e200], [3.5, 2], norms_neg + [inf, 1, 0.1, 0]),\n (True, False, [2e200, -2e200], [3.5, 2], norms_neg + [inf, 1, 0.1, 0]),\n (True, True, [2e200, -2e200], [3.5, 2], norms_neg + [inf, 1, 0.1, 0]),\n ]\n\n def gen_parameters(scalar, grad_only_one_elem, prefix_finite_grad_param):\n param = torch.ones(10, dtype=torch.float64, device=device, requires_grad=True)\n\n if grad_only_one_elem:\n param[1].mul(scalar).sum().backward()\n else:\n param.mul(scalar).sum().backward()\n\n if prefix_finite_grad_param:\n prefix_param = torch.ones(1, dtype=torch.float64, device=device, requires_grad=True)\n prefix_param.mul(1).sum().backward()\n parameters = [prefix_param, param]\n else:\n parameters = [param]\n\n return parameters\n\n def run_test_case(norm_type, error_if_nonfinite, scalar, grad_only_one_elem, prefix_finite_grad_param, is_norm_nonfinite):\n msg = (\n f'norm_type: {norm_type}, ',\n f'error_if_nonfinite: {error_if_nonfinite}, '\n f'scalar: {scalar}, '\n f'grad_only_one_elem: {grad_only_one_elem}, '\n f'prefix_finite_grad_param: {prefix_finite_grad_param}, '\n f'is_norm_nonfinite: {is_norm_nonfinite}')\n\n parameters = gen_parameters(scalar, grad_only_one_elem, prefix_finite_grad_param)\n\n # Should only throw an error if the total norm is expected to be\n # nonfinite and `error_if_nonfinite=True`\n if is_norm_nonfinite and error_if_nonfinite:\n error_msg = f'The total norm of order {float(norm_type)} for gradients'\n\n grads_before = [p.grad.clone() for p in parameters]\n\n with self.assertRaisesRegex(RuntimeError, error_msg, msg=msg):\n clip_grad_norm_(parameters, 1, norm_type=norm_type, error_if_nonfinite=True)\n\n # Grad should not change if error is thrown\n grads_after = [p.grad for p in parameters]\n self.assertEqual(grads_before, grads_after, msg=msg)\n else:\n clip_grad_norm_(parameters, 1, norm_type=norm_type, error_if_nonfinite=error_if_nonfinite)\n\n for grad_only_one_elem, prefix_finite_grad_param, scalars, norms_nonfinite, norms_finite in test_cases:\n for error_if_nonfinite in [False, True]:\n for norm_type, scalar in product(norms_nonfinite, scalars):\n run_test_case(norm_type, error_if_nonfinite, scalar, grad_only_one_elem, prefix_finite_grad_param, True)\n\n for norm_type, scalar in product(norms_finite, scalars):\n run_test_case(norm_type, error_if_nonfinite, scalar, grad_only_one_elem, prefix_finite_grad_param, False)\n\n @onlyCUDA\n @deviceCountAtLeast(2)\n def test_clip_grad_norm_multi_device(self, devices):\n class TestModel(nn.Module):\n def __init__(self):\n super(TestModel, self).__init__()\n self.layer1 = nn.Linear(10, 10)\n self.layer2 = nn.Linear(10, 10)\n\n test_model = TestModel()\n test_model.layer1.to(devices[0])\n test_model.layer2.to(devices[1])\n ref_model = TestModel().to(devices[0])\n for norm_type in [2., math.inf]:\n for p in test_model.parameters():\n p.grad = torch.ones_like(p)\n for p in ref_model.parameters():\n p.grad = torch.ones_like(p)\n norm = clip_grad_norm_(test_model.parameters(), 0.5, norm_type=norm_type)\n expected = clip_grad_norm_(ref_model.parameters(), 0.5, norm_type=norm_type)\n self.assertEqual(norm, expected)\n for p, pe in zip(test_model.parameters(), ref_model.parameters()):\n self.assertEqual(p.grad.to(devices[0]), pe.grad)\n\n @expectedFailureMeta # https://github.com/pytorch/pytorch/issues/54897\n def test_elu_inplace_overlap(self, device):\n x = torch.randn((1, 6), device=device).expand((6, 6))\n with self.assertRaisesRegex(RuntimeError, 'unsupported operation'):\n F.elu(x, inplace=True)\n with self.assertRaisesRegex(RuntimeError, 'unsupported operation'):\n F.elu_(x)\n\n @expectedFailureMeta # https://github.com/pytorch/pytorch/issues/54897\n def test_hardswish_inplace_overlap(self, device):\n x = torch.randn((1, 6), device=device).expand((6, 6))\n with self.assertRaisesRegex(RuntimeError, 'unsupported operation'):\n F.hardswish(x, inplace=True)\n\n @expectedFailureMeta # https://github.com/pytorch/pytorch/issues/54897\n def test_silu_inplace_overlap(self, device):\n x = torch.randn((1, 6), device=device).expand((6, 6))\n with self.assertRaisesRegex(RuntimeError, 'unsupported operation'):\n F.silu(x, inplace=True)\n\n @expectedFailureMeta # https://github.com/pytorch/pytorch/issues/54897\n def test_softplus_inplace_overlap(self, device):\n x = torch.randn((1, 6), device=device).expand((6, 6))\n with self.assertRaisesRegex(RuntimeError, 'unsupported operation'):\n F.softplus(x, out=x)\n\n @expectedFailureMeta # https://github.com/pytorch/pytorch/issues/54897\n def test_softshrink_inplace_overlap(self, device):\n x = torch.randn((1, 6), device=device).expand((6, 6))\n with self.assertRaisesRegex(RuntimeError, 'unsupported operation'):\n F.softshrink(x, out=x)\n\n @expectedFailureMeta # https://github.com/pytorch/pytorch/issues/54897\n def test_leaky_relu_inplace_overlap(self, device):\n x = torch.randn((1, 6), device=device).expand((6, 6))\n with self.assertRaisesRegex(RuntimeError, 'unsupported operation'):\n F.leaky_relu(x, inplace=True)\n with self.assertRaisesRegex(RuntimeError, 'unsupported operation'):\n F.leaky_relu_(x)\n\n def test_threshold_inplace_overlap(self, device):\n # Inplace threshold is okay, because it is idempotent\n x = torch.randn((1, 6), device=device).expand((6, 6))\n F.threshold(x, 0.5, 0.5, inplace=True)\n F.threshold_(x, 0.5, 0.5)\n\n @onlyOnCPUAndCUDA\n def test_triplet_margin_with_distance_loss_default_parity(self, device):\n # Test for `nn.TripletMarginWithDistanceLoss` and\n # `F.triplet_margin_with_distance_loss`. Checks\n # for parity against the respective non-distance-agnostic\n # implementations of triplet margin loss (``nn.TripletMarginLoss`\n # and `F.triplet_margin_loss`) under *default args*.\n\n for extra_args in \\\n itertools.product((0.5, 1, 1.5), (True, False), ('none', 'mean', 'sum')):\n kwargs = {'margin': extra_args[0], 'swap': extra_args[1], 'reduction': extra_args[2]}\n\n anchor = torch.randn(5, 10, device=device, requires_grad=True)\n positive = torch.randn(5, 10, device=device, requires_grad=True)\n negative = torch.randn(5, 10, device=device, requires_grad=True)\n\n # Test forward, functional\n expected = F.triplet_margin_loss(anchor, positive, negative, **kwargs)\n actual = F.triplet_margin_with_distance_loss(anchor, positive, negative, **kwargs)\n self.assertEqual(actual, expected, rtol=1e-6, atol=1e-6)\n\n # Test forward, module\n loss_ref = nn.TripletMarginLoss(**kwargs)\n loss_op = nn.TripletMarginWithDistanceLoss(**kwargs)\n self.assertEqual(loss_op(anchor, positive, negative),\n loss_ref(anchor, positive, negative),\n rtol=1e-6, atol=1e-6)\n\n # Test backward\n self.assertTrue(gradcheck(lambda a, p, n: F.triplet_margin_with_distance_loss(\n a, p, n, **kwargs), (anchor, positive, negative)))\n self.assertTrue(gradcheck(lambda a, p, n: loss_op(a, p, n),\n (anchor, positive, negative)))\n\n @onlyOnCPUAndCUDA\n def test_triplet_margin_with_distance_loss(self, device):\n # Test for parity between `nn.TripletMarginWithDistanceLoss` and\n # `F.triplet_margin_with_distance_loss`.\n\n pairwise_distance = nn.PairwiseDistance()\n\n def cosine_distance(x, y):\n return 1.0 - F.cosine_similarity(x, y)\n\n distance_functions = (pairwise_distance, cosine_distance,\n lambda x, y: 1.0 - F.cosine_similarity(x, y))\n\n reductions = ('mean', 'none', 'sum')\n margins = (1.0, 1.5, 0.5)\n swaps = (True, False)\n\n for distance_fn, reduction, margin, swap \\\n in itertools.product(distance_functions, reductions, margins, swaps):\n anchor = torch.randn(5, 10, device=device, requires_grad=True)\n positive = torch.randn(5, 10, device=device, requires_grad=True)\n negative = torch.randn(5, 10, device=device, requires_grad=True)\n\n # Test backward\n self.assertTrue(gradcheck(lambda a, p, n: F.triplet_margin_with_distance_loss(\n a, p, n, distance_function=distance_fn, reduction=reduction, margin=margin, swap=swap),\n (anchor, positive, negative)))\n loss_op = nn.TripletMarginWithDistanceLoss(distance_function=distance_fn,\n reduction=reduction, margin=margin, swap=swap)\n self.assertTrue(gradcheck(lambda a, p, n: loss_op(\n a, p, n), (anchor, positive, negative)))\n traced_loss_op = torch.jit.trace(loss_op, (anchor, positive, negative))\n self.assertTrue(gradcheck(lambda a, p, n: traced_loss_op(\n a, p, n), (anchor, positive, negative)))\n\n # Test forward parity\n functional = F.triplet_margin_with_distance_loss(anchor, positive, negative,\n distance_function=distance_fn,\n reduction=reduction, margin=margin, swap=swap)\n modular = loss_op(anchor, positive, negative)\n traced = traced_loss_op(anchor, positive, negative)\n self.assertEqual(functional, modular, atol=1e-6, rtol=1e-6)\n self.assertEqual(traced, modular, atol=1e-6, rtol=1e-6)\n\n def test_to_complex(self, device):\n m = nn.Linear(3, 5).to(device)\n self.assertIs(m, m.to(device))\n m.to(torch.cfloat)\n self.assertIs(m.weight.dtype, torch.cfloat)\n m.to(torch.cdouble)\n self.assertIs(m.weight.dtype, torch.cdouble)\n m.to(torch.float)\n self.assertIs(m.weight.dtype, torch.float)\n with warnings.catch_warnings(record=True) as w:\n # Trigger warning\n m.to(torch.cfloat)\n # Check warning occurs\n self.assertEqual(len(w), 1)\n self.assertTrue(\"Complex modules are a new feature\" in str(w[-1].message))\n\n\nclass TestModuleGlobalHooks(TestCase):\n\n def tearDown(self):\n nn.modules.module._global_backward_hooks = OrderedDict()\n nn.modules.module._global_forward_hooks = OrderedDict()\n nn.modules.module._global_forward_pre_hooks = OrderedDict()\n\n def test_module_global_hooks(self):\n module = nn.Sigmoid\n\n module_1 = module()\n module_2 = module()\n module_3 = module()\n\n input = torch.ones(5, 5, requires_grad=True)\n\n counter = {\n 'forwards': 0,\n 'backwards': 0\n }\n\n def fw_hook(inc, h_module, input, output):\n self.assertIsInstance(input, tuple)\n self.assertTrue(isinstance(output, torch.Tensor))\n self.assertTrue(isinstance(h_module, module))\n self.assertEqual(input[0], torch.ones(5, 5))\n self.assertEqual(output, torch.Tensor(5, 5).fill_(1 / (1 + 1 / math.e)))\n counter['forwards'] += inc\n\n def bw_hook(inc, h_module, grad_input, grad_output):\n self.assertIsInstance(grad_input, tuple)\n self.assertIsInstance(grad_output, tuple)\n self.assertTrue(isinstance(h_module, module))\n self.assertEqual(grad_output[0], torch.ones(5, 5) * 2)\n counter['backwards'] += inc\n\n test_fwd = nn.modules.module.register_module_forward_hook(lambda *args: fw_hook(1, *args))\n\n module_1(input)\n module_2(input)\n module_3(input)\n self.assertEqual(counter['forwards'], 3)\n self.assertEqual(counter['backwards'], 0)\n\n test_bwd = nn.modules.module.register_module_backward_hook(\n lambda *args: bw_hook(1, *args))\n\n output_1 = module_1(input)\n output_2 = module_2(input)\n output_3 = module_3(input)\n self.assertEqual(counter['forwards'], 6)\n self.assertEqual(counter['backwards'], 0)\n\n output_1.backward(torch.ones(5, 5) * 2, retain_graph=True)\n output_2.backward(torch.ones(5, 5) * 2, retain_graph=False)\n output_3.backward(torch.ones(5, 5) * 2, retain_graph=False)\n self.assertEqual(counter['forwards'], 6)\n self.assertEqual(counter['backwards'], 3)\n\n output_1.backward(torch.ones(5, 5) * 2, retain_graph=True)\n self.assertEqual(counter['forwards'], 6)\n self.assertEqual(counter['backwards'], 4)\n\n test2_fwd = nn.modules.module.register_module_forward_hook(lambda *args: fw_hook(2, *args))\n\n output = module_1(input)\n output = module_2(input)\n output = module_3(input)\n self.assertEqual(counter['forwards'], 15)\n self.assertEqual(counter['backwards'], 4)\n\n test2_bwd = nn.modules.module.register_module_backward_hook(lambda *args: bw_hook(2, *args))\n\n module_1(input).backward(torch.ones(5, 5) * 2)\n self.assertEqual(counter['forwards'], 18)\n self.assertEqual(counter['backwards'], 7)\n\n test2_bwd.remove()\n\n module_2(input).backward(torch.ones(5, 5) * 2)\n self.assertEqual(counter['forwards'], 21)\n self.assertEqual(counter['backwards'], 8)\n\n test2_fwd.remove()\n\n module_3(input).backward(torch.ones(5, 5) * 2)\n self.assertEqual(counter['forwards'], 22)\n self.assertEqual(counter['backwards'], 9)\n\n test_fwd.remove()\n test_bwd.remove()\n\n def test_module_global_hook_invalid_outputs(self):\n module = nn.Sigmoid()\n input = torch.randn(5, 5, requires_grad=True)\n\n def bw_fail1(self, grad_input, grad_output):\n return grad_input[:-1]\n\n def bw_fail2(self, grad_input, grad_output):\n return grad_input + (torch.randn(2, 2),)\n\n with nn.modules.module.register_module_backward_hook(bw_fail1):\n with self.assertRaisesRegex(RuntimeError, 'got 0, but expected 1'):\n module(input).sum().backward()\n\n with nn.modules.module.register_module_backward_hook(bw_fail2):\n with self.assertRaisesRegex(RuntimeError, 'got 2, but expected 1'):\n module(input).sum().backward()\n\n def test_module_backward_global_hook_writeable(self):\n module = nn.Sigmoid()\n input = torch.randn(5, 5, requires_grad=True)\n sig_x = torch.sigmoid(input)\n\n def bw_hook(module, grad_input, grad_output):\n for grad in grad_input:\n self.assertTrue(isinstance(grad, torch.Tensor))\n for grad in grad_output:\n self.assertTrue(isinstance(grad, torch.Tensor))\n return tuple(gi * 2 for gi in grad_input)\n\n nn.modules.module.register_module_backward_hook(bw_hook)\n module(input).backward(torch.ones(5, 5))\n expected_grad = sig_x * (1 - sig_x) * 2\n self.assertEqual(input.grad, expected_grad)\n\n def test_module_global_forward_preforward_hook_writeable(self):\n module = nn.Sigmoid()\n input = torch.randn(5, 5, requires_grad=True)\n sig_x = torch.sigmoid(input)\n\n def forward_pre_hook(m, input):\n return torch.nn.functional.relu(input[0])\n\n def forward_hook(m, input, output):\n return -output\n\n nn.modules.module.register_module_forward_pre_hook(forward_pre_hook)\n nn.modules.module.register_module_forward_hook(forward_hook)\n output = module(input)\n expected_res = -torch.sigmoid(torch.nn.functional.relu(input))\n self.assertEqual(output, expected_res)\n output.backward(torch.ones(5, 5) * 2, retain_graph=True)\n mask = (input > 0).double()\n expected_grad = -sig_x * (1 - sig_x) * 2 * mask\n self.assertEqual(input.grad, expected_grad)\n\n def test_global_and_local_hooks_order(self):\n module = nn.Sigmoid()\n\n global_forward_pre_called = False\n local_forward_pre_called = False\n global_forward_called = False\n local_forward_called = False\n global_backward_called = False\n local_backward_called = False\n\n def global_forward_pre_hook(m, input):\n nonlocal global_forward_pre_called\n self.assertTrue(not local_forward_pre_called)\n global_forward_pre_called = True\n return input\n\n def local_forward_pre_hook(m, input):\n nonlocal local_forward_pre_called\n self.assertTrue(global_forward_pre_called)\n local_forward_pre_called = True\n return input\n\n def global_forward_hook(m, input, output):\n nonlocal global_forward_called\n self.assertTrue(not local_forward_called)\n global_forward_called = True\n return output\n\n def local_forward_hook(m, input, output):\n nonlocal local_forward_called\n self.assertTrue(global_forward_called)\n local_forward_called = True\n return output\n\n def global_backward_hook(m, input, output):\n nonlocal global_backward_called\n self.assertTrue(not local_backward_called)\n global_backward_called = True\n return input\n\n def local_backward_hook(m, input, output):\n nonlocal local_backward_called\n self.assertTrue(global_backward_called)\n local_backward_called = True\n return input\n\n input = torch.randn(5, 5, requires_grad=True)\n nn.modules.module.register_module_forward_pre_hook(global_forward_pre_hook)\n module.register_forward_pre_hook(local_forward_pre_hook)\n nn.modules.module.register_module_forward_hook(global_forward_hook)\n module.register_forward_hook(local_forward_hook)\n nn.modules.module.register_module_backward_hook(global_backward_hook)\n module.register_backward_hook(local_backward_hook)\n\n output = module(input)\n self.assertTrue(local_forward_called and local_forward_pre_called and global_forward_called and global_forward_pre_called)\n\n output.backward(torch.ones(5, 5), retain_graph=True)\n self.assertTrue(local_backward_called and global_backward_called)\n\n\nclass LazyModule(torch.nn.modules.lazy.LazyModuleMixin, torch.nn.Module):\n pass\n\n\nclass TestLazyModules(TestCase):\n\n @suppress_warnings\n def test_lazy_module_parameter(self):\n module = LazyModule()\n module.register_parameter('test_param', UninitializedParameter())\n self.assertTrue(module.has_uninitialized_params())\n state_dict = module.state_dict()\n self.assertIsInstance(state_dict['test_param'], UninitializedParameter)\n new_module = LazyModule()\n # An error is raised when there is an attempt to replace an existing parameter\n # with an uninitialized one\n new_module.register_parameter('test_param', nn.Parameter(torch.ones(5, 5)))\n with self.assertRaisesRegex(RuntimeError, 'shape of an uninitialized'):\n new_module.load_state_dict(state_dict)\n # Uninitialized parameters are overriden when the state dict to be loaded contains a valid one\n new_module = LazyModule()\n new_module.register_parameter('test_param', nn.Parameter(torch.ones(5, 5)))\n module.load_state_dict(new_module.state_dict())\n self.assertEqual(module.test_param, torch.ones((5, 5)))\n\n # Uninitialized parameters are left unchanged\n module = LazyModule()\n module.register_parameter('test_param', UninitializedParameter())\n self.assertTrue(module.has_uninitialized_params())\n\n new_module = LazyModule()\n new_module.register_parameter('test_param', UninitializedParameter())\n module.load_state_dict(new_module.state_dict())\n self.assertTrue(module.has_uninitialized_params())\n\n @suppress_warnings\n def test_lazy_module_buffer(self):\n module = LazyModule()\n module.register_buffer('test_buffer', UninitializedBuffer())\n self.assertTrue(module.has_uninitialized_params())\n state_dict = module.state_dict()\n self.assertIsInstance(state_dict['test_buffer'], UninitializedBuffer)\n new_module = LazyModule()\n # An error is raised when there is an attempt to replace an existing parameter\n # with an uninitialized one\n new_module.register_buffer('test_buffer', torch.ones(5, 5))\n with self.assertRaisesRegex(RuntimeError, 'shape of an uninitialized'):\n new_module.load_state_dict(state_dict)\n # Uninitialized parameters are overriden when the state dict to be loaded contains a valid one\n new_module = LazyModule()\n new_module.register_buffer('test_buffer', torch.ones(5, 5))\n module.load_state_dict(new_module.state_dict())\n self.assertEqual(module.test_buffer, torch.ones((5, 5)))\n\n # Uninitialized parameters are left unchanged\n module = LazyModule()\n module.register_buffer('test_buffer', UninitializedBuffer())\n self.assertTrue(module.has_uninitialized_params())\n\n new_module = LazyModule()\n new_module.register_buffer('test_buffer', UninitializedBuffer())\n module.load_state_dict(new_module.state_dict())\n module.load_state_dict(new_module.state_dict())\n self.assertTrue(module.has_uninitialized_params())\n\n @suppress_warnings\n def test_lazy_module_jit_param(self):\n module = LazyModule()\n module.register_parameter('test_param', UninitializedParameter())\n self.assertTrue(module.has_uninitialized_params())\n with self.assertRaisesRegex(RuntimeError, 'run a forward pass'):\n torch.jit.script(module)\n\n @suppress_warnings\n def test_lazy_module_jit_buffer(self):\n module = LazyModule()\n module.register_buffer('test_buffer', UninitializedBuffer())\n self.assertTrue(module.has_uninitialized_params())\n with self.assertRaisesRegex(RuntimeError, 'run a forward pass'):\n torch.jit.script(module)\n\n @suppress_warnings\n def test_lazy_share_memory_param(self):\n module = LazyModule()\n module.register_parameter('test_param', UninitializedParameter())\n self.assertTrue(module.has_uninitialized_params())\n with self.assertRaisesRegex(RuntimeError, 'share memory on an uninitialized'):\n module.share_memory()\n\n @suppress_warnings\n def test_lazy_share_memory_buffer(self):\n module = LazyModule()\n module.register_buffer('test_buffer', UninitializedBuffer())\n self.assertTrue(module.has_uninitialized_params())\n with self.assertRaisesRegex(RuntimeError, 'share memory on an uninitialized'):\n module.share_memory()\n\n @suppress_warnings\n def test_linear(self):\n module = nn.LazyLinear(10)\n self.assertIsInstance(module.weight, UninitializedParameter)\n self.assertIsInstance(module.bias, UninitializedParameter)\n input = torch.ones(5, 5)\n module(input)\n self.assertIsInstance(module, nn.Linear)\n self.assertNotIsInstance(module, nn.LazyLinear)\n self.assertTrue(module.weight.shape == (10, 5))\n self.assertTrue(module.bias.shape == (10,))\n y = module(input)\n self.assertTrue(torch.equal(torch.nn.functional.linear(input, module.weight, module.bias), y))\n\n @suppress_warnings\n def test_lazy_linear_pickle(self):\n module = nn.LazyLinear(10)\n self.assertIsInstance(module.weight, UninitializedParameter)\n self.assertIsInstance(module.bias, UninitializedParameter)\n module = pickle.loads(pickle.dumps(module))\n self.assertIsInstance(module, nn.LazyLinear)\n self.assertIsInstance(module.weight, UninitializedParameter)\n self.assertIsInstance(module.bias, UninitializedParameter)\n input = torch.ones(5, 5)\n module(input) # fully materialized\n new_module = pickle.loads(pickle.dumps(module))\n self.assertIsInstance(new_module, nn.Linear)\n self.assertNotIsInstance(new_module, nn.LazyLinear)\n self.assertTrue(new_module.weight.shape == (10, 5))\n self.assertNotIsInstance(new_module.weight, UninitializedParameter)\n self.assertTrue(new_module.bias.shape == (10,))\n self.assertNotIsInstance(new_module.bias, UninitializedParameter)\n\n @suppress_warnings\n def test_linear_state(self):\n module = nn.Linear(5, 10)\n lazy_module = nn.LazyLinear(10)\n lazy_module.load_state_dict(module.state_dict())\n # Parameters have been initialized but the module won't become a full\n # Linear one until the first iteration. This is due to\n # limitations on the state_dict loading logic\n self.assertFalse(lazy_module.has_uninitialized_params())\n self.assertTrue(lazy_module.weight.shape == (10, 5))\n self.assertTrue(lazy_module.bias.shape == (10,))\n\n module = nn.Linear(5, 10)\n lazy_module = nn.LazyLinear(10)\n with self.assertRaisesRegex(RuntimeError, 'shape of an uninitialized'):\n module.load_state_dict(lazy_module.state_dict())\n\n def _check_lazy_conv(self, cls, lazy_cls, func, init_args, input_shape,\n expected_weight_shape, expected_bias_shape):\n module = lazy_cls(*init_args)\n self.assertIsInstance(module.weight, UninitializedParameter)\n if module.bias is not None:\n self.assertIsInstance(module.bias, UninitializedParameter)\n input = torch.ones(*input_shape)\n module(input)\n self.assertIsInstance(module, cls)\n self.assertNotIsInstance(module, lazy_cls)\n self.assertEqual(module.weight.shape, expected_weight_shape)\n if module.bias is not None:\n self.assertEqual(module.bias.shape, expected_bias_shape)\n y = module(input)\n self.assertTrue(torch.equal(func(input, module.weight, module.bias), y))\n\n def _check_lazy_conv_pickle(self, cls, lazy_cls, init_args, input_shape,\n expected_weight_shape, expected_bias_shape):\n module = lazy_cls(*init_args)\n self.assertIsInstance(module.weight, UninitializedParameter)\n if module.bias is not None:\n self.assertIsInstance(module.bias, UninitializedParameter)\n module = pickle.loads(pickle.dumps(module))\n self.assertIsInstance(module, lazy_cls)\n self.assertIsInstance(module.weight, UninitializedParameter)\n if module.bias is not None:\n self.assertIsInstance(module.bias, UninitializedParameter)\n input = torch.ones(*input_shape)\n module(input) # fully materialized\n new_module = pickle.loads(pickle.dumps(module))\n self.assertIsInstance(new_module, cls)\n self.assertNotIsInstance(new_module, lazy_cls)\n self.assertEqual(new_module.weight.shape, expected_weight_shape)\n self.assertNotIsInstance(new_module.weight, UninitializedParameter)\n if new_module.bias is not None:\n self.assertEqual(new_module.bias.shape, expected_bias_shape)\n self.assertNotIsInstance(new_module.bias, UninitializedParameter)\n\n def _check_lazy_conv_state(self, gen_module, gen_lazy_module,\n expected_weight_shape, expected_bias_shape):\n module = gen_module()\n lazy_module = gen_lazy_module()\n lazy_module.load_state_dict(module.state_dict())\n # Parameters have been initialized but the module won't become a full\n # Conv one until the first iteration. This is due to\n # limitations on the state_dict loading logic\n self.assertFalse(lazy_module.has_uninitialized_params())\n self.assertEqual(lazy_module.weight.shape, expected_weight_shape)\n if lazy_module.bias is not None:\n self.assertEqual(lazy_module.bias.shape, expected_bias_shape)\n\n module = gen_module()\n lazy_module = gen_lazy_module()\n with self.assertRaisesRegex(RuntimeError, 'shape of an uninitialized'):\n module.load_state_dict(lazy_module.state_dict())\n\n @suppress_warnings\n def test_lazy_conv1d(self):\n self._check_lazy_conv(nn.Conv1d, nn.LazyConv1d, torch.nn.functional.conv1d,\n (32, 2), (192, 16, 50), (32, 16, 2), (32,))\n\n @suppress_warnings\n def test_lazy_conv1d_pickle(self):\n self._check_lazy_conv_pickle(nn.Conv1d, nn.LazyConv1d, (32, 2), (192, 16, 50),\n (32, 16, 2), (32,))\n\n @suppress_warnings\n def test_lazy_conv1d_state(self):\n self._check_lazy_conv_state(lambda: nn.Conv1d(16, 32, 2),\n lambda: nn.LazyConv1d(32, 2),\n (32, 16, 2), (32,))\n\n @suppress_warnings\n def test_lazy_conv2d(self):\n self._check_lazy_conv(nn.Conv2d, nn.LazyConv2d, torch.nn.functional.conv2d,\n (32, 2), (192, 16, 8, 6), (32, 16, 2, 2), (32,))\n\n @suppress_warnings\n def test_lazy_conv2d_pickle(self):\n self._check_lazy_conv_pickle(nn.Conv2d, nn.LazyConv2d, (32, 2), (192, 16, 8, 6),\n (32, 16, 2, 2), (32,))\n\n @suppress_warnings\n def test_lazy_conv2d_state(self):\n self._check_lazy_conv_state(lambda: nn.Conv2d(16, 32, 2),\n lambda: nn.LazyConv2d(32, 2),\n (32, 16, 2, 2), (32,))\n\n @suppress_warnings\n def test_lazy_conv3d(self):\n self._check_lazy_conv(nn.Conv3d, nn.LazyConv3d, torch.nn.functional.conv3d,\n (32, 2), (192, 16, 8, 7, 6), (32, 16, 2, 2, 2), (32,))\n\n @suppress_warnings\n def test_lazy_conv3d_pickle(self):\n self._check_lazy_conv_pickle(nn.Conv3d, nn.LazyConv3d, (32, 2), (192, 16, 8, 7, 6),\n (32, 16, 2, 2, 2), (32,))\n\n @suppress_warnings\n def test_lazy_conv3d_state(self):\n self._check_lazy_conv_state(lambda: nn.Conv3d(16, 32, 2),\n lambda: nn.LazyConv3d(32, 2),\n (32, 16, 2, 2, 2), (32,))\n\n @suppress_warnings\n def test_lazy_conv_transposed1d(self):\n self._check_lazy_conv(nn.ConvTranspose1d, nn.LazyConvTranspose1d, torch.nn.functional.conv_transpose1d,\n (32, 2), (192, 16, 50), (16, 32, 2), (32,))\n\n @suppress_warnings\n def test_lazy_conv_transpose1d_pickle(self):\n self._check_lazy_conv_pickle(nn.ConvTranspose1d, nn.LazyConvTranspose1d, (32, 2),\n (192, 16, 50), (16, 32, 2), (32,))\n\n @suppress_warnings\n def test_lazy_conv_transpose1d_state(self):\n self._check_lazy_conv_state(lambda: nn.ConvTranspose1d(16, 32, 2),\n lambda: nn.LazyConvTranspose1d(32, 2),\n (16, 32, 2), (32,))\n\n @suppress_warnings\n def test_lazy_conv_transpose2d(self):\n self._check_lazy_conv(nn.ConvTranspose2d, nn.LazyConvTranspose2d, torch.nn.functional.conv_transpose2d,\n (32, 2), (192, 16, 8, 6), (16, 32, 2, 2), (32,))\n\n @suppress_warnings\n def test_lazy_conv_transpose2d_pickle(self):\n self._check_lazy_conv_pickle(nn.ConvTranspose2d, nn.LazyConvTranspose2d, (32, 2),\n (192, 16, 8, 6), (16, 32, 2, 2), (32,))\n\n @suppress_warnings\n def test_lazy_conv_transpose2d_state(self):\n self._check_lazy_conv_state(lambda: nn.ConvTranspose2d(16, 32, 2),\n lambda: nn.LazyConvTranspose2d(32, 2),\n (16, 32, 2, 2), (32,))\n\n @suppress_warnings\n def test_lazy_conv_transpose3d(self):\n self._check_lazy_conv(nn.ConvTranspose3d, nn.LazyConvTranspose3d, torch.nn.functional.conv_transpose3d,\n (32, 2), (192, 16, 8, 7, 6), (16, 32, 2, 2, 2), (32,))\n\n @suppress_warnings\n def test_lazy_conv_transpose3d_pickle(self):\n self._check_lazy_conv_pickle(nn.ConvTranspose3d, nn.LazyConvTranspose3d, (32, 2),\n (192, 16, 8, 7, 6), (16, 32, 2, 2, 2), (32,))\n\n @suppress_warnings\n def test_lazy_conv_transpose3d_state(self):\n self._check_lazy_conv_state(lambda: nn.ConvTranspose3d(16, 32, 2),\n lambda: nn.LazyConvTranspose3d(32, 2),\n (16, 32, 2, 2, 2), (32,))\n\n def _check_lazy_batchnorm(self, cls, lazy_cls, input_shape):\n for affine in [False, True]:\n for track_running_stats in [False, True]:\n lazy_module = lazy_cls(affine=affine, track_running_stats=track_running_stats)\n\n if affine:\n self.assertIsInstance(lazy_module.weight, UninitializedParameter)\n self.assertIsInstance(lazy_module.bias, UninitializedParameter)\n if track_running_stats:\n self.assertIsInstance(lazy_module.running_mean, UninitializedBuffer)\n self.assertIsInstance(lazy_module.running_var, UninitializedBuffer)\n\n input = torch.ones(*input_shape)\n y = lazy_module(input)\n self.assertIsInstance(lazy_module, cls)\n self.assertNotIsInstance(lazy_module, lazy_cls)\n\n num_features = input_shape[1]\n module = cls(num_features, affine=affine, track_running_stats=track_running_stats)\n expected = module(input)\n\n if module.weight is not None:\n self.assertEqual(lazy_module.weight.shape, module.weight.shape)\n self.assertEqual(lazy_module.weight, module.weight)\n if module.bias is not None:\n self.assertEqual(lazy_module.bias.shape, module.bias.shape)\n self.assertEqual(lazy_module.bias, module.bias)\n if module.running_mean is not None:\n self.assertEqual(lazy_module.running_mean.shape, module.running_mean.shape)\n self.assertEqual(lazy_module.running_mean, module.running_mean)\n if module.running_var is not None:\n self.assertEqual(lazy_module.running_var.shape, module.running_var.shape)\n self.assertEqual(lazy_module.running_var, module.running_var)\n if module.num_batches_tracked is not None:\n self.assertEqual(lazy_module.num_batches_tracked.shape, module.num_batches_tracked.shape)\n self.assertEqual(lazy_module.num_batches_tracked, module.num_batches_tracked)\n\n def _check_lazy_batchnorm_pickle(self, cls, lazy_cls, input_shape):\n for affine in [False, True]:\n for track_running_stats in [False, True]:\n module = lazy_cls(affine=affine, track_running_stats=track_running_stats)\n module = pickle.loads(pickle.dumps(module))\n\n self.assertIsInstance(module, lazy_cls)\n if affine:\n self.assertIsInstance(module.weight, UninitializedParameter)\n self.assertIsInstance(module.bias, UninitializedParameter)\n if track_running_stats:\n self.assertIsInstance(module.running_mean, UninitializedBuffer)\n self.assertIsInstance(module.running_var, UninitializedBuffer)\n\n input = torch.ones(*input_shape)\n module(input) # fully materialized\n module = pickle.loads(pickle.dumps(module))\n\n self.assertNotIsInstance(module, lazy_cls)\n self.assertIsInstance(module, cls)\n if affine:\n self.assertNotIsInstance(module.weight, UninitializedParameter)\n self.assertNotIsInstance(module.bias, UninitializedParameter)\n if track_running_stats:\n self.assertNotIsInstance(module.running_mean, UninitializedBuffer)\n self.assertNotIsInstance(module.running_var, UninitializedBuffer)\n\n def _check_lazy_batchnorm_state(self, cls, lazy_cls):\n module = cls(10)\n lazy_module = lazy_cls(affine=True, track_running_stats=True)\n lazy_module.load_state_dict(module.state_dict())\n # Parameters have been initialized but the module won't become a full\n # Conv one until the first iteration. This is due to\n # limitations on the state_dict loading logic\n self.assertFalse(lazy_module.has_uninitialized_params())\n self.assertEqual(lazy_module.weight.shape, (10,))\n self.assertEqual(lazy_module.bias.shape, (10,))\n self.assertEqual(lazy_module.running_mean.shape, (10,))\n self.assertEqual(lazy_module.running_var.shape, (10,))\n\n module = cls(10)\n lazy_module = lazy_cls()\n with self.assertRaisesRegex(RuntimeError, 'shape of an uninitialized'):\n module.load_state_dict(lazy_module.state_dict())\n\n def test_lazy_batchnorm1d(self):\n self._check_lazy_batchnorm(nn.BatchNorm1d, nn.LazyBatchNorm1d, (16, 3, 6))\n self._check_lazy_batchnorm(nn.BatchNorm1d, nn.LazyBatchNorm1d, (16, 6))\n\n def test_lazy_batchnorm1d_pickle(self):\n self._check_lazy_batchnorm_pickle(nn.BatchNorm1d, nn.LazyBatchNorm1d, (16, 3, 6))\n self._check_lazy_batchnorm_pickle(nn.BatchNorm1d, nn.LazyBatchNorm1d, (16, 6))\n\n def test_lazy_batchnorm1d_state(self):\n self._check_lazy_batchnorm_state(nn.BatchNorm1d, nn.LazyBatchNorm1d)\n self._check_lazy_batchnorm_state(nn.BatchNorm1d, nn.LazyBatchNorm1d)\n\n def test_lazy_batchnorm2d(self):\n self._check_lazy_batchnorm(nn.BatchNorm2d, nn.LazyBatchNorm2d, (16, 3, 6, 7))\n\n def test_lazy_batchnorm2d_pickle(self):\n self._check_lazy_batchnorm_pickle(nn.BatchNorm2d, nn.LazyBatchNorm2d, (16, 3, 6, 7))\n\n def test_lazy_batchnorm2d_state(self):\n self._check_lazy_batchnorm_state(nn.BatchNorm2d, nn.LazyBatchNorm2d)\n self._check_lazy_batchnorm_state(nn.BatchNorm2d, nn.LazyBatchNorm2d)\n\n def test_lazy_batchnorm3d(self):\n self._check_lazy_batchnorm(nn.BatchNorm3d, nn.LazyBatchNorm3d, (16, 3, 6, 7, 8))\n\n def test_lazy_batchnorm3d_pickle(self):\n self._check_lazy_batchnorm_pickle(nn.BatchNorm3d, nn.LazyBatchNorm3d, (16, 3, 6, 7, 8))\n\n def test_lazy_batchnorm3d_state(self):\n self._check_lazy_batchnorm_state(nn.BatchNorm3d, nn.LazyBatchNorm3d)\n self._check_lazy_batchnorm_state(nn.BatchNorm3d, nn.LazyBatchNorm3d)\n\n @suppress_warnings\n def test_materialize_dtype(self):\n module = LazyModule()\n module.register_parameter('test_param', UninitializedParameter())\n module.test_param.materialize(10)\n self.assertTrue(module.test_param.dtype == torch.float64)\n module = LazyModule()\n module.register_parameter('test_param', UninitializedParameter())\n module.half()\n module.test_param.materialize(10)\n self.assertTrue(module.test_param.dtype == torch.float16)\n\n @unittest.skipIf(not TEST_CUDA, 'CUDA not available')\n @suppress_warnings\n def test_materialize_device(self):\n module = LazyModule()\n module.register_parameter('test_param', UninitializedParameter())\n module.test_param.materialize(10)\n self.assertTrue(module.test_param.device.type == 'cpu')\n module = LazyModule()\n module.register_parameter('test_param', UninitializedParameter())\n module.cuda()\n module.test_param.materialize(10)\n self.assertTrue(module.test_param.device.type == 'cuda')\n\n @suppress_warnings\n def test_chained_initialization(self):\n class MyNetwork(torch.nn.Module):\n def __init__(self):\n super(MyNetwork, self).__init__()\n self.linear_1 = torch.nn.LazyLinear(15)\n self.linear_2 = torch.nn.LazyLinear(10)\n\n def forward(self, x):\n y = self.linear_1(x)\n return self.linear_2(y)\n\n net = MyNetwork()\n net(torch.ones(5, 10))\n self.assertTrue(net.linear_1.weight.shape == (15, 10))\n self.assertTrue(net.linear_1.bias.shape == (15,))\n self.assertTrue(net.linear_2.weight.shape == (10, 15))\n self.assertTrue(net.linear_2.bias.shape == (10,))\n\n @suppress_warnings\n def test_optimizer_pass(self):\n optimizers = [torch.optim.Adadelta, torch.optim.Adagrad, torch.optim.Adam,\n torch.optim.AdamW, torch.optim.Adamax,\n torch.optim.ASGD, torch.optim.SGD, torch.optim.Rprop,\n torch.optim.RMSprop, torch.optim.LBFGS]\n\n def run_step(module, optim):\n self.assertIsInstance(optim.param_groups[0]['params'][0], UninitializedParameter)\n module.test_param.materialize(10)\n self.assertIsInstance(optim.param_groups[0]['params'][0], Parameter)\n self.assertNotIsInstance(optim.param_groups[0]['params'][0], UninitializedParameter)\n for p in module.parameters():\n p.grad = torch.rand_like(p)\n if isinstance(optim, torch.optim.LBFGS):\n optim.step(lambda: 1.0)\n else:\n optim.step()\n\n for optim_cls in optimizers:\n module = LazyModule()\n module.register_parameter('test_param', UninitializedParameter())\n if optim_cls is torch.optim.SGD:\n optim = optim_cls(module.parameters(), lr=0.0)\n elif optim_cls is torch.optim.Adagrad:\n with self.assertRaisesRegex(ValueError, 'uninitialized parameter'):\n optim = optim_cls(module.parameters())\n continue\n else:\n optim = optim_cls(module.parameters())\n run_step(module, optim)\n\n @suppress_warnings\n def test_weight_norm(self):\n m = nn.LazyLinear(7)\n with self.assertRaisesRegex(ValueError, 'have uninitialized parameters.'):\n m = torch.nn.utils.weight_norm(m)\n\n @suppress_warnings\n def test_spectral_norm(self):\n m = nn.LazyLinear(7)\n with self.assertRaisesRegex(ValueError, 'have uninitialized parameters.'):\n m = torch.nn.utils.spectral_norm(m)\n\n @suppress_warnings\n def test_invalid_functions(self):\n param = torch.nn.parameter.UninitializedParameter()\n with self.assertRaisesRegex(ValueError, 'uninitialized parameter'):\n torch.empty_like(param)\n\n with self.assertRaisesRegex(ValueError, 'uninitialized parameter'):\n torch.add(param, param)\n\n with self.assertRaisesRegex(ValueError, 'uninitialized parameter'):\n param + param\n\nclass TestFunctionalPickle(TestCase):\n\n # issue gh-38137\n def test_pickle_softsign(self):\n # Make sure it does not throw an exception\n s = pickle.dumps(F.softsign)\n\n\ninstantiate_device_type_tests(TestNNDeviceType, globals())\n\nif __name__ == '__main__':\n run_tests()\n" ]
[ [ "torch.nn.functional.softshrink", "torch._nnpack_spatial_convolution", "torch.nn.SmoothL1Loss", "torch.nn.functional.adaptive_avg_pool1d", "torch.nn.functional.fractional_max_pool3d", "numpy.random.random", "torch.nn.init.normal_", "numpy.expand_dims", "torch.cosine_similarity", "torch.nn.ReplicationPad2d", "torch.nn.Threshold", "torch.nn.LazyConvTranspose3d", "torch.backends.cudnn.flags", "torch.nn.GRUCell", "torch.cuda.synchronize", "torch.nn.utils.prune.RandomStructured", "torch.nn.Upsample", "numpy.dot", "torch.nn.functional.huber_loss", "torch.nn.functional.nll_loss", "torch.nn.AdaptiveLogSoftmaxWithLoss.__call__", "torch.nn.functional.avg_pool3d", "torch.abs", "torch.randint", "torch.randn_like", "torch.nn.Bilinear", "torch.nn.KLDivLoss", "torch.nn.modules.module.register_module_forward_pre_hook", "torch.equal", "torch.nn.functional.gaussian_nll_loss", "numpy.array", "torch._grid_sampler_2d_cpu_fallback", "torch.nn.utils.remove_weight_norm", "torch.nn.init.trunc_normal_", "torch.nn.init.uniform_", "torch.matmul", "torch.nn.utils.clip_grad_value_", "torch.nn.functional.avg_pool1d", "torch.all", "torch.nn.functional.max_pool2d", "torch.nn.ParameterList", "torch.nn.Unfold", "torch.nn.ModuleDict", "torch.nn.functional.multi_head_attention_forward", "torch.nn.functional.adaptive_max_pool3d", "torch.nn.AvgPool3d", "torch.nn.functional.ctc_loss", "torch.testing._internal.common_nn.NewModuleTest", "torch.testing._internal.common_device_type.dtypes", "torch.nn.functional.embedding_bag", "torch.manual_seed", "numpy.transpose", "torch.nn.Module", "torch.nn.HuberLoss", "torch.jit.script", "torch.nn.utils.rnn.pad_sequence", "torch.nn.functional.threshold_", "torch.nn.functional.multilabel_soft_margin_loss", "torch.testing._internal.common_utils.repeat_test_for_types", "torch.nn.utils.prune.identity", "torch.nn.RNNCell", "torch.no_grad", "torch.nn.Unflatten", "torch.nn.Embedding", "torch.nn.LSTM", "torch.ones", "torch.cuda.is_available", "torch.nn.RNN", "torch.testing._internal.common_utils.get_function_arglist", "torch.nn.LayerNorm", "torch.nn.functional.max_unpool3d", "torch.testing._internal.common_device_type.deviceCountAtLeast", "torch.nn.BCELoss", "numpy.sqrt", "torch.Tensor", "torch.nn.Flatten", "torch.nn.utils.parametrize.cached", "torch.nn.Dropout", "torch.constant_pad_nd", "torch.nn.functional.triplet_margin_loss", "torch.nn.functional.silu", "torch.nn.init.xavier_uniform_", "torch.nn.modules.module.register_module_backward_hook", "torch.nn.MaxPool3d", "torch.nn.LazyConvTranspose1d", "torch.nn.MultiheadAttention", "torch.nn.AdaptiveAvgPool1d", "torch.nn.utils.fusion.fuse_conv_bn_eval", "torch.tensor", "torch.nn.functional.relu", "torch.nn.init.xavier_normal_", "torch.nn.functional.max_pool1d", "torch.testing._internal.common_utils.freeze_rng_state", "torch.nn.init.normal", "torch.testing._internal.common_device_type.precisionOverride", "torch.nn.TransformerEncoderLayer", "torch.testing._internal.hypothesis_utils.tensor", "torch.nn.Linear", "numpy.testing.assert_allclose", "torch.nn.functional.unfold", "torch.nn.GRU", "torch.isnan", "torch.nn.functional.elu", "torch.set_default_dtype", "torch.nn.functional.affine_grid", "torch.nn.utils.rnn.PackedSequence", "torch.autograd.backward", "torch.nn.functional.bilinear", "torch.testing._internal.common_cuda.tf32_on_and_off", "torch.nn.Conv3d", "torch.zeros_like", "torch.random.set_rng_state", "numpy.matmul", "torch.nn.functional.l1_loss", "torch.nn.functional.hinge_embedding_loss", "torch.nn.functional.hardswish", "torch.log", "torch.nn.functional.normalize", "torch.mv", "torch.nn.MaxUnpool2d", "scipy.stats.kstest", "torch.nn.modules.utils.consume_prefix_in_state_dict_if_present", "torch.nn.grad.conv3d_input", "torch.nn.AdaptiveLogSoftmaxWithLoss", "torch.stack", "torch.nn.BatchNorm2d", "torch.nn.functional.max_unpool2d", "torch.nn.functional.elu_", "torch.randint_like", "torch.nn.PixelUnshuffle", "torch.nn.utils.prune.remove", "torch.nn.utils.prune.PruningContainer", "torch.nn.functional.gumbel_softmax", "torch.nn.utils.prune.global_unstructured", "torch.nn.Sequential", "torch.nn.functional.embedding", "torch.nn.utils.prune._compute_nparams_toprune", "numpy.squeeze", "torch.nn.functional.fold", "torch.get_default_dtype", "torch.nn.TransformerDecoderLayer", "torch.nn.utils.rnn.pack_sequence", "torch.nn.L1Loss", "torch.nn.functional.grid_sample", "torch.nn.functional.triplet_margin_with_distance_loss", "torch.finfo", "torch.testing._internal.common_utils.download_file", "torch.nn.Parameter", "torch.nn.functional.cosine_embedding_loss", "torch.jit.trace", "torch.nn.functional.pad", "torch.nn.functional.avg_pool2d", "torch.nn.AvgPool1d", "torch.nn.ConvTranspose1d", "torch.nn.functional.adaptive_avg_pool2d", "numpy.random.randint", "torch.nn.init.calculate_gain", "numpy.linalg.inv", "scipy.stats.norm.cdf", "torch.nn.TripletMarginLoss", "torch.nn.MultiMarginLoss", "torch.__future__.set_overwrite_module_params_on_conversion", "torch.nn.PixelShuffle", "torch.testing.assert_allclose", "torch.nn.EmbeddingBag.from_pretrained", "torch.testing.get_all_fp_dtypes", "torch.testing.get_all_math_dtypes", "torch.nn.functional.interpolate", "torch.nn.functional.margin_ranking_loss", "torch.randn", "numpy.random.rand", "torch.nn.init.kaiming_normal_", "torch.load", "torch.nn.BCEWithLogitsLoss", "torch.nn.grad.conv2d_input", "torch.nn.SyncBatchNorm.convert_sync_batchnorm", "torch.testing._internal.common_device_type.skipCUDAIf", "torch.nn.AvgPool2d", "torch.nn.ParameterDict", "torch.nn.functional.fractional_max_pool2d", "torch.nn.Tanh", "torch.nn.functional.multilabel_margin_loss", "torch.nn.GroupNorm", "torch.nn.functional.kl_div", "torch.nn.ReplicationPad1d", "torch.nn.TransformerEncoder", "torch.nn.utils.prune.l1_unstructured", "torch.nn.functional.adaptive_max_pool1d", "torch.fbgemm_pack_gemm_matrix_fp16", "torch.nn.parameter.UninitializedParameter", "torch.from_numpy", "torch.nn.grad.conv1d_input", "torch.nn.LazyConvTranspose2d", "torch.nn.Hardshrink", "torch.nn.utils.parametrize.remove_parametrizations", "torch.nn.Dropout2d", "torch.nn.utils.prune.L1Unstructured", "torch.sigmoid", "torch.nn.LazyLinear", "torch.nn.init.constant_", "torch.nn.functional.gelu", "torch.nn.utils.prune.ln_structured", "numpy.seterr", "torch.zeros", "torch.device", "torch.nonzero", "torch.nn.LazyConv2d", "numpy.zeros", "torch.testing._internal.common_utils.gradgradcheck", "torch.nn.functional.leaky_relu_", "torch.repeat_interleave", "torch.nn.functional.conv1d", "torch.nn.utils.parametrize.is_parametrized", "torch.nn.Dropout3d", "torch.nn.functional.channel_shuffle", "torch._VF._add_relu", "torch.cudnn_convolution_transpose", "torch.nn.InstanceNorm1d", "torch.rand", "torch.testing._internal.common_utils._assertGradAndGradgradChecks", "torch.rand_like", "torch.nn.Sigmoid", "torch.add", "torch.nn.ReplicationPad3d", "torch.nn.PReLU", "numpy.repeat", "torch.nn.AdaptiveAvgPool2d", "torch.mean", "torch.backends.cudnn.version", "torch.nn.modules.module.register_module_forward_hook", "torch.nn.functional.pairwise_distance", "torch.nn.utils.prune._validate_pruning_amount", "torch.nn.init.orthogonal_", "torch.nn.utils.prune.is_pruned", "torch.backends.mkldnn.flags", "torch.nn.LazyConv1d", "numpy.sum", "torch.nn.PairwiseDistance", "torch.nn.ELU", "torch.nn.functional.leaky_relu", "torch.nn.functional.adaptive_max_pool2d", "torch.eye", "torch.nn.utils.rnn.pack_padded_sequence", "torch.nn.functional.multi_margin_loss", "numpy.full", "torch.testing._internal.common_utils.TemporaryFileName", "torch.nn.MaxPool2d", "torch._nnpack_available", "torch.DoubleTensor", "torch.empty", "torch.nn.LSTMCell", "numpy.reshape", "torch.nn.functional.dropout", "torch.testing._internal.common_cuda.tf32_off", "torch.nn.MaxUnpool1d", "torch.testing._internal.common_cuda.tf32_on", "torch.full", "torch.nn.utils.weight_norm", "torch.nn.TransformerDecoder", "torch.relu", "torch.arange", "torch.nn.parameter.UninitializedBuffer", "torch.nn.functional.mse_loss", "torch.solve", "torch.fbgemm_linear_fp16_weight", "torch.nn.functional.conv3d", "torch.empty_like", "torch.cat", "torch.nn.LeakyReLU", "torch.nn.init.sparse_", "torch.nn.MaxPool1d", "torch.exp", "torch.nn.DataParallel", "torch.nn.ConvTranspose2d", "torch.isfinite", "torch.nn.functional.conv2d", "torch.nn.functional.binary_cross_entropy_with_logits", "torch.nn.functional.sigmoid", "torch.nn.init.eye_", "torch.nn.functional.softplus", "torch.save", "torch.cuda.device_count", "torch.nn.functional.linear", "torch.nn.Softplus", "torch.nn.functional.softmax", "torch.testing._internal.common_device_type.skipCUDAIfCudnnVersionLessThan", "torch.testing._internal.common_device_type.expectedAlertNondeterministic", "torch.nn.ReflectionPad1d", "torch.testing._internal.common_utils.run_tests", "torch.nn.Embedding.from_pretrained", "torch.nn.functional.smooth_l1_loss", "torch.einsum", "torch.nn.utils.prune.LnStructured", "torch.set_printoptions", "torch.nn.init.dirac_", "torch.sum", "torch.Size", "torch.nn.utils.prune.random_unstructured", "torch.nn.Softmax", "torch.nn.ConvTranspose3d", "torch.nn.ReLU", "torch.nn.LazyConv3d", "torch.nn.utils.spectral_norm", "torch.nn.functional.cosine_similarity", "numpy.ones", "torch.nn.utils.rnn.pad_packed_sequence", "torch.nn.EmbeddingBag", "torch.nn.functional.adaptive_avg_pool3d", "torch.random.get_rng_state", "torch.nn.utils.prune.CustomFromMask", "torch.nn.functional.cross_entropy", "torch.nn.functional.softmin", "torch.nn.CrossEntropyLoss", "torch.where", "torch.testing._internal.common_device_type.largeTensorTest", "torch.nn.Conv1d", "torch.nn.utils.clip_grad_norm_", "torch.autograd.grad", "torch.conv2d", "torch.nn.functional.threshold", "torch.nn.AdaptiveMaxPool1d", "torch.nn.init.kaiming_uniform_", "torch.nn.functional.log_softmax", "torch.nn.Conv2d", "torch.nn.functional.hardtanh", "numpy.amax", "torch.testing._internal.common_nn.CriterionTest", "torch.nn.functional.max_unpool1d", "torch.nn.Transformer", "torch.nn.functional.pdist", "torch.nn.MaxUnpool3d", "torch.nn.Fold", "torch.nn.ModuleList", "torch.nn.functional.logsigmoid", "torch.testing._internal.common_cuda.tf32_is_not_fp32", "torch.nn.functional.conv_tbc", "torch.LongTensor", "torch.allclose", "torch.nn.functional.max_pool3d", "torch.nn.utils.convert_conv2d_weight_memory_format", "torch.testing._internal.common_utils.gradcheck", "torch.nn.parallel._functions.Broadcast.apply", "torch.nn.ReflectionPad2d", "torch.nn.TripletMarginWithDistanceLoss", "torch.nn.utils.remove_spectral_norm", "torch.testing._internal.common_device_type.dtypesIfCUDA", "torch.nn.AdaptiveAvgPool3d", "torch.nn.functional.poisson_nll_loss", "numpy.isnan", "torch.nn.MultiLabelMarginLoss", "torch.nn.utils.prune._validate_pruning_amount_init", "torch.nn.BatchNorm1d", "torch.ones_like", "torch.cudnn_convolution", "torch.nn.Softshrink" ] ]
lehduong/NPTM
[ "e1b8ec333db35e0e32e360151956b0f48f102735" ]
[ "hrank/data/imagenet.py" ]
[ "import os\nimport torchvision.transforms as transforms\nimport torchvision.datasets as datasets\nfrom torch.utils.data import DataLoader\n\n\nclass Data:\n def __init__(self, args):\n pin_memory = False\n if args.gpu is not None:\n pin_memory = True\n\n scale_size = 224\n\n traindir = os.path.join(args.data_dir, 'ILSVRC2012_img_train')\n valdir = os.path.join(args.data_dir, 'val')\n normalize = transforms.Normalize(\n mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\n\n trainset = datasets.ImageFolder(\n traindir,\n transforms.Compose([\n transforms.RandomResizedCrop(224),\n transforms.RandomHorizontalFlip(),\n transforms.Resize(scale_size),\n transforms.ToTensor(),\n normalize,\n ]))\n\n self.loader_train = DataLoader(\n trainset,\n batch_size=args.train_batch_size,\n shuffle=True,\n num_workers=2,\n pin_memory=pin_memory)\n\n testset = datasets.ImageFolder(\n valdir,\n transforms.Compose([\n transforms.Resize(256),\n transforms.CenterCrop(224),\n transforms.Resize(scale_size),\n transforms.ToTensor(),\n normalize,\n ]))\n\n self.loader_test = DataLoader(\n testset,\n batch_size=args.eval_batch_size,\n shuffle=False,\n num_workers=2,\n pin_memory=True)\n" ]
[ [ "torch.utils.data.DataLoader" ] ]
bdecost/gpytorch
[ "a5f1ad3e47daf3f8db04b605fb13ff3f9f871e3a" ]
[ "test/examples/test_kissgp_gp_regression.py" ]
[ "from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nfrom math import exp, pi\n\nimport os\nimport random\nimport torch\nimport unittest\nimport gpytorch\nfrom torch import optim\nfrom torch.autograd import Variable\nfrom gpytorch.kernels import RBFKernel, GridInterpolationKernel\nfrom gpytorch.likelihoods import GaussianLikelihood\nfrom gpytorch.means import ConstantMean\nfrom gpytorch.priors import SmoothedBoxPrior\nfrom gpytorch.random_variables import GaussianRandomVariable\n\n\n# Simple training data: let's try to learn a sine function,\n# but with KISS-GP let's use 100 training examples.\ndef make_data(cuda=False):\n train_x = Variable(torch.linspace(0, 1, 100))\n train_y = Variable(torch.sin(train_x.data * (2 * pi)))\n test_x = Variable(torch.linspace(0, 1, 51))\n test_y = Variable(torch.sin(test_x.data * (2 * pi)))\n if cuda:\n train_x = train_x.cuda()\n train_y = train_y.cuda()\n test_x = test_x.cuda()\n test_y = test_y.cuda()\n return train_x, train_y, test_x, test_y\n\n\nclass GPRegressionModel(gpytorch.models.ExactGP):\n def __init__(self, train_x, train_y, likelihood):\n super(GPRegressionModel, self).__init__(train_x, train_y, likelihood)\n self.mean_module = ConstantMean(prior=SmoothedBoxPrior(-1e-5, 1e-5))\n self.base_covar_module = RBFKernel(\n log_lengthscale_prior=SmoothedBoxPrior(exp(-5), exp(6), sigma=0.1, log_transform=True)\n )\n self.covar_module = GridInterpolationKernel(self.base_covar_module, grid_size=50, grid_bounds=[(0, 1)])\n\n def forward(self, x):\n mean_x = self.mean_module(x)\n covar_x = self.covar_module(x)\n return GaussianRandomVariable(mean_x, covar_x)\n\n\nclass TestKISSGPRegression(unittest.TestCase):\n def setUp(self):\n if os.getenv(\"UNLOCK_SEED\") is None or os.getenv(\"UNLOCK_SEED\").lower() == \"false\":\n self.rng_state = torch.get_rng_state()\n torch.manual_seed(0)\n if torch.cuda.is_available():\n torch.cuda.manual_seed_all(0)\n random.seed(0)\n\n def tearDown(self):\n if hasattr(self, \"rng_state\"):\n torch.set_rng_state(self.rng_state)\n\n def test_kissgp_gp_mean_abs_error(self):\n train_x, train_y, test_x, test_y = make_data()\n likelihood = GaussianLikelihood()\n gp_model = GPRegressionModel(train_x.data, train_y.data, likelihood)\n mll = gpytorch.mlls.ExactMarginalLogLikelihood(likelihood, gp_model)\n\n # Optimize the model\n gp_model.train()\n likelihood.train()\n\n optimizer = optim.Adam(list(gp_model.parameters()) + list(likelihood.parameters()), lr=0.1)\n optimizer.n_iter = 0\n for _ in range(25):\n optimizer.zero_grad()\n output = gp_model(train_x)\n loss = -mll(output, train_y)\n loss.backward()\n optimizer.n_iter += 1\n optimizer.step()\n\n for param in gp_model.parameters():\n self.assertTrue(param.grad is not None)\n self.assertGreater(param.grad.norm().item(), 0)\n for param in likelihood.parameters():\n self.assertTrue(param.grad is not None)\n self.assertGreater(param.grad.norm().item(), 0)\n\n # Test the model\n gp_model.eval()\n likelihood.eval()\n\n test_preds = likelihood(gp_model(test_x)).mean()\n mean_abs_error = torch.mean(torch.abs(test_y - test_preds))\n\n self.assertLess(mean_abs_error.data.squeeze().item(), 0.05)\n\n def test_kissgp_gp_fast_pred_var(self):\n with gpytorch.fast_pred_var():\n train_x, train_y, test_x, test_y = make_data()\n likelihood = GaussianLikelihood()\n gp_model = GPRegressionModel(train_x.data, train_y.data, likelihood)\n mll = gpytorch.mlls.ExactMarginalLogLikelihood(likelihood, gp_model)\n\n # Optimize the model\n gp_model.train()\n likelihood.train()\n\n optimizer = optim.Adam(list(gp_model.parameters()) + list(likelihood.parameters()), lr=0.1)\n optimizer.n_iter = 0\n for _ in range(25):\n optimizer.zero_grad()\n output = gp_model(train_x)\n loss = -mll(output, train_y)\n loss.backward()\n optimizer.n_iter += 1\n optimizer.step()\n\n for param in gp_model.parameters():\n self.assertTrue(param.grad is not None)\n self.assertGreater(param.grad.norm().item(), 0)\n for param in likelihood.parameters():\n self.assertTrue(param.grad is not None)\n self.assertGreater(param.grad.norm().item(), 0)\n\n # Test the model\n gp_model.eval()\n likelihood.eval()\n # Set the cache\n test_function_predictions = likelihood(gp_model(train_x))\n\n # Now bump up the likelihood to something huge\n # This will make it easy to calculate the variance\n likelihood.log_noise.data.fill_(3)\n test_function_predictions = likelihood(gp_model(train_x))\n\n noise = likelihood.log_noise.exp()\n var_diff = (test_function_predictions.var() - noise).abs()\n self.assertLess(torch.max(var_diff.data / noise.data), 0.05)\n\n def test_kissgp_gp_mean_abs_error_cuda(self):\n if torch.cuda.is_available():\n train_x, train_y, test_x, test_y = make_data(cuda=True)\n likelihood = GaussianLikelihood().cuda()\n gp_model = GPRegressionModel(train_x.data, train_y.data, likelihood).cuda()\n mll = gpytorch.mlls.ExactMarginalLogLikelihood(likelihood, gp_model)\n\n # Optimize the model\n gp_model.train()\n likelihood.train()\n\n optimizer = optim.Adam(list(gp_model.parameters()) + list(likelihood.parameters()), lr=0.1)\n optimizer.n_iter = 0\n for _ in range(25):\n optimizer.zero_grad()\n output = gp_model(train_x)\n loss = -mll(output, train_y)\n loss.backward()\n optimizer.n_iter += 1\n optimizer.step()\n\n for param in gp_model.parameters():\n self.assertTrue(param.grad is not None)\n self.assertGreater(param.grad.norm().item(), 0)\n for param in likelihood.parameters():\n self.assertTrue(param.grad is not None)\n self.assertGreater(param.grad.norm().item(), 0)\n\n # Test the model\n gp_model.eval()\n likelihood.eval()\n test_preds = likelihood(gp_model(test_x)).mean()\n mean_abs_error = torch.mean(torch.abs(test_y - test_preds))\n\n self.assertLess(mean_abs_error.data.squeeze().item(), 0.02)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n" ]
[ [ "torch.cuda.manual_seed_all", "torch.get_rng_state", "torch.sin", "torch.max", "torch.linspace", "torch.manual_seed", "torch.abs", "torch.cuda.is_available", "torch.set_rng_state" ] ]
maartenelgar/Block_Fund_Trading
[ "0ced0f4ac5bb8785ca1b75e55dee7df1db5030a8" ]
[ "build/lib/Scripts/RoibalBot.py" ]
[ "\r\nfrom binance.client import Client\r\nimport time\r\nimport matplotlib\r\nfrom matplotlib import cm\r\nimport matplotlib.pyplot as plt\r\nfrom binance.enums import *\r\nimport save_historical_data_Roibal\r\nfrom BinanceKeys import BinanceKey1\r\n\r\n\r\napi_key = BinanceKey1['OfBLqIoRvQCloLCSc5lmrN5ikapHhDul27yn6TrsM5X7l0dkw64ME0ESkEkBatNL']\r\napi_secret = BinanceKey1['9Jwb6sR6z8N4jWlK9n0bZrHAeipA8FaYibl5VFnBoE0t3CmnY1CyVWKCekOmpg2r']\r\n\r\nclient = Client(api_key, api_secret)\r\n\r\n# get a deposit address for BTC\r\naddress = client.get_deposit_address(asset='BTC')\r\n\r\ndef run():\r\n # get system status\r\n #Create List of Crypto Pairs to Watch\r\n list_of_symbols = ['BTCUSDT', 'ETHUSDT', 'BNBUSDT','BNBBTC', 'ETHBTC', 'LTCBTC']\r\n micro_cap_coins = ['ICXBNB', 'BRDBNB', 'NAVBNB', 'RCNBNB']\r\n\r\n #Get Status of Exchange & Account\r\n try:\r\n status = client.get_system_status()\r\n print(\"\\nExchange Status: \", status)\r\n\r\n #Account Withdrawal History Info\r\n withdraws = client.get_withdraw_history()\r\n print(\"\\nClient Withdraw History: \", withdraws)\r\n\r\n #get Exchange Info\r\n info = client.get_exchange_info()\r\n print(\"\\nExchange Info (Limits): \", info)\r\n except():\r\n pass\r\n\r\n # place a test market buy order, to place an actual order use the create_order function\r\n # if '1000 ms ahead of server time' error encountered, visit https://github.com/sammchardy/python-binance/issues/249\r\n try:\r\n order = client.create_test_order(\r\n symbol='BNBBTC',\r\n side=Client.SIDE_BUY,\r\n type=Client.ORDER_TYPE_MARKET,\r\n quantity=100)\r\n except:\r\n print(\"\\n \\n \\nATTENTION: NON-VALID CONNECTION WITH BINANCE \\n \\n \\n\")\r\n\r\n #Get Info about Coins in Watch List\r\n coin_prices(list_of_symbols)\r\n coin_tickers(list_of_symbols)\r\n #for symbol in list_of_symbols:\r\n # market_depth(symbol)\r\n\r\n #for coin in micro_cap_coins:\r\n # visualize_market_depth(1, 1, coin)\r\n for coin in micro_cap_coins:\r\n scalping_orders(coin, 1, 1)\r\n\r\n #get recent trades\r\n trades = client.get_recent_trades(symbol='BNBBTC')\r\n print(\"\\nRecent Trades: \", trades)\r\n print(\"Local Time: \", time.localtime())\r\n print(\"Recent Trades Time: \", convert_time_binance(trades[0]['time']))\r\n\r\n #get historical trades\r\n try:\r\n hist_trades = client.get_historical_trades(symbol='BNBBTC')\r\n print(\"\\nHistorical Trades: \", hist_trades)\r\n except:\r\n print('\\n \\n \\nATTENTION: NON VALID CONNECTION WITH BINANCE \\n \\n \\n')\r\n\r\n #get aggregate trades\r\n agg_trades = client.get_aggregate_trades(symbol='BNBBTC')\r\n print(\"\\nAggregate Trades: \", agg_trades)\r\n\r\n\r\ndef convert_time_binance(gt):\r\n #Converts from Binance Time Format (milliseconds) to time-struct\r\n #From Binance-Trader Comment Section Code\r\n #gt = client.get_server_time()\r\n print(\"Binance Time: \", gt)\r\n print(time.localtime())\r\n aa = str(gt)\r\n bb = aa.replace(\"{'serverTime': \",\"\")\r\n aa = bb.replace(\"}\",\"\")\r\n gg=int(aa)\r\n ff=gg-10799260\r\n uu=ff/1000\r\n yy=int(uu)\r\n tt=time.localtime(yy)\r\n #print(tt)\r\n return tt\r\n\r\n\r\ndef market_depth(sym, num_entries=20):\r\n #Get market depth\r\n #Retrieve and format market depth (order book) including time-stamp\r\n i=0 #Used as a counter for number of entries\r\n print(\"Order Book: \", convert_time_binance(client.get_server_time()))\r\n depth = client.get_order_book(symbol=sym)\r\n print(depth)\r\n print(depth['asks'][0])\r\n ask_tot=0.0\r\n ask_price =[]\r\n ask_quantity = []\r\n bid_price = []\r\n bid_quantity = []\r\n bid_tot = 0.0\r\n place_order_ask_price = 0\r\n place_order_bid_price = 0\r\n max_order_ask = 0\r\n max_order_bid = 0\r\n print(\"\\n\", sym, \"\\nDepth ASKS:\\n\")\r\n print(\"Price Amount\")\r\n for ask in depth['asks']:\r\n if i<num_entries:\r\n if float(ask[1])>float(max_order_ask):\r\n #Determine Price to place ask order based on highest volume\r\n max_order_ask=ask[1]\r\n place_order_ask_price=round(float(ask[0]),5)-0.0001\r\n #ask_list.append([ask[0], ask[1]])\r\n ask_price.append(float(ask[0]))\r\n ask_tot+=float(ask[1])\r\n ask_quantity.append(ask_tot)\r\n #print(ask)\r\n i+=1\r\n j=0 #Secondary Counter for Bids\r\n print(\"\\n\", sym, \"\\nDepth BIDS:\\n\")\r\n print(\"Price Amount\")\r\n for bid in depth['bids']:\r\n if j<num_entries:\r\n if float(bid[1])>float(max_order_bid):\r\n #Determine Price to place ask order based on highest volume\r\n max_order_bid=bid[1]\r\n place_order_bid_price=round(float(bid[0]),5)+0.0001\r\n bid_price.append(float(bid[0]))\r\n bid_tot += float(bid[1])\r\n bid_quantity.append(bid_tot)\r\n #print(bid)\r\n j+=1\r\n return ask_price, ask_quantity, bid_price, bid_quantity, place_order_ask_price, place_order_bid_price\r\n #Plot Data\r\n\r\ndef scalping_orders(coin, wait=1, tot_time=1):\r\n #Function for placing 'scalp orders'\r\n #Calls on Visualizing Scalping Orders Function\r\n ap, aq, bp, bq, place_ask_order, place_bid_order, spread, proj_spread, max_bid, min_ask = visualize_market_depth(wait, tot_time, coin)\r\n print(\"Coin: {}\\nPrice to Place Ask Order: {}\\nPrice to place Bid Order: {}\".format(coin, place_ask_order, place_bid_order))\r\n print(\"Spread: {} % Projected Spread {} %\".format(spread, proj_spread))\r\n print(\"Max Bid: {} Min Ask: {}\".format(max_bid, min_ask))\r\n #Place Orders based on calculated bid-ask orders if projected > 0.05% (transaction fee)\r\n #Documentation: http://python-binance.readthedocs.io/en/latest/account.html#orders\r\n \"\"\"\r\n if proj_spread > 0.05:\r\n quant1=100 #Determine Code Required to calculate 'minimum' quantity\r\n #Place Bid Order:\r\n bid_order1 = client.order_limit_buy(\r\n symbol=coin,\r\n quantity=quant1,\r\n price=place_bid_order)\r\n #Place Ask Order\r\n ask_order1 = client.order_limit_sell(\r\n symbol=coin,\r\n quantity=quant1,\r\n price=place_ask_order)\r\n\r\n\r\n #Place second order if current spread > 0.05% (transaction fee)\r\n\r\n \"\"\"\r\n\r\n\r\ndef visualize_market_depth(wait_time_sec='1', tot_time='1', sym='ICXBNB', precision=5):\r\n cycles = int(tot_time)/int(wait_time_sec)\r\n start_time = time.asctime()\r\n fig, ax = plt.subplots()\r\n for i in range(1,int(cycles)+1):\r\n ask_pri, ask_quan, bid_pri, bid_quan, ask_order, bid_order = market_depth(sym)\r\n\r\n #print(ask_price)\r\n plt.plot(ask_pri, ask_quan, color = 'red', label='asks-cycle: {}'.format(i))\r\n plt.plot(bid_pri, bid_quan, color = 'blue', label = 'bids-cycle: {}'.format(i))\r\n\r\n #ax.plot(depth['bids'][0], depth['bids'][1])\r\n max_bid = max(bid_pri)\r\n min_ask = min(ask_pri)\r\n max_quant = max(ask_quan[-1], bid_quan[-1])\r\n spread = round(((min_ask-max_bid)/min_ask)*100,5) #Spread based on market\r\n proj_order_spread = round(((ask_order-bid_order)/ask_order)*100, precision)\r\n price=round(((max_bid+min_ask)/2), precision)\r\n plt.plot([price, price],[0, max_quant], color = 'green', label = 'Price - Cycle: {}'.format(i)) #Vertical Line for Price\r\n plt.plot([ask_order, ask_order],[0, max_quant], color = 'black', label = 'Ask - Cycle: {}'.format(i))\r\n plt.plot([bid_order, bid_order],[0, max_quant], color = 'black', label = 'Buy - Cycle: {}'.format(i))\r\n #plt.plot([min_ask, min_ask],[0, max_quant], color = 'grey', label = 'Min Ask - Cycle: {}'.format(i))\r\n #plt.plot([max_bid, max_bid],[0, max_quant], color = 'grey', label = 'Max Buy - Cycle: {}'.format(i))\r\n ax.annotate(\"Max Bid: {} \\nMin Ask: {}\\nSpread: {} %\\nCycle: {}\\nPrice: {}\"\r\n \"\\nPlace Bid: {} \\nPlace Ask: {}\\n Projected Spread: {} %\".format(max_bid, min_ask, spread, i, price, bid_order, ask_order, proj_order_spread),\r\n xy=(max_bid, ask_quan[-1]), xytext=(max_bid, ask_quan[0]))\r\n if i==(cycles+1):\r\n break\r\n else:\r\n time.sleep(int(wait_time_sec))\r\n #end_time = time.asctime()\r\n ax.set(xlabel='Price', ylabel='Quantity',\r\n title='Binance Order Book: {} \\n {}\\n Cycle Time: {} seconds - Num Cycles: {}'.format(sym, start_time, wait_time_sec, cycles))\r\n plt.legend()\r\n plt.show()\r\n return ask_pri, ask_quan, bid_pri, bid_quan, ask_order, bid_order, spread, proj_order_spread, max_bid, min_ask\r\n\r\n\r\ndef coin_prices(watch_list):\r\n #Will print to screen, prices of coins on 'watch list'\r\n #returns all prices\r\n prices = client.get_all_tickers()\r\n print(\"\\nSelected (watch list) Ticker Prices: \")\r\n for price in prices:\r\n if price['symbol'] in watch_list:\r\n print(price)\r\n return prices\r\n\r\n\r\ndef coin_tickers(watch_list):\r\n # Prints to screen tickers for 'watch list' coins\r\n # Returns list of all price tickers\r\n tickers = client.get_orderbook_tickers()\r\n print(\"\\nWatch List Order Tickers: \\n\")\r\n for tick in tickers:\r\n if tick['symbol'] in watch_list:\r\n print(tick)\r\n return tickers\r\n\r\ndef portfolio_management(deposit = '10000', withdraw=0, portfolio_amt = '0', portfolio_type='USDT', test_acct='True'):\r\n \"\"\"The Portfolio Management Function will be used to track profit/loss of Portfolio in Any Particular Currency (Default: USDT)\"\"\"\r\n #Maintain Portfolio Statistics (Total Profit/Loss) in a file\r\n pass\r\n\r\ndef Bollinger_Bands():\r\n #This Function will calculate Bollinger Bands for Given Time Period\r\n #EDIT: Will use Crypto-Signal for this functionality\r\n #https://github.com/CryptoSignal/crypto-signal\r\n pass\r\n\r\ndef buy_sell_bot():\r\n pass\r\n\r\ndef position_sizing():\r\n pass\r\n\r\ndef trailing_stop_loss():\r\n pass\r\n\r\n\r\n#Place Limit Order\r\n\"\"\"\r\norder = client.order_limit_buy(\r\n symbol='BNBBTC',\r\n quantity=100,\r\n price='0.00001')\r\n\r\norder = client.order_limit_sell(\r\n symbol='BNBBTC',\r\n quantity=100,\r\n price='0.00001')\r\n\"\"\"\r\n\r\n\r\n\r\n\r\n\"\"\"\r\n#trade aggregator (generator)\r\nagg_trades = client.aggregate_trade_iter(symbol='ETHBTC', start_str='30 minutes ago UTC')\r\n# iterate over the trade iterator\r\nfor trade in agg_trades:\r\n pass\r\n #print(trade)\r\n # do something with the trade data\r\n\r\n# convert the iterator to a list\r\n# note: generators can only be iterated over once so we need to call it again\r\nagg_trades = client.aggregate_trade_iter(symbol='ETHBTC', start_str='30 minutes ago UTC')\r\nagg_trade_list = list(agg_trades)\r\n\r\n# fetch 30 minute klines for the last month of 2017\r\nklines = client.get_historical_klines(\"ETHBTC\", Client.KLINE_INTERVAL_30MINUTE, \"1 Dec, 2017\", \"1 Jan, 2018\")\r\n#for kline in klines:\r\n #print(kline)\r\n\"\"\"\r\n\r\n#place an order on Binance\r\n\"\"\"\r\norder = client.create_order(\r\n symbol='BNBBTC',\r\n side=SIDE_BUY,\r\n type=ORDER_TYPE_LIMIT,\r\n timeInForce=TIME_IN_FORCE_GTC,\r\n quantity=100,\r\n price='0.00001')\r\n\"\"\"\r\n\r\nif __name__ == \"__main__\":\r\n visualize_market_depth()\r\n" ]
[ [ "matplotlib.pyplot.show", "matplotlib.pyplot.legend", "matplotlib.pyplot.subplots" ] ]
jessica-lei/coronavirus-2020
[ "d51d73dd8d021bb51b78f653a87d478298794534" ]
[ "exp/polynomial_regression.py" ]
[ "import numpy as np\ntry:\n import matplotlib.pyplot as plt\nexcept:\n import matplotlib\n matplotlib.use('Agg')\n import matplotlib.pyplot as plt\n\nclass PolynomialRegression():\n def __init__(self, degree):\n \"\"\"\n Implement polynomial regression from scratch.\n \n This class takes as input \"degree\", which is the degree of the polynomial \n used to fit the data. For example, degree = 2 would fit a polynomial of the \n form:\n\n ax^2 + bx + c\n \n Your code will be tested by comparing it with implementations inside sklearn.\n DO NOT USE THESE IMPLEMENTATIONS DIRECTLY IN YOUR CODE. You may find the \n following documentation useful:\n\n https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.PolynomialFeatures.html\n https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LinearRegression.html\n\n Here are helpful slides:\n\n http://interactiveaudiolab.github.io/teaching/eecs349stuff/eecs349_linear_regression.pdf\n \n The internal representation of this class is up to you. Read each function\n documentation carefully to make sure the input and output matches so you can\n pass the test cases. However, do not use the functions numpy.polyfit or numpy.polval. \n You should implement the closed form solution of least squares as detailed in slide 10\n of the lecture slides linked above.\n\n Usage:\n import numpy as np\n \n x = np.random.random(100)\n y = np.random.random(100)\n learner = PolynomialRegression(degree = 1)\n learner.fit(x, y) # this should be pretty much a flat line\n predicted = learner.predict(x)\n\n new_data = np.random.random(100) + 10\n predicted = learner.predict(new_data)\n\n # confidence compares the given data with the training data\n confidence = learner.confidence(new_data)\n\n\n Args:\n degree (int): Degree of polynomial used to fit the data.\n \"\"\"\n self.features = []\n self.targets = []\n self.degree = degree\n self.coefficients = []\n\n \n def fit(self, features, targets):\n \"\"\"\n Fit the given data using a polynomial. The degree is given by self.degree,\n which is set in the __init__ function of this class. The goal of this\n function is fit features, a 1D numpy array, to targets, another 1D\n numpy array.\n \n\n Args:\n features (np.ndarray): 1D array containing real-valued inputs.\n targets (np.ndarray): 1D array containing real-valued targets.\n Returns:\n None (saves model and training data internally)\n \"\"\"\n self.targets = targets\n x_arr = []\n for feature in range(features.size):\n powers = np.arange(0, self.degree+1)\n x_powers = np.power(np.full(self.degree+1, features[feature]), powers)\n x_arr.append(x_powers)\n x_arr = np.array(x_arr)\n self.features = x_arr\n x_transpose = np.transpose(x_arr)\n first = np.linalg.inv(np.matmul(x_transpose, x_arr))\n sec = np.matmul(x_transpose, targets)\n self.coefficients = np.matmul(first, sec)\n\n def predict(self, features):\n \"\"\"\n Given features, a 1D numpy array, use the trained model to predict target \n estimates. Call this after calling fit.\n\n Args:\n features (np.ndarray): 1D array containing real-valued inputs.\n Returns:\n predictions (np.ndarray): Output of saved model on features.\n \"\"\"\n x_arr = []\n for feature in range(features.size):\n powers = np.arange(0, self.degree+1)\n x_powers = np.power(np.full(self.degree+1, features[feature]), powers)\n x_arr.append(x_powers)\n x_arr = np.array(x_arr)\n predictions = np.matmul(x_arr, self.coefficients)\n return predictions\n\n def visualize(self, features, targets):\n \"\"\"\n This function should produce a single plot containing a scatter plot of the\n features and the targets, and the polynomial fit by the model should be\n graphed on top of the points.\n\n DO NOT USE plt.show() IN THIS FUNCTION. Instead, use plt.savefig().\n\n Args:\n features (np.ndarray): 1D array containing real-valued inputs.\n targets (np.ndarray): 1D array containing real-valued targets.\n Returns:\n None (plots to the active figure)\n \"\"\"\n x = features\n y = self.predict(features)\n plt.title('Polynomial Regression')\n plt.plot(x, y)\n plt.savefig('Polynomial Regression')\n\n" ]
[ [ "matplotlib.use", "numpy.full", "numpy.array", "numpy.matmul", "matplotlib.pyplot.savefig", "matplotlib.pyplot.title", "matplotlib.pyplot.plot", "numpy.transpose", "numpy.arange" ] ]
mrsono0/pnu-ingro
[ "a5d1f917ed0c6fb13e4bf4986f0768e224ae6b7a" ]
[ "supplementary_lessons/A_Group/jjioii25/Gevolution/run_inclue_batch.py" ]
[ "import requests\nimport xmltodict\nfrom urllib.request import urlopen\nimport pandas as pd\nimport numpy as np\nimport pymysql as my\nfrom random import choice\nimport sys\n\nconn = None\n# 데이터베이스 연결\ndef openDB():\n conn = my.connect(\n host = '127.0.0.1',\n user = 'root',\n password = '12341234',\n db = 'pythondb',\n charset = 'utf8',\n cursorclass=my.cursors.DictCursor\n )\n return conn\n\n# 데이터베이스 해제\ndef closeDB():\n if conn:conn.close()\n\n\n# # 웹크롤링관련 메뉴 선택하는 함수\n# def crawlMenuShow():\n# i = True\n# while i:\n# choice=input('''\n# 웹크롤링 프로그램입니다.\n# 수집하고자하는 데이터를 선택해주세요 :\n# G - 구글플레이\n# A - 애플앱스토어\n# Q - 프로그램 종료\n# ''')\n \n# if choice == 'Q':\n# print('웹크롤링 프로그램을 종료합니다.')\n# i = crawlMenuChoice(choice)\n# else:\n# crawlMenuChoice(choice)\n\n\n# 웹크롤링관련 메뉴 선택하는 함수\n# 배치버전일때 choice와 flag를 입력받는다.\ndef crawlMenuChoice(*choice):\n if not choice:\n choice=input('''\n 웹크롤링 프로그램입니다.\n 수집하고자하는 데이터를 선택해주세요 :\n G - 구글플레이\n A - 애플앱스토어\n Q - 프로그램 종료\n ''')\n return choice\n\n\n# 콘솔버전일때 실행하는 함수\ndef consoleStage():\n choice = crawlMenuChoice()\n if choice == 'Q':\n print('웹크롤링 프로그램을 종료합니다.')\n sys.exit()\n else:\n getWebdata(choice)\n\n# # 배치버전일때 실행하는 함수\ndef batchStage(choice, state):\n getWebdata(choice, state)\n pass\n\n\n# Gevolution 사이트 연동하여 필요한 데이터 크롤링하는 함수\ndef getWebdata(choice, *state):\n print('웹 크롤링을 시작합니다.')\n # 발급된 계정의 인증키\n GEVOLUTION_API_KEY = 'MNOP826189'\n # g:구글플레이, a:애플 앱스토어\n market = choice[0].lower()\n # game:게임, app:일반앱, all:전체(게임+일반앱)\n app_type = 'game'\n # 1:무료, 2:유료,3:매출,4:신규무료,5:신규유료\n rank_type = 1\n # 1~OO위까지 출력 (max:100)\n rank = 100\n url = 'http://api.gevolution.co.kr/rank/xml/?aCode={code}&market={market}&appType={app_type}&rankType={rank_type}&rank={rank}'.format(code=GEVOLUTION_API_KEY, market=market, app_type=app_type, rank_type=rank_type, rank=rank)\n fp = urlopen(url)\n doc = xmltodict.parse( fp.read() )\n print('웹 크롤링이 완료되었습니다.')\n fp.close()\n \n game_df = makeDataFrame(doc, rank)\n if state:\n checkData(game_df, state)\n else:\n state = checkData(game_df) \n nextStage(state, game_df)\n\n\n\n# 크롤링한 데이터로 데이터프레임 생성하는 함수\ndef makeDataFrame( doc, rank ):\n aid = [ doc['response']['items']['item'][d]['aid'] for d in range(rank) ]\n ranking = [ doc['response']['items']['item'][d]['ranking'] for d in range(rank) ]\n lastWeek = [ doc['response']['items']['item'][d]['lastWeek'] for d in range(rank) ]\n rating = [ doc['response']['items']['item'][d]['rating'] for d in range(rank) ]\n gameName = [ doc['response']['items']['item'][d]['gameName'] for d in range(rank) ]\n publisher = [ doc['response']['items']['item'][d]['publisher'] for d in range(rank) ]\n game_dict = { 'aid':aid, 'ranking':ranking, 'lastWeek':lastWeek, 'rating':rating, \n 'gameName':gameName, 'publisher':publisher }\n\n game_df = pd.DataFrame(game_dict)\n return game_df\n\n# 크롤링한 데이터가 사용자가 원하는 데이터가 맞는지 개수를 확인하는 함수\ndef checkData(game_df, *state):\n print('데이터의 개수가 맞는지 확인합니다.')\n if len(game_df) == 100: \n print('게임랭킹데이터가 100개 수집되었습니다.')\n if state:\n # print('크롤링후state',state)\n return state\n else: \n state='ok'\n return state\n else:\n print('게임랭킹데이터의 개수가 100개가 아닙니다.')\n state = 'restart'\n return state\n\n\n# 크롤링 후 다음 단계를 실행하는 함수\ndef nextStage(state, game_df):\n # print(state[0])\n if state == 'ok':\n choice2 = str(input('다음 단계를 실행하려면 yes를 입력해주세요.'))\n if choice2 == 'yes':\n print('DB에 수집한 데이터를 적재합니다.')\n uploadDB(game_df)\n # sys.exit(1)\n else:\n print('처음으로 돌아갑니다.')\n consoleStage()\n elif state == 'restart':\n print('프로그램을 다시 시작합니다.')\n consoleStage()\n elif state[0] == 'batch':\n print('DB에 수집한 데이터를 적재합니다.')\n uploadDB(game_df)\n # sys.exit(1)\n \n\n\n# insert sql문 실행하는 함수\ndef insertData( game_df, i ):# aid,ranking,lastWeek,rating,gameName,publisher ):\n conn = openDB()\n with conn.cursor() as cursor:\n sql = 'insert into tbl_game (aid,ranking,lastWeek,rating,gameName,publisher) values(%s, %s, %s, %s, %s, %s);'\n cursor.execute( sql, (game_df['aid'][i],game_df['ranking'][i],\n game_df['lastWeek'][i],game_df['rating'][i],game_df['gameName'][i],game_df['publisher'][i]) )\n # 디비 반영\n conn.commit()\n # 영향받은 row의 수\n return conn.affected_rows()\n\n# DB에 데이터를 적재하는 함수\ndef uploadDB(game_df):\n for i in range(len(game_df)):\n insertData(game_df, i)\n closeDB()\n print('게임랭킹데이터를 DB에 적재완료했습니다.')\n\n\n######################### DB관련 업무 - 추후에 추가하는방안 생각해보기\n\n#사용자에게 검색하고자 하는 제작사를 입력받는 함수\ndef inputPublisher():\n publisher = input('검색하고자하는 제작사를 입력해주세요.')\n return publisher\n\n# 사용자에게 입력받은 제작사로 select문 실행하는 함수 \ndef selectData( publisher ):\n conn = openDB()\n rows=None\n with conn.cursor() as cursor:\n sql = \"select * from tbl_game where publisher=%s;\" \n cursor.execute( sql, (str(publisher)))\n rows = cursor.fetchall()\n closeDB()\n return rows\n\n\n# select문 실행한 결과를 보여주는 함수\ndef viewData( ):\n publisher = inputPublisher()\n rows = selectData( publisher )\n print(rows)\n\n\n# 배치함수\ndef batchRun():\n print('구글플레이스토어 게임랭킹 100개를 적재합니다.')\n batchStage('G', 'batch')\n print('애플앱스토어 게임랭킹 100개를 적재합니다.')\n batchStage('A', 'batch')\n\n\n# 콘솔버전 실행\n#consoleStage()\n\n# 배치버전 실행\nbatchStage('G', 'batch')\n\nif __name__ == '__main__':\n print('배치함수실행')\n batchRun()\n" ]
[ [ "pandas.DataFrame" ] ]
LVParkinson/bird_species_classification
[ "3c5d7dc8bcb426ba6b1457239702b27bb28880b4" ]
[ "mask_rcnn/test_images.py" ]
[ "import sys\nimport random\nimport math\nimport cv2\nimport os\nfrom matplotlib import pyplot as plt\nimport numpy as np\nfrom keras.layers import Conv2D, MaxPooling2D\nfrom keras.optimizers import Adam\nfrom keras.layers import (\n Dense,\n Activation,\n Dropout,\n Flatten,\n Input,\n AveragePooling2D,\n BatchNormalization,\n)\nfrom keras.models import Model\nfrom keras.utils import plot_model, np_utils\nfrom keras.callbacks import (\n ModelCheckpoint,\n EarlyStopping,\n TensorBoard,\n LearningRateScheduler,\n)\nfrom time import time\nfrom keras.applications.inception_v3 import InceptionV3\nfrom keras.applications.inception_resnet_v2 import InceptionResNetV2\nfrom keras import backend as K\nfrom os.path import isfile, join\nfrom os import rename, listdir, rename, makedirs\nfrom sklearn.model_selection import train_test_split, StratifiedKFold\nfrom keras.utils.generic_utils import get_custom_objects\nfrom keras.regularizers import l2\n\n\nBATCH_SIZE = 32\nVALIDATION_SPLIT = 0.1\nN_CLASSES = 16\nEPOCHS = 7\n\n# Root directory of the project\nROOT_DIR = os.path.abspath(\"./\")\n\nspecies = [\n \"blasti\",\n \"bonegl\",\n \"brhkyt\",\n \"cbrtsh\",\n \"cmnmyn\",\n \"gretit\",\n \"hilpig\",\n \"himbul\",\n \"himgri\",\n \"hsparo\",\n \"indvul\",\n \"jglowl\",\n \"lbicrw\",\n \"mgprob\",\n \"rebimg\",\n \"wcrsrt\",\n]\nspecies_check = [\"hsparo\"]\n# Import Mask RCNN\nsys.path.append(ROOT_DIR) # To find local version of the library\nfrom mrcnn import utils\nimport mrcnn.model as modellib\nfrom mrcnn import visualize\n\n# Import COCO config\nsys.path.append(os.path.join(ROOT_DIR, \"coco/\")) # To find local version\nimport coco\n\n# %matplotlib inline\n\n# Directory to save logs and trained model\nMODEL_DIR = os.path.join(ROOT_DIR, \"logs\")\n\n# Local path to trained weights file\nCOCO_MODEL_PATH = os.path.join(ROOT_DIR, \"mask_rcnn_coco.h5\")\nif not os.path.exists(COCO_MODEL_PATH):\n utils.download_trained_weights(COCO_MODEL_PATH)\n\n\nclass InferenceConfig(coco.CocoConfig):\n # Set batch size to 1 since we'll be running inference on\n # one image at a time. Batch size = GPU_COUNT * IMAGES_PER_GPU\n GPU_COUNT = 1\n IMAGES_PER_GPU = 1\n\n\nconfig = InferenceConfig()\nconfig.display()\n\n\n# Create model object in inference mode.# Creat\nmodel_coco = modellib.MaskRCNN(mode=\"inference\", model_dir=MODEL_DIR, config=config)\n\n# Load weights trained on MS-COCO\nmodel_coco.load_weights(COCO_MODEL_PATH, by_name=True)\n\n\n# COCO Class names\n# Index of the class in the list is its ID. For example, to get ID of\n# the teddy bear class, use: class_names.index('teddy bear')\nclass_names = [\n \"BG\",\n \"person\",\n \"bicycle\",\n \"car\",\n \"motorcycle\",\n \"airplane\",\n \"bus\",\n \"train\",\n \"truck\",\n \"boat\",\n \"traffic light\",\n \"fire hydrant\",\n \"stop sign\",\n \"parking meter\",\n \"bench\",\n \"bird\",\n \"cat\",\n \"dog\",\n \"horse\",\n \"sheep\",\n \"cow\",\n \"elephant\",\n \"bear\",\n \"zebra\",\n \"giraffe\",\n \"backpack\",\n \"umbrella\",\n \"handbag\",\n \"tie\",\n \"suitcase\",\n \"frisbee\",\n \"skis\",\n \"snowboard\",\n \"sports ball\",\n \"kite\",\n \"baseball bat\",\n \"baseball glove\",\n \"skateboard\",\n \"surfboard\",\n \"tennis racket\",\n \"bottle\",\n \"wine glass\",\n \"cup\",\n \"fork\",\n \"knife\",\n \"spoon\",\n \"bowl\",\n \"banana\",\n \"apple\",\n \"sandwich\",\n \"orange\",\n \"broccoli\",\n \"carrot\",\n \"hot dog\",\n \"pizza\",\n \"donut\",\n \"cake\",\n \"chair\",\n \"couch\",\n \"potted plant\",\n \"bed\",\n \"dining table\",\n \"toilet\",\n \"tv\",\n \"laptop\",\n \"mouse\",\n \"remote\",\n \"keyboard\",\n \"cell phone\",\n \"microwave\",\n \"oven\",\n \"toaster\",\n \"sink\",\n \"refrigerator\",\n \"book\",\n \"clock\",\n \"vase\",\n \"scissors\",\n \"teddy bear\",\n \"hair drier\",\n \"toothbrush\",\n]\n\n\ndef swish(x):\n return K.sigmoid(x) * x\n\n\nget_custom_objects().update({\"swish\": Activation(swish)})\n\n\ndef build_inceptionV3(\n img_shape=(416, 416, 3),\n n_classes=16,\n l2_reg=0.0,\n load_pretrained=True,\n freeze_layers_from=\"base_model\",\n):\n # Decide if load pretrained weights from imagenet\n if load_pretrained:\n weights = \"imagenet\"\n else:\n weights = None\n\n # Get base model\n base_model = InceptionV3(\n include_top=False, weights=weights, input_tensor=None, input_shape=img_shape\n )\n\n # Add final layers\n x = base_model.output\n x = AveragePooling2D((8, 8), strides=(8, 8), name=\"avg_pool\")(x)\n x = Flatten(name=\"flatten\")(x)\n x = Dense(512, activation=\"swish\", name=\"dense_1\", kernel_initializer=\"he_uniform\")(\n x\n )\n x = Dropout(0.25)(x)\n predictions = Dense(\n n_classes,\n activation=\"softmax\",\n name=\"predictions\",\n kernel_initializer=\"he_uniform\",\n )(x)\n\n # This is the model we will train\n model = Model(inputs=base_model.input, outputs=predictions)\n\n # Freeze some layers\n if freeze_layers_from is not None:\n if freeze_layers_from == \"base_model\":\n print(\" Freezing base model layers\")\n for layer in base_model.layers:\n layer.trainable = False\n else:\n for i, layer in enumerate(model.layers):\n print(i, layer.name)\n print(\" Freezing from layer 0 to \" + str(freeze_layers_from))\n for layer in model.layers[:freeze_layers_from]:\n layer.trainable = False\n for layer in model.layers[freeze_layers_from:]:\n layer.trainable = True\n\n return model\n\n\nmodel_cropped_inception_v3 = build_inceptionV3()\nmodel_cropped_inception_v3.load_weights(\"../inception_v3_crops.h5\")\nmodel_final_inception_v3 = build_inceptionV3()\nmodel_final_inception_v3.load_weights(\"../inception_v3_crops+images.h5\")\n\n\ndef build_inception_resnet_V2(\n img_shape=(416, 416, 3),\n n_classes=16,\n l2_reg=0.0,\n load_pretrained=True,\n freeze_layers_from=\"base_model\",\n):\n # Decide if load pretrained weights from imagenet\n if load_pretrained:\n weights = \"imagenet\"\n else:\n weights = None\n\n # Get base model\n base_model = InceptionResNetV2(\n include_top=False, weights=weights, input_tensor=None, input_shape=img_shape\n )\n\n # Add final layers\n x = base_model.output\n x = AveragePooling2D((8, 8), strides=(8, 8), name=\"avg_pool\")(x)\n x = Flatten(name=\"flatten\")(x)\n x = Dense(512, activation=\"swish\", name=\"dense_1\", kernel_initializer=\"he_uniform\")(\n x\n )\n x = Dropout(0.25)(x)\n predictions = Dense(\n n_classes,\n activation=\"softmax\",\n name=\"predictions\",\n kernel_initializer=\"he_uniform\",\n )(x)\n\n # This is the model we will train\n model = Model(inputs=base_model.input, outputs=predictions)\n\n # Freeze some layers\n if freeze_layers_from is not None:\n if freeze_layers_from == \"base_model\":\n print(\" Freezing base model layers\")\n for layer in base_model.layers:\n layer.trainable = False\n else:\n for i, layer in enumerate(model.layers):\n print(i, layer.name)\n print(\" Freezing from layer 0 to \" + str(freeze_layers_from))\n for layer in model.layers[:freeze_layers_from]:\n layer.trainable = False\n for layer in model.layers[freeze_layers_from:]:\n layer.trainable = True\n\n return model\n\n\nmodel_inception_resnet_v2 = build_inception_resnet_V2()\nmodel_inception_resnet_v2.load_weights(\"../inception_resnet_images+crop.h5\")\n\n\nimage_path = \"../tests/\"\n\ny_pred = []\ny_pred_irv = []\ny_pred_new = []\n \nfor i in species:\n specie = join(image_path, i)\n\n files = listdir(specie)\n files.sort(key=lambda f: int(\"\".join(filter(str.isdigit, f))))\n\n for file in files:\n\n img_path = join(specie, file)\n image = cv2.imread(img_path, 1)\n\n result = model_coco.detect([image], verbose=1)\n\n r = result[0]\n\n l = len(r[\"rois\"])\n\n batches = []\n for j in range(l):\n if r[\"class_ids\"][j] == 15:\n\n y1, x1, y2, x2 = r[\"rois\"][j]\n\n crop = image[y1:y2, x1:x2]\n crop = cv2.resize(crop, (416, 416))\n\n batches.append(crop)\n\n batches = np.asarray(batches).astype(\"float32\")\n batches /= 255\n\n if batches.shape[0] > 0:\n inception_v3_predictions = model_cropped_inception_v3.predict(batches)\n inception_renet_v2_predictions = model_inception_resnet_v2.predict(batches)\n\n flipped = []\n flipped_1 = []\n flip_final = []\n for i in range(batches.shape[0]):\n flip = np.flip(np.argsort(inception_v3_predictions)[i], axis=0)\n flip1 = np.flip(np.argsort(inception_renet_v2_predictions)[i], axis=0)\n flipped.append(flip[0])\n flipped_1.append(flip1[0])\n\n for a in range(len(flipped)):\n m1 = flipped[a]\n m2 = flipped_1[a]\n if (\n inception_v3_predictions[0][m1]\n > inception_renet_v2_predictions[0][m2]\n ):\n flip_final.append(m1)\n else:\n flip_final.append(m2)\n\n x = np.bincount(flip_final)\n\n maxi = np.argmax(x)\n\n y_pred += [maxi]\n\n else:\n im = cv2.resize(image, (416, 416))\n im = np.reshape(im, (1, 416, 416, 3))\n\n inception_v3_predictions = model_final_inception_v3.predict(im)\n inception_renet_v2_predictions = model_inception_resnet_v2.predict(im)\n\n maxi = np.argmax(inception_v3_predictions)\n maxi_1 = np.argmax(inception_renet_v2_predictions)\n\n y_pred += [maxi]\n y_pred_irv += [maxi_1]\n if (\n inception_v3_predictions[0][maxi]\n > inception_renet_v2_predictions[0][maxi_1]\n ):\n y_pred_new += [maxi]\n else:\n y_pred_new += [maxi_1]\n\n\nnp.save(\"./Y_test_predictions.npy\", y_pred)\n" ]
[ [ "numpy.bincount", "numpy.reshape", "numpy.asarray", "numpy.save", "numpy.argmax", "numpy.argsort" ] ]
rahulisaac/image-processing
[ "595e702e337729844625cd6d5d8252fcc9b63a6a" ]
[ "code/04-drawing/ApplyMask.py" ]
[ "\"\"\"\n * Python program to apply a mask to an image.\n *\n\"\"\"\nimport numpy as np\nimport skimage\nfrom skimage.viewer import ImageViewer\n\n# Load the original image\nimage = skimage.io.imread(\"maize-roots.tif\")\n\n# Create the basic mask\nmask = np.ones(shape=image.shape[0:2], dtype=\"bool\")\n\n# Draw a filled rectangle on the mask image\nrr, cc = skimage.draw.rectangle(start=(357, 44), end=(740, 720))\nmask[rr, cc] = False\n\n# Apply the mask and display the result\nimage[mask] = 0\nviewer = ImageViewer(image)\nviewer.show()\n" ]
[ [ "numpy.ones" ] ]
nklugman/PlugWatch
[ "4fbd2506a6808542fc5246e87d3c382761da1eaf" ]
[ "powerwatch/analysis/old_analysis_scripts/pw_clustering.py" ]
[ "#!/usr/bin/env python3\n\n# looking for big cluster of events and plotting GPS\n\nimport dateutil\nimport csv\nimport math\nimport pprint\nimport sys\nimport time\n\nimport itertools\nimport matplotlib.pyplot as plt\nimport numpy as np\n\ntry:\n pw_file = sys.argv[1]\nexcept:\n print()\n print('Usage: {} pw_fils.csv'.format(sys.argv[0]))\n print()\n raise\n\n# Threshold is time between events to define a cluster\n# Size is minimum number of events in a cluster to be considered an outage\nTHRES_PW = 5*60\nCLUSTER_SIZE_PW = 3\n\nprint('Config:')\nprint('PW\\tCluster sep {}, cluster size {}'.format(THRES_PW, CLUSTER_SIZE_PW))\nprint()\n\n# Load PW Data\ntimes_pw = []\ntimes_ref = {}\n\nwith open(pw_file) as csvfile:\n reader = csv.reader(csvfile)\n headers = next(reader, None)\n cores = {}\n cores_last = {}\n for row in reader:\n core_id = row[headers.index('core_id')]\n is_powered = True if row[headers.index('is_powered')] == 't' else False\n\n # Only care about the Accra sensors\n product_id = int(row[headers.index('product_id')])\n if product_id not in (7008, 7009):\n continue\n\n # Handle new nodes, we get enough repeats that ignoring the first\n # message is fine\n if core_id not in cores:\n cores[core_id] = is_powered\n continue\n\n # If the power state changes update\n if cores[core_id] != is_powered:\n cores[core_id] = is_powered\n\n # If the power turned off, note an event\n if is_powered == False:\n time_str = row[headers.index('time')]\n time_str = time_str.split('.')[0]\n date = dateutil.parser.parse(time_str)\n epoch = date.timestamp()\n\n # Filter out repeate events from same node tighter than\n # clustering\n if core_id not in cores_last:\n cores_last[core_id] = epoch\n else:\n if epoch - cores_last[core_id] < THRES_PW:\n print('filter')\n cores_last[core_id] = epoch\n continue\n cores_last[core_id] = epoch\n\n #if core_id == '35003d001951353339373130':\n # print('\\t',epoch,'\\t',time_str)\n\n # This is a bit of a hack, but really want unique times :/\n if epoch in times_ref:\n epoch += .1\n\n times_pw.append(epoch)\n times_ref[epoch] = row\n\n ## Optional bail early\n #if epoch > ((times_pw[0] + 1000*60*60*24*7)/1000):\n # break\ntimes_pw.sort()\n\nprint('PW')\nprint('times_pw size: ', len(times_pw))\n\n\nprint('-------')\nprint('Clustering....')\n\n# Clustering\n# https://stackoverflow.com/questions/15800895/finding-clusters-of-numbers-in-a-list\n#\n# This magic splits into events into clusters where clusters are identified by\n# being runs of numbers at least THRES apart. The `res[j]` holds the whole list\n# of clusters, while the `r2` is what we actually use and filters down to just\n# the clusters that are at least CLUSTER_SIZE.\n\nnd = [0] + list(np.where(np.diff(times_pw) > THRES_PW)[0] + 1) + [len(times_pw)]\na, b = itertools.tee(nd)\nnext(b, None)\nres = {}\nr2 = {}\nfor j, (f, b) in enumerate(zip(a, b)):\n res[j] = times_pw[f:b]\n if len(res[j]) >= CLUSTER_SIZE_PW:\n cluster_times_pw = list(res[j])\n r2[int(np.average(cluster_times_pw))] = cluster_times_pw\n\nprint('PW')\nprint('num clusters of any size', len(res))\nprint('num clusters of min size', len(r2))\n\ncluster_times_pw = []\ncnts_pw = []\ncluster_sizes_pw = {}\nbig_times = []\nfor time,cluster in r2.items():\n #print(time,cluster)\n t = time\n cluster_times_pw.append(t)\n cnts_pw.append(len(cluster))\n\n if len(cluster) not in cluster_sizes_pw:\n cluster_sizes_pw[len(cluster)] = 1\n else:\n cluster_sizes_pw[len(cluster)] += 1\n\n #if t == 1535074586:\n # print('PRINTING CLUSTER 1535074586')\n # for c in cluster:\n # print(times_ref[c])\n\n if len(cluster) > 20:\n big_times.append(t)\n print('\\t{}\\t{}'.format(t, len(cluster)))\n s = set()\n for pw in cluster:\n row = times_ref[pw]\n core_id = row[headers.index('core_id')]\n if core_id in s:\n #print(cluster)\n #print(s)\n #print(core_id)\n #print(row[headers.index('time')])\n #raise NotImplementedError\n print(\"!!! DUP\")\n continue\n s.add(core_id)\n lat = row[headers.index('gps_latitude')]\n lng = row[headers.index('gps_longitude')]\n if lat != '':\n print('\\t\\t{},{}'.format(lat,lng))\n\nprint(cluster_sizes_pw)\nfor t in big_times:\n print(t)\n\n#print(cnts_pw)\n\nplt.scatter(cluster_times_pw,cnts_pw)\nplt.show()\n\n" ]
[ [ "numpy.average", "matplotlib.pyplot.scatter", "matplotlib.pyplot.show", "numpy.diff" ] ]
SeonghoBaek/RealtimeCamera
[ "1b371b58eafdddf94330f008495dc9ad593ea8e1" ]
[ "layers.py" ]
[ "import tensorflow as tf\nfrom tensorflow.python.client import device_lib\nimport numpy as np\nimport util\nimport argparse\nimport os\nimport csv\n\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\n\ninput_feature_dim = 97\ncond_step_dim = 8\ncond_wafer_dim = 24\ncond_dim = cond_step_dim + cond_wafer_dim\n\nlstm_sequence_length = 20\nlstm_hidden_size_layer1 = 64\nlstm_hidden_size_layer2 = 64\nlstm_feature_dim = lstm_hidden_size_layer1\nlstm_z_sequence_dim = 16\nlstm_linear_transform_input_dim = 2 * lstm_feature_dim\n\ng_encoder_z_local_dim = 16\ng_encoder_z_dim = lstm_z_sequence_dim + g_encoder_z_local_dim + cond_dim\ng_encoder_input_dim = input_feature_dim\ng_encoder_layer1_dim = 84\ng_encoder_layer2_dim = 64\ng_encoder_layer3_dim = 32\n\ng_decoder_output_dim = input_feature_dim\ng_decoder_layer2_dim = 72\ng_decoder_layer1_dim = 84\n\nd_layer_1_dim = input_feature_dim\nd_layer_2_dim = 64\nd_layer_3_dim = 32\nd_layer_4_dim = 16\n\nnum_block_layers = 3\ndense_layer_depth = 16\n\n\ndef lstm_network(input, scope='lstm_network'):\n with tf.variable_scope(scope):\n # tf.nn.rnn_cell\n lstm_cell1 = tf.contrib.rnn.BasicLSTMCell(lstm_hidden_size_layer1, forget_bias=1.0)\n lstm_cell2 = tf.contrib.rnn.BasicLSTMCell(lstm_hidden_size_layer2, forget_bias=1.0)\n\n lstm_cells = tf.contrib.rnn.MultiRNNCell(cells=[lstm_cell1, lstm_cell2], state_is_tuple=True)\n\n # tf.nn.rnn_cell\n # lstm_cell1 = tf.nn.rnn_cell.LSTMCell(lstm_hidden_size_layer1, forget_bias=1.0)\n # lstm_cell2 = tf.nn.rnn_cell.LSTMCell(lstm_hidden_size_layer2, forget_bias=1.0)\n\n #lstm_cells = tf.nn.rnn_cell.MultiRNNCell(cells=[lstm_cell1, lstm_cell2], state_is_tuple=True)\n\n # initial_state = lstm_cells.zero_state(batch_size, tf.float32)\n\n _, states = tf.nn.dynamic_rnn(lstm_cells, input, dtype=tf.float32, initial_state=None)\n\n # z_sequence_output = states[1].h\n # print(z_sequence_output.get_shape())\n states_concat = tf.concat([states[0].h, states[1].h], 1)\n\n #def fc(input, scope, out_dim, non_linear_fn=None, initial_value=None, use_bias=True):\n z_sequence_output = fc(states_concat, lstm_z_sequence_dim, scope='linear_transform')\n\n return z_sequence_output\n\n\ndef fc(input_data, out_dim, non_linear_fn=None, initial_value=None, use_bias=True, scope='fc'):\n with tf.variable_scope(scope):\n input_dims = input_data.get_shape().as_list()\n\n if len(input_dims) == 4:\n _, input_h, input_w, num_channels = input_dims\n in_dim = input_h * input_w * num_channels\n flat_input = tf.reshape(input_data, [-1, in_dim])\n else:\n in_dim = input_dims[-1]\n flat_input = input_data\n\n if initial_value is None:\n fc_weight = tf.get_variable(\"weights\", shape=[in_dim, out_dim], initializer=tf.random_normal_initializer(mean=0., stddev=0.01))\n fc_bias = tf.get_variable(\"bias\", shape=[out_dim], initializer=tf.constant_initializer(0.0))\n else:\n fc_weight = tf.get_variable(\"weights\", initializer=initial_value[0])\n fc_bias = tf.get_variable(\"bias\", shape=[out_dim], initializer=initial_value[1])\n\n if use_bias:\n output = tf.add(tf.matmul(flat_input, fc_weight), fc_bias)\n else:\n output = tf.matmul(flat_input, fc_weight)\n\n if non_linear_fn is None:\n return output\n else:\n activation = non_linear_fn(output)\n\n return activation\n\n\ndef batch_norm(x, b_train, scope, reuse=False):\n with tf.variable_scope(scope, reuse=tf.AUTO_REUSE):\n n_out = x.get_shape().as_list()[-1]\n\n beta = tf.get_variable('beta', initializer=tf.constant(0.0, shape=[n_out]))\n gamma = tf.get_variable('gamma', initializer=tf.constant(1.0, shape=[n_out]))\n\n batch_mean, batch_var = tf.nn.moments(x, [0], name='moments')\n ema = tf.train.ExponentialMovingAverage(decay=0.9)\n\n def mean_var_with_update():\n ema_apply_op = ema.apply([batch_mean, batch_var])\n with tf.control_dependencies([ema_apply_op]):\n return tf.identity(batch_mean), tf.identity(batch_var)\n\n mean, var = tf.cond(b_train,\n mean_var_with_update,\n lambda: (ema.average(batch_mean), ema.average(batch_var)))\n normed = tf.nn.batch_normalization(x, mean, var, beta, gamma, 1e-3)\n\n return normed\n\n\ndef conv(input, scope, filter_dims, stride_dims, padding='SAME',\n non_linear_fn=tf.nn.relu, dilation=[1, 1, 1, 1], bias=True):\n input_dims = input.get_shape().as_list()\n\n assert (len(input_dims) == 4) # batch_size, height, width, num_channels_in\n assert (len(filter_dims) == 3) # height, width and num_channels out\n assert (len(stride_dims) == 2) # stride height and width\n\n num_channels_in = input_dims[-1]\n filter_h, filter_w, num_channels_out = filter_dims\n stride_h, stride_w = stride_dims\n\n with tf.variable_scope(scope):\n conv_weight = tf.Variable(\n tf.truncated_normal([filter_h, filter_w, num_channels_in, num_channels_out], stddev=0.1, dtype=tf.float32))\n conv_bias = tf.Variable(tf.zeros([num_channels_out], dtype=tf.float32))\n map = tf.nn.conv2d(input, conv_weight, strides=[1, stride_h, stride_w, 1], padding=padding, dilations=dilation)\n\n if bias is True:\n map = tf.nn.bias_add(map, conv_bias)\n\n if non_linear_fn is not None:\n activation = non_linear_fn(map)\n else:\n activation = map\n\n # print(activation.get_shape().as_list())\n return activation\n\n\ndef batch_norm_conv(x, b_train, scope):\n with tf.variable_scope(scope, reuse=tf.AUTO_REUSE):\n n_out = x.get_shape().as_list()[-1]\n\n beta = tf.get_variable('beta', initializer=tf.constant(0.0, shape=[n_out]))\n gamma = tf.get_variable('gamma', initializer=tf.constant(1.0, shape=[n_out]))\n\n batch_mean, batch_var = tf.nn.moments(x, [0, 1, 2], name='moments')\n ema = tf.train.ExponentialMovingAverage(decay=0.9)\n\n def mean_var_with_update():\n ema_apply_op = ema.apply([batch_mean, batch_var])\n with tf.control_dependencies([ema_apply_op]):\n return tf.identity(batch_mean), tf.identity(batch_var)\n\n mean, var = tf.cond(b_train,\n mean_var_with_update,\n lambda: (ema.average(batch_mean), ema.average(batch_var)))\n normed = tf.nn.batch_normalization(x, mean, var, beta, gamma, 1e-3)\n\n return normed\n\n\ndef add_dense_layer(layer, filter_dims, act_func=tf.nn.relu, scope='dense_layer',\n use_bn=True, bn_phaze=False, use_bias=False, dilation=[1, 1, 1, 1]):\n with tf.variable_scope(scope):\n l = layer\n\n if use_bn:\n l = batch_norm_conv(l, b_train=bn_phaze, scope='bn')\n\n l = act_func(l)\n l = conv(l, scope='conv', filter_dims=filter_dims, stride_dims=[1, 1], dilation=dilation,\n non_linear_fn=None, bias=use_bias)\n l = tf.concat([l, layer], 3)\n\n return l\n\n\ndef add_residual_layer(layer, filter_dims, act_func=tf.nn.relu, scope='residual_layer',\n use_bn=True, bn_phaze=False, use_bias=False, dilation=[1, 1, 1, 1]):\n with tf.variable_scope(scope):\n l = layer\n\n if use_bn:\n l = batch_norm_conv(l, b_train=bn_phaze, scope='bn')\n\n l = act_func(l)\n l = conv(l, scope='conv', filter_dims=filter_dims, stride_dims=[1, 1], dilation=dilation, non_linear_fn=act_func, bias=use_bias)\n\n return l\n\n\ndef add_dense_transition_layer(layer, filter_dims, stride_dims=[1, 1], act_func=tf.nn.relu, scope='transition',\n use_bn=True, bn_phaze=False, use_pool=True, use_bias=False, dilation=[1, 1, 1, 1]):\n with tf.variable_scope(scope):\n if use_bn:\n l = batch_norm_conv(layer, b_train=bn_phaze, scope='bn')\n\n l = act_func(l)\n l = conv(l, scope='conv', filter_dims=filter_dims, stride_dims=stride_dims, non_linear_fn=None,\n bias=use_bias, dilation=dilation)\n\n if use_pool:\n l = tf.nn.max_pool(l, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')\n\n return l\n\n\ndef global_avg_pool(input_data, output_length=1, padding='VALID', scope='gloval_avg_pool'):\n input_dims = input_data.get_shape().as_list()\n\n assert (len(input_dims) == 4) # batch_size, height, width, num_channels_in\n\n num_channels_in = input_dims[-1]\n height = input_dims[1]\n width = input_dims[2]\n\n with tf.variable_scope(scope):\n if output_length == 1:\n pool = tf.nn.avg_pool(input_data, [1, height, width, 1], strides=[1, 1, 1, 1], padding=padding)\n pool = tf.reduce_mean(pool, axis=[1, 2])\n pool = tf.squeeze(pool, axis=[1, 2])\n\n return pool\n else:\n if num_channels_in != output_length:\n conv_weight = tf.Variable(tf.truncated_normal([1, 1, num_channels_in, output_length], stddev=0.1, dtype=tf.float32))\n conv = tf.nn.conv2d(input_data, conv_weight, strides=[1, 1, 1, 1], padding='SAME')\n pool = tf.nn.avg_pool(conv, ksize=[1, height, width, 1], strides=[1, 1, 1, 1], padding=padding)\n else:\n pool = tf.nn.avg_pool(input_data, ksize=[1, height, width, 1], strides=[1, 1, 1, 1], padding=padding)\n pool = tf.squeeze(pool, axis=[1, 2])\n\n return pool\n\n\ndef avg_pool(input, scope, filter_dims, stride_dims, padding='SAME'):\n assert (len(filter_dims) == 2) # filter height and width\n assert (len(stride_dims) == 2) # stride height and width\n\n filter_h, filter_w = filter_dims\n stride_h, stride_w = stride_dims\n\n with tf.variable_scope(scope):\n pool = tf.nn.avg_pool(input, ksize=[1, filter_h, filter_w, 1], strides=[1, stride_h, stride_w, 1],\n padding=padding)\n\n return pool\n\n\ndef get_deconv2d_output_dims(input_dims, filter_dims, stride_dims, padding):\n batch_size, input_h, input_w, num_channels_in = input_dims\n filter_h, filter_w, num_channels_out = filter_dims\n stride_h, stride_w = stride_dims\n\n if padding == 'SAME':\n out_h = input_h * stride_h\n elif padding == 'VALID':\n out_h = (input_h - 1) * stride_h + filter_h\n\n if padding == 'SAME':\n out_w = input_w * stride_w\n elif padding == 'VALID':\n out_w = (input_w - 1) * stride_w + filter_w\n\n return [batch_size, out_h, out_w, num_channels_out]\n\n\ndef deconv(input_data, b_size, scope, filter_dims, stride_dims, padding='SAME', non_linear_fn=tf.nn.relu):\n input_dims = input_data.get_shape().as_list()\n # print(scope, 'in', input_dims)\n assert (len(input_dims) == 4) # batch_size, height, width, num_channels_in\n assert (len(filter_dims) == 3) # height, width and num_channels out\n assert (len(stride_dims) == 2) # stride height and width\n\n input_dims = [b_size, input_dims[1], input_dims[2], input_dims[3]]\n num_channels_in = input_dims[-1]\n filter_h, filter_w, num_channels_out = filter_dims\n stride_h, stride_w = stride_dims\n\n output_dims = get_deconv2d_output_dims(input_dims,\n filter_dims,\n stride_dims,\n padding)\n\n with tf.variable_scope(scope):\n deconv_weight = tf.Variable(\n tf.random_normal([filter_h, filter_w, num_channels_out, num_channels_in], stddev=0.1, dtype=tf.float32))\n\n deconv_bias = tf.Variable(tf.zeros([num_channels_out], dtype=tf.float32))\n\n map = tf.nn.conv2d_transpose(input_data, deconv_weight, output_dims, strides=[1, stride_h, stride_w, 1],\n padding=padding)\n\n map = tf.nn.bias_add(map, deconv_bias)\n\n activation = non_linear_fn(map)\n\n # print(scope, 'out', activation.get_shape().as_list())\n return activation\n\n\ndef self_attention(x, channels, act_func=tf.nn.relu, scope='attention'):\n with tf.variable_scope(scope):\n batch_size, height, width, num_channels = x.get_shape().as_list()\n\n f = conv(x, scope='f_conv', filter_dims=[1, 1, channels//8], stride_dims=[1, 1], non_linear_fn=act_func)\n f = tf.layers.max_pooling2d(f, pool_size=2, strides=2, padding='SAME')\n\n print('attention f dims: ' + str(f.get_shape().as_list()))\n\n g = conv(x, scope='g_conv', filter_dims=[1, 1, channels//8], stride_dims=[1, 1], non_linear_fn=act_func)\n\n print('attention g dims: ' + str(g.get_shape().as_list()))\n\n h = conv(x, scope='h_conv', filter_dims=[1, 1, channels//2], stride_dims=[1, 1], non_linear_fn=act_func)\n h = tf.layers.max_pooling2d(h, pool_size=2, strides=2, padding='SAME')\n\n print('attention h dims: ' + str(h.get_shape().as_list()))\n\n # N = h * w\n g = tf.reshape(g, shape=[-1, g.shape[1]*g.shape[2], g.get_shape().as_list()[-1]])\n\n print('attention g flat dims: ' + str(g.get_shape().as_list()))\n\n f = tf.reshape(f, shape=[-1, f.shape[1]*f.shape[2], f.shape[-1]])\n\n print('attention f flat dims: ' + str(f.get_shape().as_list()))\n\n s = tf.matmul(g, f, transpose_b=True) # # [bs, N, N]\n\n beta = tf.nn.softmax(s) # attention map\n\n print('attention beta dims: ' + str(s.get_shape().as_list()))\n\n h = tf.reshape(h, shape=[-1, h.shape[1]*h.shape[2], h.shape[-1]])\n\n print('attention h flat dims: ' + str(h.get_shape().as_list()))\n\n o = tf.matmul(beta, h) # [bs, N, C]\n\n print('attention o dims: ' + str(o.get_shape().as_list()))\n\n gamma = tf.get_variable(\"gamma\", [1], initializer=tf.constant_initializer(0.0))\n\n o = tf.reshape(o, shape=[-1, height, width, num_channels // 2]) # [bs, h, w, C]\n o = conv(o, scope='attn_conv', filter_dims=[1, 1, channels], stride_dims=[1, 1], non_linear_fn=act_func)\n x = gamma * o + x\n\n return x\n" ]
[ [ "tensorflow.constant_initializer", "tensorflow.nn.conv2d", "tensorflow.contrib.rnn.BasicLSTMCell", "tensorflow.matmul", "tensorflow.nn.moments", "tensorflow.reshape", "tensorflow.contrib.rnn.MultiRNNCell", "tensorflow.control_dependencies", "tensorflow.nn.softmax", "tensorflow.nn.avg_pool", "tensorflow.random_normal", "tensorflow.random_normal_initializer", "tensorflow.identity", "tensorflow.concat", "tensorflow.constant", "tensorflow.variable_scope", "tensorflow.squeeze", "tensorflow.nn.conv2d_transpose", "tensorflow.nn.dynamic_rnn", "tensorflow.nn.bias_add", "tensorflow.nn.batch_normalization", "tensorflow.nn.max_pool", "tensorflow.zeros", "tensorflow.truncated_normal", "tensorflow.get_variable", "tensorflow.layers.max_pooling2d", "tensorflow.train.ExponentialMovingAverage", "tensorflow.reduce_mean" ] ]
jsr1611/efficient_object_labeling_tool
[ "ff51935a1c267dd58845a7864114868f1e55cbf9" ]
[ "yolo_v31.py" ]
[ "# -*- coding: utf-8 -*-\n\"\"\"\nClass definition of YOLO_v3 style detection model on image and video\n# Added functionalities:\n # Manually remove bboxes, and draw new ones\n # Auto identify the duration of the video input file in number of frames => frame_count_total variable\n # Handle missing objects and new objects by removal and addition functions\n # Generate output video\n # Display Two screens, an editor and replay of the interpolated frames\n\"\"\"\nimport _tkinter\nimport colorsys\nimport os\nfrom os.path import isfile\nfrom timeit import default_timer as timer\nimport datetime as dtime\nimport numpy as np\nfrom keras import backend as K\nfrom keras.models import load_model\nfrom keras.layers import Input\nfrom PIL import Image, ImageFont, ImageDraw\n\nfrom yolo3.model import yolo_eval, yolo_body, tiny_yolo_body\nfrom yolo3.utils import letterbox_image\nimport os\nfrom keras.utils import multi_gpu_model\nimport cv2\nimport easygui as ez\nfrom tkinter.filedialog import askopenfilename, Tk, Button, X\nfrom SecondVid_v01 import camera1_tracker, dispay_info\n\n# Global variables\ncounter_ = 1\ninterval = 10\nframes_total = 0\nfinal_coor_name = \"./coordinates_.txt\"\nfinal_coor_name = final_coor_name[:-4] + dtime.datetime.today().strftime('%Y%m%d%H%M') + final_coor_name[-4:]\nbboxNxt = []\nbboxPrev = [] # previous frame data\n\nframeNum = 0\nintrpltd_box = [frameNum, 0, (0, 0, 0, 0)] # temp variable for full data on one object\nmy_flag2 = False # return img and bbox in the '2nd video labeling'\ncam2_flag = 0\noutput_path3 = \"\"\nid_max = 0\nstatus = \"\" # Window status indicator, ex: Active or Inactive\n\n\n# A function for writing bbox coordinates into a file\ndef write2File(final_bbox):\n for f in range(len(final_bbox)):\n # print(\"Frame:\", final_bbox[f])\n with open(final_coor_name,\n \"a\") as text_file: # \"a\" for appending; \"w\" for overwriting\n print(\n \"{0:<6d} {1:<6d} {2:<6d} {3:<6d} {4:<6d} {5:<6d}\".format(final_bbox[f][0], final_bbox[f][1],\n final_bbox[f][2][0],\n final_bbox[f][2][1], final_bbox[f][2][2],\n final_bbox[f][2][3]), file=text_file)\n\n print(\"The human generated bbox coordinates are saved at: {}\".format(final_coor_name))\n\n\n# A function to truncate erroneous zeros\ndef trunc_0s(data_in):\n data_out = []\n # print(\"data_in before:\", data_in)\n try:\n if len(data_in[2]) == 4:\n if data_in[2][0] == 0 and data_in[2][1] == 0:\n # print(\"YES\\n\")\n if data_in[2][2] != 0:\n data_out.append(data_in)\n data_in = data_out\n else:\n for a in range(len(data_in)):\n if data_in[a][2][0] == 0 and data_in[a][2][1] == 0:\n print(\"YES\\n\")\n for i in range(len(data_in)):\n if data_in[i][2][0] != 0 and data_in[i][2][1] != 0 and data_in[i][2][2] != 0:\n data_out.append(data_in[i])\n data_in = data_out\n except IndexError:\n print(\"Index Error inside eucl_sort_add() function\")\n # print(\"data_in after:\", data_in)\n return data_in\n\n\n# A function for identifying and matching objects between 2 different frames. LENGTH of both objects should be the SAME\ndef eucl_sort(data_0, data_x):\n import math\n # coor1, bbox = eucl_sort(coor1, bbox)\n # provide coordinates (any_nym, top, left, bottom, right) of two frames\n # and get the corrected array of coordinates for the frame(array)\n # ------------Frame x-1 -----------------------------------------\n print(\"previous_data_0 \", data_0, '\\n')\n print(\"current_data_x \", data_x, '\\n')\n\n data_0 = trunc_0s(data_0)\n data_x = trunc_0s(data_x)\n\n data_return = []\n data_xx = data_x\n data_00 = data_0\n\n data_0_new = []\n data_x_new = []\n if (len(data_xx) > 0 and len(data_00)):\n for el in data_0:\n data_0_new.append(el[2])\n for el2 in data_x:\n data_x_new.append(el2[2])\n data0r_np = data_0 # to be reused\n dataxr_np = data_x # to be reused\n return_np = data_x # to be returned\n data_0 = data_0_new\n data_x = data_x_new\n\n data_0 = replaceAll(\" \".join(str(x) for x in data_0))\n data_x = replaceAll(\" \".join(str(x) for x in data_x).replace(\"[\", \"\"))\n # ------------Frame 0-----------------------------------------\n data_0 = [int(i) for i in data_0.split()]\n frame_obj_0 = int(len(data_0) / 4)\n data0_np = np.array(data_0).reshape(frame_obj_0, 4)\n # ------------Frame x-----------------------------------------\n data_x = [int(i) for i in data_x.split()]\n frame_obj_x = int(len(data_x) / 4)\n datax_np = np.array(data_x).reshape(frame_obj_x, 4)\n centroid_xy_0 = [] #\n centroid_x_0 = [] #\n centroid_y_0 = [] #\n # -----------------\n for k in range(data0_np.shape[0]):\n Left_0, Top_0, Right_0, Bottom_0 = data0_np[k, :]\n centroid_xy_0.append((Left_0 + Right_0) / 2)\n centroid_xy_0.append((Top_0 + Bottom_0) / 2)\n centroid_xy_0 = np.array(centroid_xy_0).reshape(data0_np.shape[0], 2)\n # -----------------------Frame x centroid-----------------------------\n centroid_xy_x = [] #\n centroid_x_x = [] #\n centroid_y_x = [] #\n # -----------------\n for k in range(datax_np.shape[0]):\n Left_x, Top_x, Right_x, Bottom_x = datax_np[k, :]\n centroid_xy_x.append((Left_x + Right_x) / 2)\n centroid_xy_x.append((Top_x + Bottom_x) / 2)\n\n centroid_xy_x = np.array(centroid_xy_x).reshape(datax_np.shape[0], 2)\n # ---------------------------------Euclidean distance calculation------------------------------------------\n index_mat = []\n duplicate_index = []\n tmp_arr = []\n for k in range(data0_np.shape[0]):\n index = 0\n for l in range(datax_np.shape[0]):\n if l == 0:\n cx, cy = centroid_xy_0[k, :] - centroid_xy_x[l, :]\n Euc_Dis = math.sqrt(cx ** 2 + cy ** 2)\n else:\n cx, cy = centroid_xy_0[k, :] - centroid_xy_x[l, :]\n Euc_Dis_new = math.sqrt(cx ** 2 + cy ** 2)\n if Euc_Dis_new > Euc_Dis:\n Euc_Dis = Euc_Dis\n index = index\n else:\n Euc_Dis = Euc_Dis_new\n index = l\n if k == 0:\n index_mat.append(index)\n tmp_arr.append(data_00[index][1])\n for i in range(k):\n if index not in index_mat:\n index_mat.append(index)\n tmp_arr.append(data_00[index][1])\n old_indices = []\n try:\n for o in range(len(data_00)):\n old_indices.append(data_00[o][1])\n\n for i in range(len(old_indices)):\n if old_indices[i] not in tmp_arr:\n index_mat.append(i)\n tmp_arr.append(old_indices[i])\n\n index_mat = np.array(index_mat, np.int16)\n for i in range(len(data_xx)):\n data_return.append(data_xx[index_mat[i]])\n data_return[i][1] = data_00[i][1]\n except IndexError:\n print(\"Index Error inside eucl_sort() function\")\n # print(\"index_mat:\", index_mat)\n print(\"Output data_0 data_x:\\n\", data_00, data_return)\n else:\n pass\n return data_00, data_return\n\n\n# replaceAll removes all unnecessary literals in a given string\ndef replaceAll(txt):\n print(\"Input txt data:\", txt)\n txt = txt.replace(\",\", \" \").replace(\"]\", \" \").replace(\"[\", \" \").replace(\")\", \" \").replace(\"(\", \" \")\n print(\"Output txt data:\", txt)\n return txt\n\n\n# euc_remove function removes object bbox coordinates inside a given area specified by another (bigger) bbox coordinates\ndef euc_remove(input_0, target):\n print(\"input data \", input_0, '\\n')\n print(\"target for removal \", target, '\\n')\n global rm_labels\n output_data = []\n cxy = []\n for i in range(len(input_0)):\n cxy.append((int((int(input_0[i][2][0]) + int(input_0[i][2][2])) / 2),\n int((int(input_0[i][2][1]) + int(input_0[i][2][3])) / 2)))\n index2 = 0\n index = 0\n myflag_0 = False\n rm_labels = []\n for i in range(len(input_0)):\n for j in range(len(target)):\n if target[j][0] < cxy[i][0] < target[j][2] and target[j][1] < cxy[i][1] < target[j][3]:\n myflag_0 = True\n index2 = i\n else:\n try:\n if not myflag_0:\n index = i\n except IndexError:\n print(\"Index Error\")\n if not myflag_0:\n output_data.append(input_0[index])\n else:\n rm_labels.append(index2)\n print(\"deleted label: \", input_0[index2])\n myflag_0 = False\n print(\"rm_label(len)=\", len(rm_labels))\n print(\"Output data: \", output_data)\n return output_data\n\n\n# eucl_sort_remove removes missing object(s) in the past frame (data_0) and matches the objects between frames\ndef eucl_sort_remove(data_0, data_x):\n # coor1, bbox = eucl_sort_remove(coor1, bbox)\n import math\n # provide coordinates (any_nym, top, left, bottom, right) of two frames\n # and get the corrected array of coordinates for the frame(array)\n # ------------Frame x-1 -----------------------------------------\n print(\"previous_data_0 \", data_0, '\\n')\n print(\"current_data_x \", data_x, '\\n')\n data_x = trunc_0s(data_x)\n data_0 = trunc_0s(data_0)\n\n data_return = []\n data_xx = data_x\n data_00 = data_0\n\n data_0_new = []\n data_x_new = []\n if (len(data_00) > 0 and len(data_xx) > 0):\n for el in data_0:\n data_0_new.append(el[2])\n for el2 in data_x:\n data_x_new.append(el2[2])\n data0r_np = data_0 # to be reused\n dataxr_np = data_x # to be reused\n return_np = data_x # to be returned\n data_0 = data_0_new\n data_x = data_x_new\n\n data_0 = replaceAll(\" \".join(str(x) for x in data_0))\n data_x = replaceAll(\" \".join(str(x) for x in data_x).replace(\"[\", \"\"))\n # ------------Frame 0-----------------------------------------\n data_0 = [int(i) for i in data_0.split()]\n frame_obj_0 = int(len(data_0) / 4)\n data0_np = np.array(data_0).reshape(frame_obj_0, 4)\n # ------------Frame x-----------------------------------------\n data_x = [int(i) for i in data_x.split()]\n frame_obj_x = int(len(data_x) / 4)\n datax_np = np.array(data_x).reshape(frame_obj_x, 4)\n\n centroid_xy_0 = [] #\n centroid_x_0 = [] #\n centroid_y_0 = [] #\n # -----------------\n for k in range(data0_np.shape[0]):\n Left_0, Top_0, Right_0, Bottom_0 = data0_np[k, :]\n centroid_xy_0.append((Left_0 + Right_0) / 2)\n centroid_xy_0.append((Top_0 + Bottom_0) / 2)\n centroid_xy_0 = np.array(centroid_xy_0).reshape(data0_np.shape[0], 2)\n\n # -----------------------Frame x centroid-----------------------------\n centroid_xy_x = [] #\n centroid_x_x = [] #\n centroid_y_x = [] #\n # -----------------\n for k in range(datax_np.shape[0]):\n Left_x, Top_x, Right_x, Bottom_x = datax_np[k, :]\n centroid_xy_x.append((Left_x + Right_x) / 2)\n centroid_xy_x.append((Top_x + Bottom_x) / 2)\n\n centroid_xy_x = np.array(centroid_xy_x).reshape(datax_np.shape[0], 2)\n\n # ---------------------------------Euclidean distance calculation------------------------------------------\n index_mat = []\n l = 0\n\n for k in range(datax_np.shape[0]):\n index = 0\n for l in range(data0_np.shape[0]):\n if (l == 0):\n cx, cy = centroid_xy_x[k, :] - centroid_xy_0[l, :]\n Euc_Dis = math.sqrt(cx ** 2 + cy ** 2)\n # print(\"Euc_Dis\", Euc_Dis)\n else:\n cx, cy = centroid_xy_x[k, :] - centroid_xy_0[l, :]\n Euc_Dis_new = math.sqrt(cx ** 2 + cy ** 2)\n # print(\"Euc_Dis_new\", Euc_Dis_new)\n if Euc_Dis_new > Euc_Dis:\n Euc_Dis = Euc_Dis\n index = index\n else:\n Euc_Dis = Euc_Dis_new\n index = l\n\n index_mat = np.append(index_mat, index)\n index_mat = np.array(index_mat, np.int16)\n # print(index_mat)\n for i in range(len(data_xx)):\n data_return.append(data_00[index_mat[i]])\n data_return[i][1] = data_00[index_mat[i]][1]\n print(\"Output data_0 data_x:\\n\", data_return, \"\\n\", data_xx)\n else:\n pass\n return data_return, data_xx\n\n\n# eucl_sort_add adds new objects at the end of the array (data_x)and needed for matching the objects between frames\ndef eucl_sort_add(data_0, data_x):\n import math\n # provide coordinates (frame num, id, top, left, bottom, right) of two frames\n # and get the corrected array of coordinates for the frame(array)\n # ------------Frame x-1 -----------------------------------------\n print(\"previous_data_0 \", data_0, '\\n')\n print(\"current_data_x \", data_x, '\\n')\n\n data_x = trunc_0s(data_x)\n data_0 = trunc_0s(data_0)\n\n data_return = []\n data_xx = data_x\n data_00 = data_0\n\n data_0_new = []\n data_x_new = []\n if (len(data_00) > 0 and len(data_xx) > 0):\n for el in data_0:\n data_0_new.append(el[2])\n for el2 in data_x:\n data_x_new.append(el2[2])\n data0r_np = data_0 # to be reused\n dataxr_np = data_x # to be reused\n return_np = data_x # to be returned\n data_0 = data_0_new\n data_x = data_x_new\n\n data_0 = replaceAll(\" \".join(str(x) for x in data_0))\n data_x = replaceAll(\" \".join(str(x) for x in data_x).replace(\"[\", \"\"))\n # ------------Frame 0-----------------------------------------\n data_0 = [int(i) for i in data_0.split()]\n frame_obj_0 = int(len(data_0) / 4)\n data0_np = np.array(data_0).reshape(frame_obj_0, 4)\n # ------------Frame x-----------------------------------------\n data_x = [int(i) for i in data_x.split()]\n frame_obj_x = int(len(data_x) / 4)\n datax_np = np.array(data_x).reshape(frame_obj_x, 4)\n\n centroid_xy_0 = [] #\n centroid_x_0 = [] #\n centroid_y_0 = [] #\n # -----------------\n for k in range(data0_np.shape[0]):\n Left_0, Top_0, Right_0, Bottom_0 = data0_np[k, :]\n centroid_xy_0.append((Left_0 + Right_0) / 2)\n centroid_xy_0.append((Top_0 + Bottom_0) / 2)\n centroid_xy_0 = np.array(centroid_xy_0).reshape(data0_np.shape[0], 2)\n\n # -----------------------Frame x centroid-----------------------------\n centroid_xy_x = [] #\n centroid_x_x = [] #\n centroid_y_x = [] #\n # -----------------\n for k in range(datax_np.shape[0]):\n Left_x, Top_x, Right_x, Bottom_x = datax_np[k, :]\n centroid_xy_x.append((Left_x + Right_x) / 2)\n centroid_xy_x.append((Top_x + Bottom_x) / 2)\n\n centroid_xy_x = np.array(centroid_xy_x).reshape(datax_np.shape[0], 2)\n\n # ---------------------------------Euclidean distance calculation------------------------------------------\n index_mat = []\n l = 0\n test_mat = []\n\n for k in range(data0_np.shape[0]):\n index = 0\n for l in range(datax_np.shape[0]):\n if (l == 0):\n cx, cy = centroid_xy_0[k, :] - centroid_xy_x[l, :]\n Euc_Dis = math.sqrt(cx ** 2 + cy ** 2)\n # print(\"Euc_Dis\", Euc_Dis)\n else:\n cx, cy = centroid_xy_0[k, :] - centroid_xy_x[l, :]\n Euc_Dis_new = math.sqrt(cx ** 2 + cy ** 2)\n # print(\"Euc_Dis_new\", Euc_Dis_new)\n if Euc_Dis_new > Euc_Dis:\n Euc_Dis = Euc_Dis\n index = index\n else:\n Euc_Dis = Euc_Dis_new\n index = l\n\n index_mat = np.append(index_mat, index)\n index_mat = np.array(index_mat, np.int16)\n # print(\"existing:\", end=\" \")\n # for x in range(0, len(data_xx)):\n # print(x, end=\" \")\n # print(\"\\nMatching index:\\t\", index_mat)\n\n data_new = []\n index_mat_new = []\n\n for i in range(len(data_00)):\n data_return.append(data_xx[index_mat[i]])\n data_return[i][1] = data_00[i][1]\n\n arr = [0] * len(data_xx)\n for i in range(len(data_xx)):\n try:\n for j in range(len(index_mat)):\n if i == index_mat[j]:\n arr[i] = 1\n except IndexError:\n print(\"IndexError. Unmatching index:\", i)\n for k in range(len(arr)):\n if arr[k] == 0:\n data_new.append(data_xx[k])\n index_mat_new.append(k)\n try:\n idn = data_return[-1][1] # assign last element's id to idn,\n except IndexError:\n print(\"Index Error\")\n # #and check if it is max value, if not assign max value to idn using the below for loop\n for i in range(len(data_return)):\n if data_return[i][1] > idn:\n idn = data_return[i][1]\n # assign new id to the new objects, get id from idn (max val of previous frame id)\n for m in range(len(index_mat_new)):\n idn += 1\n data_return.append(data_xx[index_mat_new[m]])\n data_return[len(index_mat) + m][1] = idn\n\n # print(\"index_mat_new:\", index_mat_new)\n print(\"Return data_0, data_x: \\n\", data_00, \"\\n\", data_return)\n # print(\"data_new\", data_new)\n else:\n pass\n return data_00, data_return\n\n\ndef eucl_find(data_0, data_x):\n import math\n # ------------Frame x-1 -----------------------------------------\n print(\"data_previous 0 \", data_0, '\\n')\n print(\"data_current x \", data_x, '\\n')\n data_0_new = []\n #data_x_new = []\n data_return = []\n data_00 = data_0 # to be reused\n for el in data_0:\n data_0_new.append(el[2])\n data_x = data_x[2]\n data_0 = data_0_new\n #data_x = data_x_new\n\n data_0 = replaceAll(\" \".join(str(x) for x in data_0))\n data_x = replaceAll(\" \".join(str(x) for x in data_x).replace(\"[\", \"\"))\n\n # ------------Frame 0-----------------------------------------\n data_0 = [int(i) for i in data_0.split()]\n frame_obj_0 = int(len(data_0) / 4)\n data0_np = np.array(data_0).reshape(frame_obj_0, 4)\n\n # ------------Frame x-----------------------------------------\n data_x = [int(i) for i in data_x.split()]\n frame_obj_x = int(len(data_x) / 4)\n datax_np = np.array(data_x).reshape(frame_obj_x, 4)\n centroid_xy_0 = [] #\n # -----------------\n for k in range(data0_np.shape[0]):\n Left_0, Top_0, Right_0, Bottom_0 = data0_np[k, :]\n centroid_xy_0.append((Left_0 + Right_0) / 2)\n centroid_xy_0.append((Top_0 + Bottom_0) / 2)\n centroid_xy_0 = np.array(centroid_xy_0).reshape(data0_np.shape[0], 2)\n # -----------------------Frame x centroid-----------------------------\n centroid_xy_x = [] #\n # -----------------\n for k in range(datax_np.shape[0]):\n Left_x, Top_x, Right_x, Bottom_x = datax_np[k, :]\n centroid_xy_x.append((Left_x + Right_x) / 2)\n centroid_xy_x.append((Top_x + Bottom_x) / 2)\n centroid_xy_x = np.array(centroid_xy_x).reshape(datax_np.shape[0], 2)\n # ---------------------------------Euclidean distance calculation------------------------------------------\n index_mat = []\n try:\n for k in range(datax_np.shape[0]):\n index = 0\n for l in range(data0_np.shape[0]):\n if (l == 0):\n cx, cy = centroid_xy_x[k, :] - centroid_xy_0[l, :]\n Euc_Dis = math.sqrt(cx ** 2 + cy ** 2)\n else:\n cx, cy = centroid_xy_x[k, :] - centroid_xy_0[l, :]\n Euc_Dis_new = math.sqrt(cx ** 2 + cy ** 2)\n if Euc_Dis_new > Euc_Dis:\n Euc_Dis = Euc_Dis\n index = index\n else:\n Euc_Dis = Euc_Dis_new\n index = l\n index_mat = np.append(index_mat, index)\n index_mat = np.array(index_mat, np.int16)\n data_return = data_00[index_mat[0]]\n\n del data_00[index_mat[0]]\n except Exception as e:\n print(e)\n print(\"data_return\", data_return)\n return data_00, data_return\n\ndef fileOpenClicked(default_path):\n root = Tk()\n video_path = str(\n askopenfilename(filetypes=[(\"MP4 files\", \"*.mp4\"), (\"AVI files\", \"*.avi\"), (\"All files\", \"*.*\")]))\n video_path = \"./\" + os.path.split(video_path)[1]\n root.destroy()\n if len(video_path) >= 5:\n print(\"Input file path selected by the user: \", video_path)\n else:\n vid_tmp = cv2.VideoCapture(default_path)\n if vid_tmp.isOpened():\n video_path = default_path\n else:\n raise IOError(\"Error. User canceled input file selection.\")\n print(\"User selected default input file path:\", video_path)\n return video_path\n\n\ndef myRect(img, mybbox, i):\n try:\n if i == 'one':\n cv2.rectangle(img, (int(mybbox[2][0]), int(mybbox[2][1])),\n (int(mybbox[2][2]), int(mybbox[2][3])), (0, 255, 0), 2)\n cv2.rectangle(img, (int(mybbox[2][0]), int(mybbox[2][1]) - 20),\n ((int(mybbox[2][0]) + 30), int(mybbox[2][1])), (0, 255, 0), -1)\n cv2.putText(img, str(mybbox[1]), (int(mybbox[2][0]) + 1, (int(mybbox[2][1]) - 3)),\n cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 1, cv2.LINE_AA)\n else:\n cv2.rectangle(img, (int(mybbox[i][2][0]), int(mybbox[i][2][1])),\n (int(mybbox[i][2][2]), int(mybbox[i][2][3])), (0, 255, 0), 2)\n cv2.rectangle(img, (int(mybbox[i][2][0]), int(mybbox[i][2][1]) - 20),\n ((int(mybbox[i][2][0]) + 30), int(mybbox[i][2][1])), (0, 255, 0), -1)\n cv2.putText(img, str(mybbox[i][1]), (int(mybbox[i][2][0]) + 1, (int(mybbox[i][2][1]) - 3)),\n cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 1, cv2.LINE_AA)\n except IndexError:\n print(\"Index Error\")\n except ValueError:\n print(\"Value Error\")\n return img\n\n\nclass YOLO(object):\n _defaults = {\n \"model_path\": 'model_data/yolo.h5',\n \"anchors_path\": 'model_data/yolo_anchors.txt',\n \"classes_path\": 'model_data/coco_classes.txt',\n \"score\": 0.6,\n \"iou\": 0.45,\n \"model_image_size\": (416, 416),\n \"gpu_num\": 1,\n }\n\n @classmethod\n def get_defaults(cls, n):\n if n in cls._defaults:\n return cls._defaults[n]\n else:\n return \"Unrecognized attribute name '\" + n + \"'\"\n\n def __init__(self, **kwargs):\n self.__dict__.update(self._defaults) # set up default values\n self.__dict__.update(kwargs) # and update with user overrides\n self.class_names = self._get_class()\n self.anchors = self._get_anchors()\n self.sess = K.get_session()\n self.boxes, self.scores, self.classes = self.generate()\n\n def _get_class(self):\n classes_path = os.path.expanduser(self.classes_path)\n with open(classes_path) as f:\n class_names = f.readlines()\n class_names = [c.strip() for c in class_names]\n return class_names\n\n def _get_anchors(self):\n anchors_path = os.path.expanduser(self.anchors_path)\n with open(anchors_path) as f:\n anchors = f.readline()\n anchors = [float(x) for x in anchors.split(',')]\n return np.array(anchors).reshape(-1, 2)\n\n def generate(self):\n model_path = os.path.expanduser(self.model_path)\n assert model_path.endswith('.h5'), 'Keras model or weights must be a .h5 file.'\n\n # Load model, or construct model and load weights.\n num_anchors = len(self.anchors)\n num_classes = len(self.class_names)\n is_tiny_version = num_anchors == 6 # default setting\n try:\n self.yolo_model = load_model(model_path, compile=False)\n except:\n self.yolo_model = tiny_yolo_body(Input(shape=(None, None, 3)), num_anchors // 2, num_classes) \\\n if is_tiny_version else yolo_body(Input(shape=(None, None, 3)), num_anchors // 3, num_classes)\n self.yolo_model.load_weights(self.model_path) # make sure model, anchors and classes match\n else:\n assert self.yolo_model.layers[-1].output_shape[-1] == \\\n num_anchors / len(self.yolo_model.output) * (num_classes + 5), \\\n 'Mismatch between model and given anchor and class sizes'\n\n print('{} model, anchors, and classes loaded.'.format(model_path))\n\n # Generate colors for drawing bounding boxes.\n hsv_tuples = [(x / len(self.class_names), 1., 1.)\n for x in range(len(self.class_names))]\n self.colors = list(map(lambda x: colorsys.hsv_to_rgb(*x), hsv_tuples))\n self.colors = list(\n map(lambda x: (int(x[0] * 255), int(x[1] * 255), int(x[2] * 255)),\n self.colors))\n np.random.seed(10101) # Fixed seed for consistent colors across runs.\n np.random.shuffle(self.colors) # Shuffle colors to decorrelate adjacent classes.\n np.random.seed(None) # Reset seed to default.\n\n # Generate output tensor targets for filtered bounding boxes.\n self.input_image_shape = K.placeholder(shape=(2,))\n if self.gpu_num >= 2:\n self.yolo_model = multi_gpu_model(self.yolo_model, gpus=self.gpu_num)\n boxes, scores, classes = yolo_eval(self.yolo_model.output, self.anchors,\n len(self.class_names), self.input_image_shape,\n score_threshold=self.score, iou_threshold=self.iou)\n return boxes, scores, classes\n\n def detect_image(self, image):\n global bbox, my_label, frameNum\n start = timer()\n img = np.asarray(image)\n bbox = []\n id_num = 0\n my_label = \"veh\"\n centroid_xy = []\n\n if self.model_image_size != (None, None):\n assert self.model_image_size[0] % 32 == 0, 'Multiples of 32 required'\n assert self.model_image_size[1] % 32 == 0, 'Multiples of 32 required'\n boxed_image = letterbox_image(image, tuple(reversed(self.model_image_size)))\n else:\n new_image_size = (image.width - (image.width % 32),\n image.height - (image.height % 32))\n boxed_image = letterbox_image(image, new_image_size)\n image_data = np.array(boxed_image, dtype='float32')\n\n image_data /= 255.\n image_data = np.expand_dims(image_data, 0) # Add batch dimension.\n\n out_boxes, out_scores, out_classes = self.sess.run(\n [self.boxes, self.scores, self.classes],\n feed_dict={\n self.yolo_model.input: image_data,\n self.input_image_shape: [image.size[1], image.size[0]],\n K.learning_phase(): 0\n })\n\n print('Found {} boxes for {}'.format(len(out_boxes), 'img'))\n\n font = ImageFont.truetype(font='font/FiraMono-Medium.otf',\n size=np.floor(3e-2 * image.size[1] + 0.5).astype('int32'))\n thickness = (image.size[0] + image.size[1]) // 300\n\n for i, c in reversed(list(enumerate(out_classes))):\n predicted_class = self.class_names[c]\n box = out_boxes[i]\n score = out_scores[i]\n\n label = '{} {:.2f}'.format(predicted_class, score)\n draw = ImageDraw.Draw(image)\n label_size = draw.textsize(label, font)\n\n top, left, bottom, right = box\n top = max(0, np.floor(top + 0.5).astype('int32'))\n left = max(0, np.floor(left + 0.5).astype('int32'))\n bottom = min(image.size[1], np.floor(bottom + 0.5).astype('int32'))\n right = min(image.size[0], np.floor(right + 0.5).astype('int32'))\n ybox = [left, top, right, bottom]\n # print('yolo:', label+str(id_num), (left, top), (right, bottom))\n bbox.append([frame_counter, id_num, (left, top, right, bottom)])\n centroid_xy.append(int((left + right) / 2))\n centroid_xy.append(int((top + bottom) / 2))\n print(frame_counter, id_num, (left, top, right, bottom))\n # print(\"counter_=1:\", my_label + str(id_num))\n if top - label_size[1] >= 0:\n text_origin = np.array([left, top - label_size[1]])\n else:\n text_origin = np.array([left, top + 1])\n try:\n cv2.rectangle(img, (left, top), (right, bottom), (0, 255, 0), 2)\n cv2.rectangle(img, (left, top - 20), ((left + 30), top), (0, 255, 0), -1)\n cv2.circle(img, (centroid_xy[0], centroid_xy[1]), 3, (0, 255, 0), 2)\n cv2.putText(img, str(id_num), (left + 1, top - 3), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 1,\n cv2.LINE_AA)\n except IndexError:\n print(\"Index Error at detect_image()\")\n id_num += 1\n centroid_xy = []\n left = 0\n right = 0\n top = 0\n bottom = 0\n\n end = timer()\n # print(end - start)\n if my_flag2:\n return img, bbox\n return img\n\n def close_session(self):\n self.sess.close()\n\n ############ Drawing function ##################################\n def drawRect(self, img1, img2):\n # img1 - input image with bboxes for displaying and drawing on\n # img2 - orignal image to be output with bboxes only\n global bbox, bboxPrev, label, id_n, my_label, rm_labels, numOfObj, tmp_bbox, myflag, cam2_flag, id_max, eucfind_data0\n id_n = 1\n label = len(coor1) + id_n\n tmp_bbox = []\n myflag = False\n newObjCounter = 1\n eucfind_data0 = coor1\n eucfind_data1 = coor1 # checked\n while True:\n r = cv2.selectROI(\"Label Editor\", img1, fromCenter=False, showCrosshair=True)\n x1 = int(r[0])\n y1 = int(r[1])\n x2 = int(r[0] + r[2])\n y2 = int(r[1] + r[3])\n if Cam2_flag == 1: # working for second camera\n while True:\n if counter_ == 1:\n label = ez.enterbox(\"Please enter the id of the object\")\n elif counter_ > 1:\n data_x = [frameNum, 0, (x1, y1, x2, y2)]\n if data_x[2][0] == 0 and data_x[2][1] == 0 and data_x[2][2] == 0:\n print(\"jumped?\")\n break\n else:\n eucfind_data0, bbox_ = eucl_find(eucfind_data0, data_x)\n label = bbox_[1]\n msg = \"Selected ID is {}. Is this object ID correct?\".format(label)\n title = \"Object ID selection process\"\n choices = [\"Yes\", \"No\", \"Modify\"]\n key = ez.buttonbox(msg, title, choices)\n if key == \"Yes\":\n eucfind_data1 = eucfind_data0\n pass\n if key == \"Modify\":\n eucfind_data0 = eucfind_data1\n label = ez.enterbox(\"Please enter the ID of the object\")\n else:\n pass\n else:\n label = 0\n try:\n if type(int(label)) is int:\n print(\"label given: {}, my_flag3={}, counter_={}\".format(label, Cam2_flag, counter_))\n break\n else:\n print(\"Please enter the object id correctly. The id should be an integer number!\", label)\n except TypeError:\n print(\"Type Error at bbox appending frameNum={}\".format(counter_))\n except ValueError:\n print(\"Value Error\")\n\n else: # working for first camera\n if counter_ > 1: # when working for consecutive frames\n if len(rm_labels) == 1 and newObjCounter == 1:\n label = rm_labels[0]\n print(\"label:{},myflg3={},counter={},rm_lbls#={}\".format(label, Cam2_flag, counter_,\n len(rm_labels)))\n elif len(rm_labels) > 1 or newObjCounter > 1:\n for i in range(len(coor1)):\n if id_max < coor1[i][1]:\n id_max = coor1[i][1]\n label = id_max + id_n\n id_n += 1\n print(\"label:{},myflg3={},countr={},rm_lbl# = {}\".format(label, Cam2_flag, counter_,\n len(rm_labels)))\n else: # when working for first frame\n label = id_n - 1\n id_n += 1\n try:\n bbox_ = [frameNum, int(label), (x1, y1, x2, y2)]\n bbox_2 = trunc_0s(bbox_)\n print(\"bbox_2, bbox_\", bbox_2, bbox_)\n if bbox_ != bbox_2:\n pass # print(\"jumped?\")\n else:\n bbox.append([frameNum, int(label), (x1, y1, x2, y2)])\n myRect(img1, bbox_, 'one') # Generating bboxes on an image\n print(\"Drawn bbox:\", [frameNum, label, (x1, y1, x2, y2)])\n except ValueError:\n print(\"Value Error\")\n newObjCounter += 1\n if cv2.waitKey(0) & 0xff == 27:\n if Cam2_flag == 1: # when working for second camera\n if counter_ > 1 and len(bbox) > len(coor1):\n myflag = True\n print(\"\\n\\n\\n\\nmyflag=True: bbox, coor1 before eucl_sort_add() \\n\", bbox, \"\\n\", coor1)\n coor1, bbox = eucl_sort_add(coor1, bbox)\n tmp_bbox = bbox\n elif counter_ > 1 and len(bbox) == len(coor1) and (len(bbox) > 0 and len(coor1) > 0):\n print(\"\\n\\n\\n\\nmyflag=True: bbox, coor1 before eucl_sort() \\n\", bbox, \"\\n\", coor1)\n coor1, bbox = eucl_sort(coor1, bbox)\n elif counter_ > 1 and len(bbox_) < len(coor1):\n print(\"\\n\\n\\n\\nmyflag=True: bbox, coor1 before eucl_sort_rem() \\n\", bbox, \"\\n\", coor1)\n coor1, bbox = eucl_sort_remove(coor1, bbox)\n else: # when working for first camera\n if counter_ > 1: # when working for consecutive frames\n if len(bbox) < len(coor1) and len(coor1) > 0:\n myflag = False\n coor1, bbox = eucl_sort_remove(coor1, bbox)\n coor1, bbox = eucl_sort(coor1, bbox)\n # print(\"bbox, coor1 after eucl_sort() \\n\", bbox,\"\\n\", coor1)\n elif len(bbox) == len(coor1) and (len(bbox) > 0 and len(coor1) > 0):\n coor1, bbox = eucl_sort(coor1, bbox)\n # print(\"bbox, coor1 after eucl_sort() \\n\", bbox, \"\\n\", coor1)\n else:\n myflag = True\n coor1, bbox = eucl_sort_add(coor1, bbox)\n tmp_bbox = bbox\n else: # when working for first frame\n if Cam2_flag == 0: # if it is first camera\n tmp_id = 0\n print(\"Frames before renaming: bbox \\n\", bbox)\n if len(bbox) > 0:\n for l in range(len(bbox)):\n bbox[l][1] = tmp_id\n tmp_id += 1\n print(\"Frames after renaming: bbox \\n\", bbox)\n else:\n pass\n print(\"coor1, myflag after eucl before imshow(): \\n\", coor1, \"\\n\", myflag)\n if len(bbox) > 0:\n for i in range(len(bbox)):\n myRect(img2, bbox, i) # Generating bboxes on an image\n cv2.imshow(\"Label Editor\", img2)\n if myflag:\n try:\n bbox = bbox[:len(coor1)]\n except IndexError:\n print(\"Index Error\")\n break\n rm_labels = []\n return img2\n\n ############ Removing function ################################\n def roiCUT(self, img1, img2):\n # img1 - input image containing bboxes for removal\n # img2 - image with no bboxes and to copy ROI from\n global buffer, bbox\n target = []\n img = img1\n buffer = []\n # rois = []\n while True:\n r = cv2.selectROI(\"Label Editor\", img, fromCenter=False, showCrosshair=True)\n x1 = int(r[0]) # top\n y1 = int(r[1]) # left\n x2 = int(r[0] + r[2]) # bottom\n y2 = int(r[1] + r[3]) # right\n imgCrop = img2[y1:y2, x1:x2]\n # rois.append([y1, y2, x1, x2])\n target.append([x1, y1, x2, y2])\n print(\"Area selected for cutting(erasing) and removing the bboxes inside:\\n\", [x1, y1, x2, y2])\n buffer.append(imgCrop)\n img4 = img2.copy()\n img[y1:y2, x1:x2] = img2[y1:y2, x1:x2]\n bbox = euc_remove(bbox, target)\n centroid_xy = []\n for i in range(len(bbox)):\n img = myRect(img4, bbox, i)\n try:\n centroid_xy.append(int((bbox[i][2][0] + bbox[i][2][2]) / 2))\n centroid_xy.append(int((bbox[i][2][1] + bbox[i][2][3]) / 2))\n cv2.circle(img, (centroid_xy[0], centroid_xy[1]), 3, (0, 255, 0), 2)\n except IndexError:\n print(\"Index Error\")\n centroid_xy = []\n dispay_info(img, 1, \"Active\", counter_, frames_total)\n if cv2.waitKey(0) & 0xff == 27:\n # bbox = euc_remove(bbox, target)\n break\n return img4\n\n\ndef detect_video(yolo, video_path, output_path=\"./OutputVid_.mp4\"):\n global bbox, bboxPrev, counter_, interval, frames_total, bboxNxt, out, intrpltd_box, coordif, final_xy, frameNum, myflag, tmp_bbox, intervalCoord, out2, randomCounter_, cam2_flag, output_path3\n\n final_xy = [] # final array for bbox coordinates = ground truth data\n intervalVid = [] # array for interval frames (skipped frames interpolation)\n\n try:\n default_path = './2020_0109_140236_NOR_FILE.AVI'\n if Cam2_flag == 0:\n print(\"Default input file path: \", default_path)\n while True:\n fastTrack2ndCam = int(ez.enterbox(\"Enter 1 if you have camera 1 output, otherwise enter 0.\"))\n if fastTrack2ndCam == 1:\n output_path3 = fileOpenClicked(default_path)\n video_path = output_path3\n Cam2_flag = 1\n break\n elif fastTrack2ndCam == 0:\n Cam2_flag = 0\n video_path = fileOpenClicked(default_path)\n break\n else:\n print(\"You entered something wrong. Please, enter 1 or 0 to proceed.\")\n if Cam2_flag == 1:\n if video_path[-8:-4] == \"left\":\n video_path2 = video_path[:-8] + \"right\" + video_path[-4:]\n else:\n video_path2 = video_path[:-9] + \"left\" + video_path[-4:]\n vid_new = cv2.VideoCapture(video_path2)\n if vid_new.isOpened():\n default_path = video_path2\n video_path = video_path2\n print(\"2nd camera input file: Input file path automatically selected: \", video_path)\n else:\n print(\n \"2nd camera input file: Input file path automatic selection failed. Openration is handed to user.\\n\")\n video_path = fileOpenClicked(default_path)\n else:\n raise IOError(\"Couldn't open webcam or video file\")\n except IOError:\n print(\"Video format error.\")\n except _tkinter.TclError:\n print(\"Video format error.\")\n\n title_ = output_path[:-4] + dtime.datetime.today().strftime('%Y%m%d%H%M')\n type_ = output_path[-4:]\n output_path2 = title_ + type_ # for output video and displaying interpolation results\n vid = cv2.VideoCapture(video_path)\n vid2 = cv2.VideoCapture(video_path)\n if not vid.isOpened():\n raise IOError(\"Couldn't open webcam or video\")\n video_FourCC = int(vid.get(cv2.CAP_PROP_FOURCC))\n video_fps = vid.get(cv2.CAP_PROP_FPS)\n frame_count_total = int(vid.get(cv2.CAP_PROP_FRAME_COUNT)) # total number of frames in a video file\n print(\"Video file duration: {0:<d} frames, {1:<.2f} seconds\\n\".format(frame_count_total, frame_count_total / 30.0))\n\n video_size = (int(vid.get(cv2.CAP_PROP_FRAME_WIDTH)),\n int(vid.get(cv2.CAP_PROP_FRAME_HEIGHT)))\n isOutput = True if output_path != \"\" else False\n if isOutput:\n # set the [video] output file write function\n # out = cv2.VideoWriter(output_path, cv2.VideoWriter_fourcc(*'XVID'), 30.0, video_size)\n # out = cv2.VideoWriter(output_path, cv2.VideoWriter_fourcc(*'mp4v'), 30.0, video_size)\n try:\n if video_path[-3:] == 'mp4' or video_path[-3:] == 'MP4':\n out2 = cv2.VideoWriter(output_path2, cv2.VideoWriter_fourcc(*'mp4v'), 30.0, video_size)\n\n elif video_path[-3:] == 'avi' or video_path[-3:] == 'AVI':\n out2 = cv2.VideoWriter(output_path2, cv2.VideoWriter_fourcc(*'XVID'), 30.0, video_size)\n else:\n print(\"Please check file format\", type(video_path), video_path[-4:], \"?\")\n except IOError:\n print(\"File format incorrect\")\n\n accum_time = 0\n curr_fps = 0\n fps = \"FPS: ??\"\n prev_time = timer()\n\n while True:\n return_value, frame = vid.read()\n if not return_value:\n print(\"Output video file is generated at:\", output_path2)\n print(\"---------------------------------------------------------------------------------------\\n\")\n if Cam2_flag == 1:\n print(\"2nd camera video labeling is finished\")\n print(\"Program finished the job.\\n\")\n elif Cam2_flag == 0:\n print(\"2nd camera video labeling is started\")\n else:\n print(\"Something else\")\n break\n image = Image.fromarray(frame)\n imgcopy = np.asarray(image).copy()\n imgcopy3 = imgcopy.copy()\n image = yolo.detect_image(image)\n result = np.asarray(image)\n curr_time = timer()\n exec_time = curr_time - prev_time\n prev_time = curr_time\n accum_time = accum_time + exec_time\n curr_fps = curr_fps + 1\n if accum_time > 1:\n accum_time = accum_time - 1\n fps = \"FPS: \" + str(curr_fps)\n curr_fps = 0\n coordif = []\n intervalCoord = []\n # Flag for image description-helpers:\n # disp_descriptions(image, flag_num, status, frame_counter, total_frame_count)\n # flag_num = 1-5 or else (\"Flag number is empty\"):\n # 1 => \"Yolo's result is displayed. Editing (removing) bbox is enabled\"\n # 2 => \"Editing bbox is finished. Manual labeling (drawing) is enabled\"\n # 3 => \"Labeling for current frame is finished (final result)\"\n # 4 => \"Replay of Camera 1\"\n # 5 => \"Replay of Camera 2\"\n # status => Active or Inactive\n ############ First interval ##################################\n\n if counter_ == 1:\n frame_counter = 0\n print(\"\\n\\n First_Frame\\n\\n\")\n result_tmp = result.copy()\n result2 = result.copy()\n cv2.namedWindow(\"Label Editor\", cv2.WINDOW_NORMAL)\n if Cam2_flag == 0:\n dispay_info(result2, 1, \"Active\", counter_,\n frame_count_total) # Adding text to result2. \"Yolo's result. Editing is enabled...\"\n elif Cam2_flag == 1:\n dispay_info(result_tmp, 1, \"Inactive\", counter_,\n frame_count_total) # Adding text to result2. \"Yolo's result. Editing is enabled...\"\n cv2.imshow(\"Label Editor\", result_tmp)\n cv2.namedWindow(\"AutoTracking Cam1\", cv2.WINDOW_NORMAL)\n camera1_tracker(output_path3, counter_, interval)\n vidtmp = cv2.VideoCapture(output_path3)\n vidtmp.set(cv2.CAP_PROP_POS_FRAMES, 0)\n _, frametmp = vidtmp.read()\n dispay_info(frametmp, 4, \"Inactive\", counter_,\n frame_count_total)\n cv2.imshow(\"AutoTracking Cam1\", frametmp)\n dispay_info(result2, 1, \"Active\", counter_,\n frame_count_total) # Adding text to result2. \"Yolo's result. Editing is enabled...\"\n imgcopy = yolo.roiCUT(result2, imgcopy)\n imgcopy2 = imgcopy.copy()\n dispay_info(imgcopy2, 2, \"Active\", counter_,\n frame_count_total) # Adding text to imgcopy to show updates. \"Drawing is enabled...\"\n cv2.imshow(\"Label Editor\", imgcopy2)\n result = yolo.drawRect(imgcopy2, imgcopy3)\n result_tmp = result.copy()\n dispay_info(result_tmp, 3, \"Active\", counter_,\n frame_count_total) # Adding text to imgcopy to show updates. \"Final result...\"\n cv2.imshow(\"Label Editor\", result_tmp)\n coor1 = bbox\n bbox = []\n cv2.waitKey(0) & 0xff\n\n ############ N-th interval ##################################\n\n elif (counter_ - 1) % interval == 0:\n print(\"\\n\\n\\n Interval_{} \\n\\n\\n\".format(int((counter_ - 1) / interval)))\n result2 = result.copy()\n result_tmp = result.copy()\n if Cam2_flag == 0:\n dispay_info(result2, 1, \"Active\", counter_,\n frame_count_total) # Adding text to result2. \"Yolo's result. Editing is enabled...\"\n if Cam2_flag == 1:\n dispay_info(result_tmp, 1, \"Inactive\", counter_,\n frame_count_total) # Adding text to result2. \"Yolo's result. Editing is enabled...\"\n cv2.imshow(\"Label Editor\", result_tmp)\n print(\"camera1_tracker(output_path3, frame_count_total, counter_, interval)\", output_path3,\n frame_count_total, counter_, interval)\n camera1_tracker(output_path3, counter_, interval)\n dispay_info(result2, 1, \"Active\", counter_,\n frame_count_total) # Adding text to result2. \"Yolo's result. Editing is enabled...\"\n imgcopy = yolo.roiCUT(result2, imgcopy)\n imgcopy2 = imgcopy.copy()\n dispay_info(imgcopy2, 2, \"Active\", counter_,\n frame_count_total) # Adding text to imgcopy to show updates. \"Drawing is enabled...\"\n # Displaying edited Yolo's result and labeling (drawing) enabled ---------------------------------------\n cv2.imshow(\"Label Editor\", imgcopy2)\n result = yolo.drawRect(imgcopy2, imgcopy3)\n result_tmp = result.copy()\n result_tmp2 = result.copy()\n dispay_info(result_tmp, 3, \"Active\", counter_,\n frame_count_total) # Adding text to imgcopy to show updates. \"Final result...\"\n cv2.imshow(\"Label Editor\", result_tmp)\n print(\"After drawRect(), bbox, coor1\\n\", bbox, \"\\n\", coor1)\n if counter_ == interval + 1:\n for i in range(interval):\n vid2.set(cv2.CAP_PROP_POS_FRAMES, i)\n _, frame2 = vid2.read()\n intervalVid.append(frame2)\n elif counter_ > interval + 1:\n for i in range(interval):\n vid2.set(cv2.CAP_PROP_POS_FRAMES, counter_ - interval - 1 + i)\n _, frame2 = vid2.read()\n intervalVid.append(frame2)\n if not myflag:\n try:\n for i in range(len(bbox)):\n dif = (np.subtract(bbox[i][2], coor1[i][2])) / interval\n coordif.append(dif)\n dif = []\n except IndexError:\n print(\"Index Error at generating dif distance, frameNum={}, 1st condition\".format(counter_))\n else:\n try:\n for i in range(len(bbox)):\n dif = (np.subtract(bbox[i][2], coor1[i][2])) / interval\n coordif.append(dif)\n dif = []\n except IndexError:\n print(\"Index Error at generating dif distance, frameNum={}, 2nd condition\".format(counter_))\n for i in range(interval):\n if len(bbox) > 0:\n for j in range(len(bbox)):\n try:\n intrpltd_box[2] = np.add(coor1[j][2], coordif[j] * i).astype('int16')\n intrpltd_box[1] = coor1[j][1]\n intrpltd_box[0] = frame_counter\n coorx.append(intrpltd_box)\n final_xy.append(intrpltd_box)\n intervalCoord.append(intrpltd_box)\n intrpltd_box = [0, 0, (0, 0, 0, 0)]\n except IndexError:\n print(\"Index Error at enerating intrpltd_box, frameNum={}\".format(counter_))\n frame_counter += 1\n else:\n pass\n randomCounter_ = counter_\n for l in range(interval):\n if len(bbox) > 0:\n for k in range(len(bbox)):\n # Generating bboxes on an image\n intervalVid[l] = myRect(intervalVid[l], intervalCoord, (l * len(bbox) + k))\n if isOutput:\n randomCounter_ += 1\n out2.write(intervalVid[l])\n dispay_info(result_tmp2, 3, \"Inactive\", counter_,\n frame_count_total) # Adding text to imgcopy to show updates. \"Final result...\"\n for m in range(interval):\n intervalVid_tmp = intervalVid\n try:\n if Cam2_flag == 1:\n cv2.namedWindow(\"AutoTracking Cam2\", cv2.WINDOW_NORMAL)\n if m + 1 == interval:\n dispay_info(intervalVid_tmp[m], 5, \"Inactive\", counter_ - interval + m + 1,\n frame_count_total)\n else:\n dispay_info(intervalVid_tmp[m], 5, \"Active\", counter_ - interval + m + 1,\n frame_count_total)\n cv2.imshow(\"AutoTracking Cam2\", intervalVid_tmp[m])\n else:\n cv2.namedWindow(\"AutoTracking Cam1\", cv2.WINDOW_NORMAL)\n if m + 1 == interval:\n dispay_info(intervalVid_tmp[m], 4, \"Inactive\", counter_ - interval + m + 1,\n frame_count_total)\n else:\n dispay_info(intervalVid_tmp[m], 4, \"Active\", counter_ - interval + m + 1,\n frame_count_total)\n cv2.imshow(\"AutoTracking Cam1\", intervalVid_tmp[m])\n cv2.imshow(\"Label Editor\", result_tmp2)\n except IndexError:\n print(\"Index Error at replay function frameNum={}\".format(counter_))\n cv2.waitKey(0) & 0xff\n intervalVid = []\n intervalCoord = []\n coor1 = bbox\n if myflag:\n coor1 = tmp_bbox\n tmp_bbox = []\n myflag = False\n bbox = []\n coordif = []\n # cv2.waitKey(0) & 0xff\n\n ############# Last interval ##################################\n elif (frame_count_total - counter_) < interval and counter_ == frame_count_total:\n print(\"\\n\\n\\n Last_Frame\\n\\n\\n\")\n result2 = result.copy()\n result_tmp = result.copy()\n\n if Cam2_flag == 0:\n dispay_info(result2, 1, \"Active\", counter_,\n frame_count_total) # Adding text to result2. \"Yolo's result. Editing is enabled...\")\n elif Cam2_flag == 1:\n dispay_info(result_tmp, 1, \"Inactive\", counter_,\n frame_count_total) # Adding text to result2. \"Yolo's result. Editing is enabled...\"\n cv2.imshow(\"Label Editor\", result_tmp)\n print(\"camera1_tracker(output_path3, frame_count_total, counter_, interval)\", output_path3,\n frame_count_total, counter_, interval)\n camera1_tracker(output_path3, counter_, interval)\n dispay_info(result2, 1, \"Active\", counter_,\n frame_count_total) # Adding text to result2. \"Yolo's result. Editing is enabled...\"\n imgcopy1 = yolo.roiCUT(result2, imgcopy)\n dispay_info(imgcopy1, 2, \"Active\", counter_,\n frame_count_total) # Adding text to imgcopy to show updates. \"Drawing is enabled...\"\n result = yolo.drawRect(imgcopy1, imgcopy)\n result_tmp = result.copy()\n result_tmp2 = result.copy()\n dispay_info(result_tmp, 3, \"Active\", counter_,\n frame_count_total) # Adding text to imgcopy to show updates. \"Final result\"\n cv2.imshow(\"Label Editor\", result_tmp)\n if frame_count_total % interval == 0:\n for i in range(interval):\n vid2.set(cv2.CAP_PROP_POS_FRAMES, counter_ - interval + i)\n _, frame2 = vid2.read()\n intervalVid.append(frame2)\n if len(bbox) > 0:\n for i in range(len(bbox)):\n try:\n dif = (np.subtract(bbox[i][2], coor1[i][2])) / interval\n coordif.append(dif)\n except IndexError:\n print(\"Index Error at generating dif distance, frameNum={}, 1st condition\".format(counter_))\n for i in range(interval):\n for j in range(len(bbox)):\n try:\n intrpltd_box[2] = np.add(coor1[j][2], coordif[j] * i).astype('int16')\n intrpltd_box[1] = coor1[j][1]\n intrpltd_box[0] = frame_counter\n coorx.append(intrpltd_box)\n final_xy.append(intrpltd_box)\n intervalCoord.append(intrpltd_box)\n intrpltd_box = [0, 0, (0, 0, 0, 0)]\n except IndexError:\n print(\"Index Error at generating intrpltd_box, frameNum={}, 1st condition\".format(\n counter_))\n frame_counter += 1\n else:\n print(\"No bounding boxes. Skipping to next interval\")\n randomCounter_ = counter_\n for l in range(interval):\n if len(bbox) > 0:\n for k in range(len(bbox)):\n # Generating bboxes on an image\n intervalVid[l] = myRect(intervalVid[l], intervalCoord, (l * len(bbox) + k))\n if isOutput:\n randomCounter_ += 1\n out2.write(intervalVid[l])\n dispay_info(result_tmp2, 3, \"Inactive\", counter_,\n frame_count_total) # Adding text to imgcopy to show updates. \"Final result\"\n for m in range(interval):\n intervalVid_tmp = intervalVid\n try:\n if Cam2_flag == 1:\n dispay_info(intervalVid_tmp[m], 5, \"Active\", counter_ - interval + m + 1,\n frame_count_total)\n cv2.imshow(\"AutoTracking Cam2\", intervalVid_tmp[m])\n else:\n dispay_info(intervalVid_tmp[m], 4, \"Active\", counter_ - interval + m + 1,\n frame_count_total)\n cv2.imshow(\"AutoTracking Cam1\", intervalVid_tmp[m])\n cv2.imshow(\"Label Editor\", result_tmp2) # Final result\n except IndexError:\n print(\"Index Error at replay function, frameNum={}, 1st condition\".format(counter_))\n cv2.waitKey(0) & 0xff\n intervalVid = []\n intervalCoord = []\n else:\n for i in range(frame_count_total % interval):\n vid2.set(cv2.CAP_PROP_POS_FRAMES, counter_ - (frame_count_total % interval) + i)\n _, frame2 = vid2.read()\n intervalVid.append(frame2)\n if len(bbox) > 0:\n for i in range(len(bbox)):\n try:\n dif = (np.subtract(bbox[i][2], coor1[i][2])) / (frame_count_total % interval)\n coordif.append(dif)\n except IndexError:\n print(\"Index Error at generating dif distance, frameNum={}, 2nd condition\".format(counter_))\n for i in range(frame_count_total % interval):\n for j in range(len(bbox)):\n try:\n intrpltd_box[2] = np.add(coor1[j][2], coordif[j] * i).astype('int16')\n intrpltd_box[1] = coor1[j][1]\n intrpltd_box[0] = frame_counter\n coorx.append(intrpltd_box)\n final_xy.append(intrpltd_box)\n intervalCoord.append(intrpltd_box)\n intrpltd_box = [0, 0, (0, 0, 0, 0)]\n except IndexError:\n print(\"Index Error at generating intrpltd_box, frameNum={}, 2nd condition\".format(\n counter_))\n frame_counter += 1\n randomCounter_ = counter_\n else:\n pass\n for l in range(frame_count_total % interval):\n if len(bbox) > 0:\n for k in range(len(bbox)):\n # Generating bboxes on an image\n intervalVid[l] = myRect(intervalVid[l], intervalCoord, (l * len(bbox) + k))\n if isOutput:\n randomCounter_ += 1\n out2.write(intervalVid[l])\n else:\n pass\n dispay_info(result_tmp2, 3, \"Inactive\", counter_,\n frame_count_total) # Adding text to imgcopy to show updates. \"Final result\"\n for m in range(frame_count_total % interval):\n intervalVid_tmp = intervalVid\n try:\n if Cam2_flag == 1:\n dispay_info(intervalVid_tmp[m], 5, \"Active\", counter_ - interval + m + 1,\n frame_count_total)\n cv2.imshow(\"AutoTracking Cam2\", intervalVid_tmp[m])\n else:\n dispay_info(intervalVid_tmp[m], 4, \"Active\", counter_ - interval + m + 1,\n frame_count_total)\n cv2.imshow(\"AutoTracking Cam1\", intervalVid_tmp[m])\n cv2.imshow(\"Label Editor\", result_tmp2)\n except IndexError:\n print(\"Index Error at replay function, frameNum={}, 2nd condition\".format(counter_))\n cv2.waitKey(0) & 0xff\n intervalVid = []\n intervalCoord = []\n # Adding the new objects\n if myflag:\n a = len(tmp_bbox) - len(coor1)\n print(\"len(bbox), len(coor1), len(tmp_bbox) ? \", len(bbox), len(coor1), len(tmp_bbox))\n print(\"Number of new objects ? \", a)\n for x in range(a):\n try:\n print(\"Added: \", tmp_bbox[-(a - x)])\n final_xy.append(tmp_bbox[-(a - x)])\n except IndexError:\n print(\"Index Error at adding new objects in last frame\")\n cv2.waitKey(0) & 0xff\n\n print(\"frame_count_total, counter_\", frame_count_total, counter_)\n if (counter_ == frame_count_total):\n print(\"\\nLabeling is finished.\\n\")\n print(\"WRITING TO FILE\")\n print(\"\\n\")\n write2File(final_xy)\n counter_ += 1\n # if isOutput:\n # out.write(result)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n Cam2_flag += 1\n if Cam2_flag == 1:\n counter_ = 1\n interval = 10\n frame_count_total = 0\n final_coor_name = \"./coordinates_.txt\"\n final_coor_name = final_coor_name[:-4] + dtime.datetime.today().strftime('%Y%m%d%H%M') + final_coor_name[-4:]\n coorx = []\n coor1 = [] # previous frame data\n\n frame_counter = 0\n intrpltd_box = [frame_counter, 0, (0, 0, 0, 0)] # temp variable for full data on one object\n output_path3 = output_path2\n detect_video(yolo, video_path, output_path=\"./OutputVid_.mp4\")\n yolo.close_session()\n" ]
[ [ "numpy.array", "numpy.add", "numpy.asarray", "numpy.random.seed", "numpy.random.shuffle", "numpy.subtract", "numpy.append", "numpy.expand_dims", "numpy.floor" ] ]
zhutchens1/inverse_transform_sampling
[ "496a124f7723bda4d9b5c439d94aabfb787d30a0" ]
[ "inverse_transform_sampling.py" ]
[ "import numpy as np\nfrom scipy.interpolate import interp1d\n\ndef inverse_transform_sampling(data, bins, nsamples):\n \"\"\"\n Extract random samples from a distribution\n using inverse transform sampling. This code\n uses a Univariate Spline (without smoothing)\n to extract the inverse CDF for an arbitrary\n continuous distribution.\n\n Parameters\n ------------------\n data : array_like\n 1D distribution to be sampled.\n bins : int or array_like\n Histogram bins for `data` (see np.histogram).\n nsamples : int\n Number of samples (>1) to be returned.\n\n Returns\n --------------------\n samples : np.array\n Samples according to the distribution of `data`.\n Length matches nsamples.\n \"\"\"\n hist, binedges = np.histogram(data, bins=bins, density=True)\n cum_values = np.zeros_like(binedges)\n cum_values[1:] = np.cumsum(hist*(binedges[1:]-binedges[:-1]))\n inversecdf = interp1d(cum_values, binedges)\n uval = np.random.rand(nsamples)\n samples = inversecdf(uval)\n return samples\n\n\n\nif __name__=='__main__':\n data = np.random.normal(loc=140,scale=26,size=1000)\n samples = inverse_transform_sampling(data, bins=40, nsamples=500)\n \n import matplotlib.pyplot as plt\n plt.figure()\n plt.hist(data, bins=40, label='Raw Data')\n plt.hist(samples, histtype='step', color='orange', linewidth=3, label='Samples')\n plt.legend(loc='best')\n plt.show() \n" ]
[ [ "numpy.histogram", "numpy.zeros_like", "scipy.interpolate.interp1d", "numpy.random.rand", "numpy.random.normal", "matplotlib.pyplot.legend", "matplotlib.pyplot.figure", "matplotlib.pyplot.hist", "numpy.cumsum", "matplotlib.pyplot.show" ] ]
Qinaty/input-aware-backdoor-attack-release
[ "ce897adf4a3ce0d2badbd2b53233561fee6c7db7" ]
[ "classifier_models/vgg.py" ]
[ "\"\"\"VGG11/13/16/19 in Pytorch.\"\"\"\nimport torch\nimport torch.nn as nn\n\n\ncfg = {\n \"VGG11\": [64, \"M\", 128, \"M\", 256, 256, \"M\", 512, 512, \"M\", 512, 512, \"M\"],\n \"VGG13\": [64, 64, \"M\", 128, 128, \"M\", 256, 256, \"M\", 512, 512, \"M\", 512, 512, \"M\"],\n \"VGG16\": [64, 64, \"M\", 128, 128, \"M\", 256, 256, 256, \"M\", 512, 512, 512, \"M\", 512, 512, 512, \"M\"],\n \"VGG19\": [64, 64, \"M\", 128, 128, \"M\", 256, 256, 256, 256, \"M\", 512, 512, 512, 512, \"M\", 512, 512, 512, 512, \"M\"],\n}\n\n\nclass VGG(nn.Module):\n def __init__(self, vgg_name):\n super(VGG, self).__init__()\n self.features = self._make_layers(cfg[vgg_name])\n self.classifier = nn.Linear(512, 10)\n\n def forward(self, x):\n out = self.features(x)\n out = out.view(out.size(0), -1)\n out = self.classifier(out)\n return out\n\n def _make_layers(self, cfg):\n layers = []\n in_channels = 3\n for x in cfg:\n if x == \"M\":\n layers += [nn.MaxPool2d(kernel_size=2, stride=2)]\n else:\n layers += [\n nn.Conv2d(in_channels, x, kernel_size=3, padding=1),\n nn.BatchNorm2d(x),\n nn.ReLU(inplace=True),\n ]\n in_channels = x\n layers += [nn.AvgPool2d(kernel_size=1, stride=1)]\n return nn.Sequential(*layers)\n\n\ndef test():\n net = VGG(\"VGG11\")\n x = torch.randn(2, 3, 32, 32)\n y = net(x)\n print(y.size())\n\n\n# test()\n" ]
[ [ "torch.nn.Linear", "torch.nn.MaxPool2d", "torch.nn.Sequential", "torch.nn.AvgPool2d", "torch.nn.BatchNorm2d", "torch.nn.ReLU", "torch.nn.Conv2d", "torch.randn" ] ]
adelabriere/matchms
[ "a580539e6db3f4f00e12097983b85b2d494159ba" ]
[ "matchms/similarity/CosineGreedy.py" ]
[ "from typing import Tuple\nimport numpy\nfrom matchms.typing import SpectrumType\nfrom .BaseSimilarity import BaseSimilarity\nfrom .spectrum_similarity_functions import collect_peak_pairs\nfrom .spectrum_similarity_functions import score_best_matches\n\n\nclass CosineGreedy(BaseSimilarity):\n \"\"\"Calculate 'cosine similarity score' between two spectra.\n\n The cosine score aims at quantifying the similarity between two mass spectra.\n The score is calculated by finding best possible matches between peaks\n of two spectra. Two peaks are considered a potential match if their\n m/z ratios lie within the given 'tolerance'.\n The underlying peak assignment problem is here solved in a 'greedy' way.\n This can perform notably faster, but does occasionally deviate slightly from\n a fully correct solution (as with the Hungarian algorithm, see\n :class:`~matchms.similarity.CosineHungarian`). In practice this will rarely\n affect similarity scores notably, in particular for smaller tolerances.\n\n For example\n\n .. testcode::\n\n import numpy as np\n from matchms import Spectrum\n from matchms.similarity import CosineGreedy\n\n reference = Spectrum(mz=np.array([100, 150, 200.]),\n intensities=np.array([0.7, 0.2, 0.1]))\n query = Spectrum(mz=np.array([100, 140, 190.]),\n intensities=np.array([0.4, 0.2, 0.1]))\n\n # Use factory to construct a similarity function\n cosine_greedy = CosineGreedy(tolerance=0.2)\n\n score = cosine_greedy.pair(reference, query)\n\n print(f\"Cosine score is {score['score']:.2f} with {score['matches']} matched peaks\")\n\n Should output\n\n .. testoutput::\n\n Cosine score is 0.83 with 1 matched peaks\n\n \"\"\"\n # Set key characteristics as class attributes\n is_commutative = True\n # Set output data type, e.g. (\"score\", \"float\") or [(\"score\", \"float\"), (\"matches\", \"int\")]\n score_datatype = [(\"score\", numpy.float64), (\"matches\", \"int\")]\n\n def __init__(self, tolerance: float = 0.1, mz_power: float = 0.0,\n intensity_power: float = 1.0):\n \"\"\"\n Parameters\n ----------\n tolerance:\n Peaks will be considered a match when <= tolerance apart. Default is 0.1.\n mz_power:\n The power to raise m/z to in the cosine function. The default is 0, in which\n case the peak intensity products will not depend on the m/z ratios.\n intensity_power:\n The power to raise intensity to in the cosine function. The default is 1.\n \"\"\"\n self.tolerance = tolerance\n self.mz_power = mz_power\n self.intensity_power = intensity_power\n\n def pair(self, reference: SpectrumType, query: SpectrumType) -> Tuple[float, int]:\n \"\"\"Calculate cosine score between two spectra.\n\n Parameters\n ----------\n reference\n Single reference spectrum.\n query\n Single query spectrum.\n\n Returns\n -------\n Score\n Tuple with cosine score and number of matched peaks.\n \"\"\"\n def get_matching_pairs():\n \"\"\"Get pairs of peaks that match within the given tolerance.\"\"\"\n matching_pairs = collect_peak_pairs(spec1, spec2, self.tolerance,\n shift=0.0, mz_power=self.mz_power,\n intensity_power=self.intensity_power)\n if matching_pairs is None:\n return None\n matching_pairs = matching_pairs[numpy.argsort(matching_pairs[:, 2])[::-1], :]\n return matching_pairs\n\n spec1 = reference.peaks.to_numpy\n spec2 = query.peaks.to_numpy\n matching_pairs = get_matching_pairs()\n if matching_pairs is None:\n return numpy.asarray((float(0), 0), dtype=self.score_datatype)\n score = score_best_matches(matching_pairs, spec1, spec2,\n self.mz_power, self.intensity_power)\n return numpy.asarray(score, dtype=self.score_datatype)\n" ]
[ [ "numpy.asarray", "numpy.argsort" ] ]
maksimio/csi_classification
[ "b3f87e3de84f9e6d5f2ae34ea2d61e84a413553f" ]
[ "classification.py" ]
[ "from metawifi.df import wifilearn\nfrom metawifi import WifiDf, WifiLearn\nimport pandas as pd\nfrom matplotlib import pyplot as plt\nimport scipy\nimport seaborn as sns\n\n\nwd = WifiDf('./csi/use_in_paper/2_objects').set_type('abs')\n# wd = WifiDf('./csi/homelocation/three place').set_type('abs')\nx, y, z, a = wd.prep_featurespace()\ndf = pd.DataFrame(x)\ndf['target'] = y\n# print(x)\nsns.lmplot(x='skew_1', y='kurt_1', data=df, hue='target', fit_reg=False)\nsns.lmplot(x='skew_2', y='kurt_2', data=df, hue='target', fit_reg=False)\nsns.lmplot(x='skew_3', y='kurt_3', data=df, hue='target', fit_reg=False)\nsns.lmplot(x='std_1', y='mu42_1', data=df, hue='target', fit_reg=False)\n\nplt.show()\nexit()\nwl = WifiLearn(*wd.prep_csi()).fit_classic().print()\n\n\n# https://habr.com/ru/company/ods/blog/325422/" ]
[ [ "pandas.DataFrame", "matplotlib.pyplot.show" ] ]
qiuqiangkong/HEAR2021_Challenge_PANNs
[ "daae61a072d0102ef224e5c7c4038bf5960c43c5" ]
[ "panns_hear/panns.py" ]
[ "import torch\n\nfrom .models import Cnn14\n\n\ndef load_model(model_file_path, device=None):\n if device is None:\n device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n\n # Instantiate model\n model = Cnn14(\n sample_rate=32000,\n window_size=1024,\n hop_size=320,\n mel_bins=64,\n fmin=50,\n fmax=14000,\n classes_num=527,\n )\n model.to(device)\n\n # Set model weights using checkpoint file\n checkpoint = torch.load(model_file_path, map_location=device)\n model.load_state_dict(checkpoint['model'])\n\n model.sample_rate = 32000 # Input sample rate\n model.scene_embedding_size = 2048\n model.timestamp_embedding_size = 2048\n\n return model\n\n\ndef get_scene_embeddings(x, model):\n\n audio_length = x.shape[1]\n minimum_length = 32000\n\n if audio_length < minimum_length:\n batch_size = x.shape[0]\n device = x.device\n x = torch.cat((x, torch.zeros(batch_size, minimum_length - audio_length).to(device)), dim=1)\n\n with torch.no_grad():\n model.eval()\n embeddings = model(x)['embedding']\n \n return embeddings\n\n\ndef get_timestamp_embeddings(x, model):\n audio_length = x.shape[1]\n minimum_length = 32000\n\n if audio_length < minimum_length:\n batch_size = x.shape[0]\n device = x.device\n x = torch.cat((x, torch.zeros(batch_size, minimum_length - audio_length).to(device)), dim=1)\n\n with torch.no_grad():\n model.eval()\n sed_embeddings = model(x)['sed_embedding']\n \n batch_size, frames_num, embedding_size = sed_embeddings.shape\n \n time_steps = torch.arange(frames_num)[None, :] * 0.01 # (frames_num,)\n time_steps = time_steps.repeat(batch_size, 1) # (batch_size, frames_num)\n\n return sed_embeddings, time_steps\n" ]
[ [ "torch.zeros", "torch.arange", "torch.no_grad", "torch.cuda.is_available", "torch.load" ] ]
lamvng/Log-File-Analysis
[ "6870afe2b3bf143ca31cb4df191d208101ccfd80" ]
[ "predict.py" ]
[ "import argparse\nfrom tensorflow.keras.models import load_model\nfrom preprocess import load_file, process_data, feature_extract\nimport settings\nfrom numpy import unique\nimport json\nfrom datetime import datetime\nfrom termcolor import colored\n\n\nsettings.init()\n\n\ndef predict(df_test):\n print(colored('\\n[+] Loading pre-weighted model...\\n', 'green'))\n path = \"{}/saved_model/model.h5\".format(settings.root)\n loaded_model = load_model(path)\n\n # Load top columns\n top_columns = []\n with open(\"{}/results/most_important_features.txt\".format(settings.root), \"r\") as f:\n for line in f:\n column = line.split(':')[0]\n top_columns.append(column)\n\n # Load and process testing dataset\n df = process_data.encode(df_test, label_encoded_features=['protocol_type', 'service', 'flag'])\n df = process_data.normalize(df) # Normalize the test dataset\n df = feature_extract.create_dataset(df, top_columns) # Feature Extraction\n y_test = df['attack_type'] # Label # Series\n X_test = df.drop(['attack_type'], axis='columns') # Features # Dataframe\n\n # Predict\n y_predict = loaded_model.predict_classes(X_test, verbose=0)\n return y_predict\n\n\n# Output\ndef set_output_verbose(df_test, y_predict):\n for index, pred in enumerate(y_predict):\n if pred != 0:\n if pred == 1:\n print(colored(\"\\n[+] DoS warning:\\nPacket {}: {}, service: {}, flag: {}\".format(index, df_test.iloc[index]['protocol_type'], df_test.iloc[index]['service'], df_test.iloc[index]['flag']), 'red'))\n elif pred == 2:\n print(colored(\"\\n[+] Probing-Scanning warning:\\nPacket {}: {}, service: {}, flag: {}\".format(index, df_test.iloc[index]['protocol_type'], df_test.iloc[index]['service'], df_test.iloc[index]['flag']), 'red'))\n elif pred == 3:\n print(colored(\"\\n[+] User-to-Root Escalation warning:\\nPacket {}: {}, service: {}, flag: {}\".format(index, df_test.iloc[index]['protocol_type'], df_test.iloc[index]['service'], df_test.iloc[index]['flag']), 'red'))\n elif pred == 4:\n print(colored(\"\\n[+] Remote-to-Local Breach warning:\\nPacket {}: {}, service: {}, flag: {}\".format(index, df_test.iloc[index]['protocol_type'], df_test.iloc[index]['service'], df_test.iloc[index]['flag']), 'red'))\n\n\ndef set_output(df_test, y_predict):\n y_unique = unique(y_predict)\n if 1 in y_unique:\n print(colored('\\n[+] Warning: DoS packets detected!', 'red'))\n if 2 in y_unique:\n print(colored('\\n[+] Warning: Probing-Scanning activities detected!', 'red'))\n if 3 in y_unique:\n print(colored('\\n[+] Warning: User-to-Root Escalation detected!', 'red'))\n if 4 in y_unique:\n print(colored('\\n[+] Warning: Remote-to-Local Breach detected!', 'red'))\n\n\n# Output to file:\ndef output_to_json(df_test, y_predict):\n output = []\n for index, pred in enumerate(y_predict):\n if pred != 0:\n if pred == 1:\n attack_type = 'dos'\n elif pred == 2:\n attack_type = 'probe'\n elif pred == 3:\n attack_type = 'u2r'\n elif pred == 4:\n attack_type = 'r2l'\n dict = {\n \"id\": index,\n \"attack_type\": attack_type,\n \"protocol_type\": df_test.iloc[index]['protocol_type'],\n \"service\": df_test.iloc[index]['service'],\n \"flag\": df_test.iloc[index]['flag'],\n \"src_bytes\": int(df_test.iloc[index]['src_bytes']),\n \"dst_bytes\": int(df_test.iloc[index]['dst_bytes'])\n }\n output.append(dict)\n now = datetime.now()\n time = now.strftime(\"%Y-%m-%d_%H:%M:%S\")\n dump = json.dumps(output)\n loaded_dump = json.loads(dump)\n with open (\"{}/results/results_{}.json\".format(settings.root, time), \"w\") as json_file:\n json_file.write(dump)\n print(colored(\"\\n[+] Analysis output has been saved in JSON format.\\n\", \"green\"))\n\n\ndef output_to_csv(df_test, y_predict):\n now = datetime.now()\n time = now.strftime(\"%Y-%m-%d_%H:%M:%S\")\n with open (\"{}/results/results_{}.csv\".format(settings.root, time), \"w\") as csv_file:\n for index,pred in enumerate(y_predict):\n if pred != 0:\n if pred == 1:\n attack_type = 'dos'\n elif pred == 2:\n attack_type = 'probe'\n elif pred == 3:\n attack_type = 'u2r'\n elif pred == 4:\n attack_type = 'r2l'\n csv_file.write(\"{},{},{},{},{},{},{}\\n\".format(index,\n attack_type,\n df_test.iloc[index]['protocol_type'],\n df_test.iloc[index]['service'],\n df_test.iloc[index]['flag'],\n df_test.iloc[index]['src_bytes'],\n df_test.iloc[index]['dst_bytes']))\n print(colored(\"\\n[+] Analysis output has been saved in CSV format.\\n\", \"green\"))\n\n# Parser\nparser = argparse.ArgumentParser(description='Log file analyzer and classifier.')\nparser.add_argument('-f', '--file',\n help='Log file to analyze',\n required=True,\n choices=['sample_log_1.csv', 'sample_log_2.csv', 'sample_log_3.csv'])\n\nparser.add_argument('-v', '--verbose',\n help='Verbose mode',\n action='store_true')\n\nparser.add_argument('-o',\n '--output',\n help='Output type',\n choices=['csv', 'json'])\n\n\nargs = vars(parser.parse_args())\n\n\nsample_log = load_file.load_file(args['file'])\noutput = args['output']\nverbose = args['verbose']\n\n\ny_predict = predict(sample_log)\nsample_log_unencoded = load_file.load_file(args['file'])\n\n\n# Deal with verbose output\nif verbose:\n set_output_verbose(sample_log_unencoded, y_predict)\nelse:\n set_output(sample_log, y_predict)\n\n\n# Output to json file:\nif output == 'json':\n output_to_json(sample_log_unencoded, y_predict)\nelif output == 'csv':\n output_to_csv(sample_log_unencoded, y_predict)\n\n\nprint(colored(\"\\n[+] Analysis completed.\\n\", \"green\"))\n# conda activate mlds\n\n# python3 predict.py --file sample_log_2.csv\n# python3 predict.py --file sample_log_2.csv --verbose\n# python3 predict.py --file sample_log_2.csv --output json\n# python3 predict.py --file sample_log_2.csv --output csv" ]
[ [ "tensorflow.keras.models.load_model", "numpy.unique" ] ]
BlueWay-KU/Study
[ "a86405cdc3011eaed1b980b562b75df1e9ce90a8" ]
[ "DeepLearning/Python/Chapter 3/Ch03-04-01-network.py" ]
[ "import numpy as np\r\n\r\ndef sigmoid(x):\r\n return 1 / (1 + np.exp(-x))\r\n\r\nX = np.array([1.0, 0.5])\r\nW1 = np.array([[0.1, 0.3, 0.5], [0.2, 0.4, 0.6]])\r\nB1 = np.array([0.1, 0.2, 0.3])\r\n\r\nprint(W1.shape)\r\nprint(X.shape)\r\nprint(B1.shape)\r\n\r\nA1 = np.dot(X, W1) + B1\r\nZ1 = sigmoid(A1)\r\n\r\nprint(A1)\r\nprint(Z1)\r\n\r\nW2 = np.array([[0.1, 0.4], [0.2, 0.5], [0.3, 0.6]])\r\nB2 = np.array([0.1, 0.2])\r\n\r\nprint(Z1.shape)\r\nprint(W2.shape)\r\nprint(B2.shape)\r\n\r\nA2 = np.dot(Z1, W2) + B2\r\nZ2 = sigmoid(A2)\r\n\r\ndef identity_function(x):\r\n return x\r\n\r\nW3 = np.array([[0.1, 0.3], [0.2, 0.4]])\r\nB3 = np.array([0.1, 0.2])\r\n\r\nA3 = np.dot(Z2, W3) + B3\r\nY = identity_function(A3)\r\n" ]
[ [ "numpy.array", "numpy.dot", "numpy.exp" ] ]
maknotavailable/security-hub
[ "9c073b457fb871480db871d0665dbd7683940d25" ]
[ "src/detect_live.py" ]
[ "# import the necessary packages\nfrom imutils.video import VideoStream\nfrom imutils.video import FPS\nimport numpy as np\nimport imutils\nimport time\nimport cv2\nimport logging\n\n# Format logging\nlog = logging.getLogger(__name__)\nlogging.basicConfig(level=logging.INFO,\n format = '%(asctime)s - %(levelname)s - %(name)s - %(message)s')\n\nfp_deploy = '../model/MobileNetSSD_deploy.prototxt'\nfp_model = '../model/MobileNetSSD_deploy.caffemodel'\n\n# initialize the list of class labels MobileNet SSD was trained to\n# detect, then generate a set of bounding box colors for each class\nCLASSES = [\"background\", \"aeroplane\", \"bicycle\", \"bird\", \"boat\",\n\t\"bottle\", \"bus\", \"car\", \"cat\", \"chair\", \"cow\", \"diningtable\",\n\t\"dog\", \"horse\", \"motorbike\", \"person\", \"pottedplant\", \"sheep\",\n\t\"sofa\", \"train\", \"tvmonitor\"]\nCOLORS = np.random.uniform(0, 255, size=(len(CLASSES), 3))\n\n# load our serialized model from disk\nlog.info(\" loading model...\")\nnet = cv2.dnn.readNetFromCaffe(fp_deploy, fp_model)\n\n# initialize the video stream, allow the camera sensor to warm up,\n# and initialize the FPS counter\nlog.info(\" starting video stream...\")\nvs = VideoStream(src=0).start()\n# vs = VideoStream(usePiCamera=True).start()\ntime.sleep(2.0)\nfps = FPS().start()\n\n# loop over the frames from the video stream\nwhile True:\n\t# grab the frame from the threaded video stream and resize it\n\t# to have a maximum width of 400 pixels\n\tframe = vs.read()\n\tframe = imutils.resize(frame, width=400)\n\n\t# grab the frame dimensions and convert it to a blob\n\t(h, w) = frame.shape[:2]\n\tblob = cv2.dnn.blobFromImage(cv2.resize(frame, (300, 300)),\n\t\t0.007843, (300, 300), 127.5)\n\n\t# pass the blob through the network and obtain the detections and\n\t# predictions\n\tnet.setInput(blob)\n\tdetections = net.forward()\n\t# loop over the detections\n\tfor i in np.arange(0, detections.shape[2]):\n\t\t# extract the confidence (i.e., probability) associated with\n\t\t# the prediction\n\t\tconfidence = detections[0, 0, i, 2]\n\n\t\t# filter out weak detections by ensuring the `confidence` is\n\t\t# greater than the minimum confidence\n\t\tif confidence > 0.3:\n\t\t\t# extract the index of the class label from the\n\t\t\t# `detections`, then compute the (x, y)-coordinates of\n\t\t\t# the bounding box for the object\n\t\t\tidx = int(detections[0, 0, i, 1])\n\t\t\tbox = detections[0, 0, i, 3:7] * np.array([w, h, w, h])\n\t\t\t(startX, startY, endX, endY) = box.astype(\"int\")\n\n\t\t\t# draw the prediction on the frame\n\t\t\tlabel = \"{}: {:.2f}%\".format(CLASSES[idx],\n\t\t\t\tconfidence * 100)\n\t\t\tcv2.rectangle(frame, (startX, startY), (endX, endY),\n\t\t\t\tCOLORS[idx], 2)\n\t\t\ty = startY - 15 if startY - 15 > 15 else startY + 15\n\t\t\tcv2.putText(frame, label, (startX, y),\n\t\t\t\tcv2.FONT_HERSHEY_SIMPLEX, 0.5, COLORS[idx], 2)\n \t# show the output frame\n\tcv2.imshow(\"Frame\", frame)\n\tkey = cv2.waitKey(1) & 0xFF\n\n\t# if the `q` key was pressed, break from the loop\n\tif key == ord(\"q\"):\n\t\tbreak\n\n\t# update the FPS counter\n\tfps.update()\n\n# stop the timer and display FPS information\nfps.stop()\nlog.info(\" elapsed time: {:.2f}\".format(fps.elapsed()))\nlog.info(\" approx. FPS: {:.2f}\".format(fps.fps()))\n\n# do a bit of cleanup\ncv2.destroyAllWindows()\nvs.stop()" ]
[ [ "numpy.array", "numpy.arange" ] ]
spectre007/CCParser
[ "d48421ad0f178bfe7aa6ce93692858c86f44d1ed" ]
[ "ParserData.py" ]
[ "from . import constants as c\nimport numpy as np\nimport json\n\nclass Struct(object):\n \"\"\" Struct-like container object \"\"\"\n def __init__(self, **kwds): # keyword args define attribute names and values\n self.__dict__.update(**kwds)\n\nclass ParseContainer(object):\n \"\"\" Generic container object which keeps track of the parsed quantities.\n It allows to parse the same quantity several times.\n There should be one instance/parsed quantity. \"\"\"\n def __init__(self):\n self.nversion = 0\n self.data = []\n self.lines = []\n self.serializable = False\n\n @classmethod\n def from_obj(cls, line, parsed_obj):\n \"\"\"Alternative constructor. Initialize directly with line and parsed\n object.\n\n Parameters\n ----------\n line : int\n line number\n parsed_obj : any\n parsed object\n \"\"\"\n pc = cls()\n pc.add(line, parsed_obj)\n return pc\n\n def add(self, hook_line, new_obj):\n #self.data[hook_line] = new_pvalue\n self.data.append(new_obj)\n self.lines.append(hook_line)\n self.nversion += 1\n\n def get_first(self):\n idx = self.lines.index(min(self.lines))#not needed if assuming ordered parsing (line by line)\n #return self.data[0]\n return self.data[idx]\n\n def get_last(self):\n idx = self.lines.index(max(self.lines))#not needed if assuming ordered parsing (line by line)\n # return self.data[-1]\n return self.data[idx]\n\n def get_data(self):\n return self.data\n\n def get_lines(self):\n return self.lines\n\n def make_serializable(self):\n \"\"\"Turn fancy data types into sth that json.dump can recognize. \"\"\"\n try:\n dt = type(self.data[0])\n except IndexError:\n raise ParserDataError((\"ParseContainer not serializable (data list\"\n \" empty).\"))\n # take care of numpy data types\n if dt.__module__ == \"numpy\" or \"numpy.\" in dt.__module__:\n encoder = NumpyEncoder()\n self.data = [encoder.default(obj) for obj in self.data]\n # CCParser data types\n elif dt == MolecularOrbitals or dt == Amplitudes:\n self.data = [obj.encode() for obj in self.data]\n # assume other datatypes are serializable\n self.serializable = True\n\n def to_tuple(self):\n if self.serializable:\n return tuple(zip(self.data, self.lines))\n else:\n self.make_serializable()\n return tuple(zip(self.data, self.lines))\n\n def to_list(self):\n if self.serializable:\n return list(zip(self.data, self.lines))\n else:\n self.make_serializable()\n return list(zip(self.data, self.lines))\n\n def __len__(self):\n assert len(self.data) == len(self.lines)\n return len(self.data)\n\n def __getitem__(self, idx):\n if isinstance(idx, slice):\n return self.data[idx.start : idx.stop : idx.step]\n else:\n if idx >= len(self.data) or abs(idx) > len(self.data):\n raise IndexError(\"ParseContainer: Index out of range\")\n return self.data[idx]\n\n def __setitem__(self, idx, value):\n \"\"\" Setter method which expects value tuple (line, parsed_obj) \"\"\"\n self.lines[idx] = value[0]\n self.data[idx] = value[1]\n\n def __delitem__(self, idx):\n self.data.remove(idx)\n self.lines.remove(idx)\n\n def __iter__(self):\n return iter(self.data)\n\n# def __next__(self):\n# if self.n <= self.nversion:\n# return self.data[self.n]\n# else:\n# raise StopIteration\n\n def __contains__(self, line):\n if type(line) == str:\n line = int(line)\n return True if line in self.lines else False\n\n def __str__(self):\n s = \"\\n\"\n s+= \"Line\" + 3*\" \" + \"Parsed Value\\n\"\n for i in range(self.nversion):\n s+= str(self.lines[i]) + 3*\" \" + str(self.data[i]) + \"\\n\"\n return s\n\nclass ParserDataError(Exception):\n \"\"\"Raise for ParserData related errors. \"\"\"\n\nclass StructEncoder(json.JSONEncoder):\n def default(self, struct):\n if isinstance(struct, Struct):\n results = {}\n for label, pc in struct.__dict__.items():\n results[label] = pc.to_list()\n return results\n else:\n super().default(self, struct)\n\nclass NumpyEncoder(json.JSONEncoder):\n \"\"\" Special json encoder for numpy types \"\"\"\n def default(self, obj):\n if isinstance(obj, (np.int_, np.intc, np.intp, np.int8, np.int16,\n np.int32, np.int64, np.uint8, np.uint16, np.uint32,\n np.uint64)):\n return int(obj)\n elif isinstance(obj, (np.float_, np.float16, np.float32, np.float64)):\n return float(obj)\n elif isinstance(obj, (np.ndarray,)): #### This is the fix\n return obj.tolist()\n else:\n super().default(self, obj)\n\nclass MolecularOrbitals(object):\n # TODO: change name? \"OrbitalEnergies\"\n # TODO: add symmetries\n \"\"\" General molecular orbital class, which has more functionality than\n simple arrays.\n \"\"\"\n N_ORB_PER_LINE = 10\n\n def __init__(self, o, v):\n self.occ = list(map(float, o))\n self.virt = list(map(float, v))\n self.n_occ = len(o)\n self.n_virt = len(v)\n self.n_mo = self.n_occ + self.n_virt\n self.homo = max(self.occ ) if self.n_occ > 0 else 0\n self.lumo = min(self.virt) if self.n_virt > 0 else 0\n\n @classmethod\n def from_dict(cls, d):\n try:\n return cls(d[\"occ\"], d[\"virt\"])\n except (KeyError, TypeError) as e:\n raise ParserDataError((\"Dictionary not suitable to create \"\n \"MolecularOrbitals object.\"))\n\n #TODO: from_string method as implicit list conversion is not great\n\n @classmethod\n def from_tuples(cls, t):\n # find first occurrence of virt\n idx = next(t.index(i) for i in t if i[1] == \"virt\" or i[1] == \"v\")\n # create lists using the index\n o, dummy = zip(*t[:idx])\n v, dummy = zip(*t[idx:])\n return cls(o, v)\n\n def __str__(self):\n n1 = [i for i in range(1, self.n_occ+1)]\n n2 = [i for i in range(self.n_occ +1, self.n_mo+1)]\n s = \"\\n\"\n for i in range(0, len(self.occ), self.N_ORB_PER_LINE):\n s += 4*\" \" + \" \".join(\"{:>8}\".format(j) for j in n1[i:i+self.N_ORB_PER_LINE])+\"\\n\"\n if i == 0:\n s += \" occ: \" +' '.join(\"{:8.3f}\".format(j) for j in self.occ[i:i+self.N_ORB_PER_LINE])+\"\\n\"\n else:\n s += 6*\" \"+' '.join(\"{:8.3f}\".format(j) for j in self.occ[i:i+self.N_ORB_PER_LINE])+\"\\n\"\n s += 7*\" \"+88*\"-\"+\"\\n\"\n for i in range(0, len(self.virt), self.N_ORB_PER_LINE):\n s += 4*\" \" + \" \".join(\"{:>8}\".format(j) for j in n2[i:i+self.N_ORB_PER_LINE])+\"\\n\"\n if i == 0:\n s += \" virt:\" +' '.join(\"{:8.3f}\".format(j) for j in self.virt[i:i+self.N_ORB_PER_LINE])+\"\\n\"\n else:\n s += 6*\" \"+' '.join(\"{:8.3f}\".format(j) for j in self.virt[i:i+self.N_ORB_PER_LINE])+\"\\n\"\n return s\n\n def RVS(self, gap):\n \"\"\" Determine amount of virtual orbitals to freeze based on energy gap (in eV) \"\"\"\n if gap <= 0:\n raise ValueError(\"Negative or Zero energy gap not allowed for restriction of virtual space.\")\n else:\n thr = gap/c.Hartree2eV + self.homo\n# print(\"THR: \",thr)\n# print(\"N_VIRT: \", self.n_virt)\n idx = min(range(len(self.virt)), key=lambda i: abs(self.virt[i]-thr))\n freeze = self.n_virt - (idx +1)\n part_of_v = float(freeze)/float(self.n_virt)\n s = \"Index: {0:3d}, Number of frozen virtuals: {1:3d}, ({2:.1%})\".format(idx, freeze, part_of_v)\n print(s)\n\n def to_dict(self):\n return {\"occ\" : self.occ, \"virt\" : self.virt}\n\n def to_tuples(self):\n return list(zip(self.occ, [\"occ\" for i in range(self.n_occ )])) \\\n + list(zip(self.virt, [\"virt\" for i in range(self.n_virt)]))\n\n def encode(self, fmt=tuple):\n if fmt == tuple:\n return self.to_tuples()\n elif fmt == dict:\n return self.to_dict()\n else:\n raise ValueError(\"Export format not recognized.\")\n\nclass Amplitudes(object):\n \"\"\" General container for amplitudes of one state for easier access to and export of amplitude data \"\"\"\n def __init__(self, occ, virt, v, factor=1.0):\n self.occ = occ # list of lists, even if only single int in sublist\n self.virt= virt\n self.v = v\n self.factor = factor\n self.weights = list(map(lambda x: self.factor * x**2, self.v))\n self.print_thr = 0.05\n\n def __str__(self):\n s = \"Amplitudes: Weights > {0:.0%}\\n\".format(self.print_thr)\n for i in range(len(self.occ)):\n if self.weights[i] > self.print_thr:\n if len(self.occ[i]) == 1:\n s += \"{0:>4} -> {1:>4} : {2:.1f}\\n\".format(self.occ[i][0],\n self.virt[i][0], 100*self.weights[i])\n elif len(self.occ[i]) == 2:\n s += \"{0:>4}, {1:>4} -> {2:>4}, {3:>4} : {4:.1f}\\n\".format(\n self.occ[i][0], self.occ[i][1], self.virt[i][0],\n self.virt[i][1], 100*self.weights[i])\n return s\n\n @classmethod\n def from_list(cls, allinone, factor=1.0):\n \"\"\" Alternative constructor which expects single list.\n Format: [[occ_i, occ_j,..., virt_a, virt_b,..., ampl], ...] \"\"\"\n occ, virt, v = [], [], []\n for transition in allinone:\n assert(len(transition) % 2 != 0)\n n_mo = int((len(transition)-1)/2)\n occ.append(transition[0:n_mo])# slices yield list, even if only one element\n virt.append(transition[n_mo:-1])\n v.append(transition[-1])# index yields float\n return cls(occ, virt, v, factor)\n\n def to_dataframe(self, thresh=0.05):\n \"\"\" Converts the amplitude data to handy pandas.DataFrame object \"\"\"\n try:\n import pandas as pd\n except ImportError:\n raise ImportError(\"Module 'pandas' needed for 'Amplitudes.to_dataframe()' \")\n # TODO: improve this clunky part\n max_exc = max(list(map(len,self.occ)))\n occ, virt = [], []\n for i in range(len(self.occ)):\n occ.append(self.occ[i] + [0]*(max_exc - len(self.occ[i])))\n virt.append(self.virt[i] + [0]*(max_exc - len(self.virt[i])))\n idx_o = list(map(lambda x: \"occ_\"+str(x), [n for n in range(1,max_exc+1)]))\n idx_v = list(map(lambda x: \"virt_\"+str(x), [n for n in range(1,max_exc+1)]))\n df = pd.concat([pd.DataFrame(occ, columns=idx_o),\n pd.DataFrame(virt, columns=idx_v),\n pd.Series(self.weights, name=\"weight\")], axis=1)\n return df[(df[\"weight\"] > thresh)] # trim DataFrame based on awesome function\n\n def to_list(self):\n \"\"\" Return single list of amplitude data in the format:\n [[occ_i, occ_j,..., virt_a, virt_b,..., ampl], ...]\n \"\"\"\n ampl = []\n for i, v in enumerate(self.v):\n ampl.append(self.occ[i] + self.virt[i] + [v])\n return ampl\n\n def encode(self, fmt=list):\n if fmt == list:\n return self.to_list()\n# elif fmt == pd.DataFrame:\n# return self.to_dataframe()\n else:\n raise ValueError(\"Export format not recognized.\")\n\n" ]
[ [ "pandas.DataFrame", "pandas.Series" ] ]
andersonmarques/programacao_2_ufra
[ "94a22559eed817a429309d8da338431416608c0c" ]
[ "vetores_matrizes/q154.py" ]
[ "import numpy as np\n\nmatriz = np.random.rand(3,6)\n\nsoma_vendas = 0\nvalor_vendedor_top = 0\nvendedor_top = \"\"\n\nfor i in range(0, len(matriz)):\n for j in range(0, len(matriz[0])):\n soma_vendas += matriz[i][j]\n\n soma_vendedor = 0\n soma_vendedor += matriz[i][j]\n print(soma_vendedor)\n if soma_vendedor >= valor_vendedor_top:\n vendedor_top = f\"Vendedor {i+1}\"\n\nprint(np.round(matriz,2))\nprint('Soma de vendas: {:.2f}'.format(soma_vendas))\nprint(f'Vendedor top: {vendedor_top}')" ]
[ [ "numpy.round", "numpy.random.rand" ] ]
sparks-baird/piro
[ "3edb29c2bc9e3e4e64b91d89c815744d7db655d5" ]
[ "piro/route.py" ]
[ "import logging\n\nimport numpy as np\nimport plotly.express as px\nimport pandas as pd\nimport os\nimport json\n\nfrom pymatgen.core import Composition\nfrom pymatgen.analysis.phase_diagram import PhaseDiagram\nfrom pymatgen.util.string import latexify\nfrom piro.data import GASES, GAS_RELEASE, DEFAULT_GAS_PRESSURES\nfrom piro.mprester import get_mprester\nfrom piro.reactions import get_reactions\nfrom piro.settings import settings\nfrom piro.utils import get_epitaxies, get_similarities\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass SynthesisRoutes:\n def __init__(\n self,\n target_entry_id,\n confine_to_icsd=True,\n confine_to_stables=True,\n hull_distance=None,\n simple_precursors=False,\n explicit_includes=None,\n exclude_compositions=None,\n allow_gas_release=False,\n add_elements=None,\n flexible_competition=0,\n entries=None,\n epitaxies=None,\n similarities=None,\n sigma=2 * 6.242 * 0.01,\n transport_constant=10.0,\n custom_target_entry=None,\n confine_competing_to_icsd=False\n ):\n \"\"\"\n Synthesis reaction route recommendations, derived semi-empirically using the Classical Nucleation Theory\n and high-throughput DFT data (doi: 10.1021/jacs.1c04888). After instantiation, synthesis planning plots\n are generated using the recommend_routes method (See this method's arguments as well).\n Precursor library, epitaxial match and similarity metrics are precomputed upon instantiation,\n and can be cached.\n Args:\n target_entry_id (str): Materials Project entry id for target material\n confine_to_icsd (bool): Use ICSD-sourced entries to find precursors. Defaults to True.\n confine_to_stables (bool): Use stable entries only to find. Defaults to True.\n hull_distance (float): Use entries within this distance to hull (eV/atom). Can significantly increase\n number of possible precursors and slow down the predictions. Ignored if confine_to_stables is True.\n simple_precursors (bool or int): If True, or integer >0, precursors with fewer components will\n be considered. Defaults to False.\n explicit_includes (list): list of MP-ids to explicitly include. For example, confine_to_stables may exclude\n certain common precursors in some systems, if they are not on the convex-hull - this allows such\n potential precursors to be added to the library manually.\n exclude_compositions (list): list of compositions to avoid in precursor library. All entries at this\n composition are removed from the precursor library.\n allow_gas_release (bool): Many reactions require the release of gases like CO2, O2, etc. depending on the\n precursors, which requires explicitly considering them in balancing the reactions. Defaults to False.\n add_elements List(str): Add elements to the chemical space of libraries that doesn't exist in the target\n material. Best example is 'C', which would allow carbonates to be added to the precursor library.\n flexible_competition (int): This parameter specifies the depth of the competing phase search, and can help\n add more resolution to the phase competition axis of the recommendation plot.\n Defaults to 0, which would include only competing phases that have the same number of elements as the\n target. A reliable heuristic is setting it as 1, if x-axis of the plot is not informative.\n entries (list): List of Materials Project ComputedEntry objects, as can be obtained via the API. If provided\n these entries will be used while forming the precursor library. If not provided, MP database will be\n queried via their Rest API to get the most up-to-date entries. Defaults to None.\n epitaxies (dict): Dict of minimum matching areas between the target and entries, normally as computed\n via the get_epitaxies method. Recommended use is to leave as None.\n similarities (dict): Dict of similarity quantiles between the target and entries, normally as computed\n via the get_similarities method. Recommended use is to leave as None.\n sigma (float): surface energy constant (eV/Ang^2) to be used in predictions. Defaults to equivalent of\n 2.0 J/m^2.\n transport_constant (float): diffusion barrier coefficient (max barrier). Defaults to 10.0 eV.\n custom_target_entry (MP entry): custom ComputedEntry pymatgen object. It can be used to plan synthesis\n of a user-supplied compound that does not have a corresponding MP entry.\n allow_gas_release (bool): Many reactions require the release of gases like CO2, O2, etc. depending on the\n precursors, which requires explicitly considering them in balancing the reactions. Defaults to False.\n confine_competing_to_icsd (bool): Use ICSD-sourced entries to as competing compounds. Defaults to False.\n \"\"\"\n\n self.target_entry_id = target_entry_id\n self.confine_to_icsd = confine_to_icsd\n self.confine_to_stables = confine_to_stables\n self.simple_precursors = simple_precursors\n self.explicit_includes = explicit_includes if explicit_includes else []\n self.allow_gas_release = allow_gas_release\n self.temperature = None\n self.pressure = None\n self.add_elements = add_elements if add_elements else []\n self.entries = entries\n self.hull_distance = hull_distance\n self.confine_competing_to_icsd = confine_competing_to_icsd\n self.exclude_compositions = exclude_compositions\n self.custom_target_entry = custom_target_entry\n self.flexible_competition = flexible_competition if flexible_competition is not None else 0\n self._sigma = sigma if sigma is not None else 2 * 6.242 * 0.01\n self._transport_constant = transport_constant if transport_constant is not None else 10.0\n\n self.plot_data = None\n self.reactions = {}\n if not entries:\n if not custom_target_entry:\n with get_mprester() as mpr:\n _e = mpr.get_entry_by_material_id(self.target_entry_id)\n else:\n _e = custom_target_entry\n self.elts = list(_e.composition.as_dict().keys())\n if add_elements:\n self.elts.extend(add_elements)\n self.get_mp_entries()\n else:\n self.elts = list(self.target_entry.composition.as_dict().keys())\n\n self.get_precursor_library()\n print(\"Precursor library ready.\")\n self.epitaxies = epitaxies if epitaxies else get_epitaxies(\n self.precursor_library, self.target_entry\n )\n self.similarities = similarities if similarities else get_similarities(\n self.precursor_library, self.target_entry\n )\n\n self._reactions_objs = None\n\n @property\n def reactions_objs(self):\n if not self._reactions_objs:\n self._reactions_objs = get_reactions(\n self.target_entry,\n self.elts,\n self.precursor_library,\n self.allow_gas_release\n )\n logger.info(f\"Total # of balanced reactions obtained: {len(self.reactions)}\")\n return self._reactions_objs\n\n def get_mp_entries(self):\n with get_mprester() as mpr:\n self.entries = mpr.get_entries_in_chemsys(\n self.elts,\n inc_structure=\"final\",\n property_data=[\"icsd_ids\", \"formation_energy_per_atom\"],\n )\n for entry in self.entries:\n entry.structure.entry_id = entry.entry_id\n print(\"Total # of entries found in this chemistry: \", len(self.entries))\n\n @property\n def target_entry(self):\n if self.custom_target_entry:\n return self.custom_target_entry\n else:\n return [e for e in self.entries if e.entry_id == self.target_entry_id][0]\n\n def get_precursor_library(self):\n phased = PhaseDiagram(self.entries)\n if self.confine_to_stables:\n precursor_library = list(phased.stable_entries)\n elif self.hull_distance is not None:\n precursor_library = [\n e\n for e in self.entries\n if phased.get_e_above_hull(e) <= self.hull_distance\n ]\n else:\n precursor_library = [e for e in self.entries]\n if self.confine_to_icsd:\n precursor_library = [i for i in precursor_library if i.data[\"icsd_ids\"]]\n\n if self.simple_precursors:\n precursor_library = [\n i\n for i in precursor_library\n if len(i.composition.elements)\n < len(self.target_entry.composition.elements)\n - self.simple_precursors\n + 1\n ]\n\n if self.target_entry in precursor_library:\n precursor_library.pop(precursor_library.index(self.target_entry))\n\n if self.explicit_includes:\n print(\"explicitly including: \", self.explicit_includes)\n for entry_id in self.explicit_includes:\n try:\n entry = [e for e in self.entries if e.entry_id == entry_id][0]\n except IndexError:\n print(\"Could not find {} in entry list\".format(entry_id))\n continue\n if entry not in precursor_library:\n precursor_library.append(entry)\n\n if self.exclude_compositions:\n precursor_library = [\n i\n for i in precursor_library\n if i.composition.reduced_formula not in self.exclude_compositions\n ]\n\n self.precursor_library = precursor_library\n\n print(\n \"Total # of precursors materials obeying the provided filters: \",\n len(precursor_library),\n )\n return self.precursor_library\n\n @property\n def sigma(self):\n return self._sigma\n\n @property\n def transport_constant(self):\n return self._transport_constant\n\n def get_reactions_with_energies(self):\n reactions_dict = {}\n for r in self.reactions_objs:\n if r.label in reactions_dict:\n continue\n else:\n r.update_reaction_energy(\n self.temperature,\n self.pressure\n )\n r.update_nucleation_barrier(\n self.epitaxies,\n self.similarities,\n self.sigma,\n self.transport_constant\n )\n r.update_reaction_summary()\n r.update_competing_phases(\n self.entries,\n self.confine_competing_to_icsd,\n self.flexible_competition,\n self.allow_gas_release,\n self.temperature,\n self.pressure\n )\n reactions_dict[r.label] = r.as_dict()\n\n return reactions_dict\n\n def recommend_routes(\n self,\n temperature=298.0,\n pressure=DEFAULT_GAS_PRESSURES,\n max_component_precursors=0,\n show_fraction_known_precursors=True,\n show_known_precursors_only=False,\n display_peroxides=True,\n display_superoxides=True,\n w=None,\n h=None,\n xrange=None,\n yrange=None,\n add_pareto=False,\n custom_text=\"\",\n ):\n \"\"\"\n Synthesis reaction route recommendations, derived semi-empirically using the Classical Nucleation Theory\n and high-throughput DFT data (doi: 10.1021/jacs.1c04888). After instantiation, synthesis planning plots\n are generated using this method.\n Args:\n temperature (float): Temperature (in Kelvin) to consider in free energy adjustments for gases.\n pressure (dict or float): Gas pressures (in atm). If float, all gases are assumed to have the same constant\n pressure. A dictionary in the form of {'O2': 0.21, 'CO2':, 0.05} can be provided to explicitly\n specify partial pressures. Defaults to a default pressure dictionary pertaining to\n open atmosphere conditions.\n max_component_precursors (int): Used to limit the reactants to simpler sub-chemistries of our target to\n obtain a more refined candidate precursor list. If set, compounds with more unique elements than this\n limit are ignored as precursors. For example, for a ternary target compound, max_component_precursors=2\n would limit precursors to binary compounds (add_element is ignored, i.e. carbonated versions of binary\n compounds would also be included).\n show_known_precursors_only (bool): applies an additional filter to the precursor list during reaction\n generation to select only those phases text-mined by Kononova et al. (doi: 10.1038/s41597-019-0224-1)\n as solid-state precursors. Defaults to False.\n show_fraction_known_precursors (bool): can color-code the reactions based on what fraction of the precursors\n are in the above text-mined dataset. Defaults to True.\n display_peroxides (bool): whether reactions involving peroxides are included in the plot. Defaults to True.\n display_superoxides (bool): whether reactions involving superoxides are included in the plot.\n Defaults to True.\n w (int): width of the generated plot in pixels\n h (int): height of the generated plot in pixels\n xrange (tuple): sets the x-axis range\n yrange (tuple): sets the y-axis range\n add_pareto (bool): adds the Pareto front line to the plot.\n custom_text (str): text appended to the figure title.\n \"\"\"\n if not (self.pressure == pressure and self.temperature == temperature):\n self.temperature = temperature if temperature is not None else 298.0\n self.pressure = pressure if pressure is not None else DEFAULT_GAS_PRESSURES\n self.reactions = self.get_reactions_with_energies()\n\n self.check_if_known_precursors()\n\n self.plot_data = pd.DataFrame.from_dict(self.reactions, orient=\"index\")[\n [\n \"n_competing\",\n \"barrier\",\n \"summary\",\n \"energy\",\n \"enthalpy\",\n \"exp_precursors\",\n \"precursor_formulas\",\n ]\n ]\n if max_component_precursors:\n allowed_precursor_ids = [\n i.entry_id\n for i in self.precursor_library\n if len(set(i.composition.as_dict().keys()).difference(self.add_elements))\n <= max_component_precursors\n or i.composition.reduced_formula in GAS_RELEASE\n ]\n display_reactions = []\n for r in self.plot_data.index.to_list():\n if set(r.split(\"_\")).issubset(set(allowed_precursor_ids)):\n display_reactions.append(r)\n self.plot_data = self.plot_data.loc[display_reactions]\n\n if not display_peroxides:\n peroxides = {\n \"Li2O2\",\n \"K2O2\",\n \"BaO2\",\n \"Rb2O2\",\n \"Cs2O2\",\n \"Na2O2\",\n \"SrO2\",\n \"CaO2\",\n \"MgO2\",\n \"ZnO2\",\n \"CdO2\",\n \"HgO2\",\n }\n allowed_rows = []\n for i in range(len(self.plot_data)):\n if not peroxides.intersection(\n set(self.plot_data[\"precursor_formulas\"][i].tolist())\n ):\n allowed_rows.append((i))\n self.plot_data = self.plot_data.iloc[allowed_rows]\n\n if not display_superoxides:\n superoxides = {\"LiO2\", \"NaO2\", \"KO2\", \"RbO2\", \"CsO2\"}\n allowed_rows = []\n for i in range(len(self.plot_data)):\n if not superoxides.intersection(\n set(self.plot_data[\"precursor_formulas\"][i].tolist())\n ):\n allowed_rows.append((i))\n self.plot_data = self.plot_data.iloc[allowed_rows]\n\n color = \"exp_precursors\" if show_fraction_known_precursors else None\n\n if show_known_precursors_only:\n self.plot_data = self.plot_data[\n self.plot_data[\"exp_precursors\"].astype(float) == 1.0\n ]\n fig = px.scatter(\n self.plot_data,\n x=\"n_competing\",\n y=\"barrier\",\n hover_data=[\"summary\"],\n color=color,\n width=w,\n height=h,\n template=\"simple_white\",\n )\n for i in fig.data:\n i.marker.size = 10\n fig.update_layout(\n yaxis={\n \"title\": \"Nucleation barrier (a.u.)\",\n \"ticks\": \"inside\",\n \"mirror\": True,\n \"showline\": True,\n },\n xaxis={\n \"title\": \"Number of competing phases\",\n \"ticks\": \"inside\",\n \"mirror\": True,\n \"showline\": True,\n },\n font={\"size\": 13},\n title=r\"Target: \"\n + self.target_entry.structure.composition.reduced_formula\n + custom_text,\n title_font_size=15,\n title_x=0.5,\n )\n fig.update_traces(\n marker=dict(\n size=12, line=dict(width=2, color=\"DarkSlateGrey\"), opacity=0.8\n ),\n selector=dict(mode=\"markers\"),\n )\n if xrange:\n fig.update_xaxes(range=xrange)\n if yrange:\n fig.update_yaxes(range=yrange)\n\n if add_pareto:\n import plotly.graph_objects as go\n\n _pareto_data = self.topsis().loc[self.get_pareto_front()]\n _x = _pareto_data[\"n_competing\"]\n _y = _pareto_data[\"barrier\"]\n fig.add_trace(\n go.Scatter(\n x=_x,\n y=_y,\n line=dict(color=\"firebrick\", width=2)\n )\n )\n fig.add_trace(\n go.Scatter(\n x=[_x[0], _x[0], None, _x[-1], self.topsis()[\"n_competing\"].max()],\n y=[_y[0], self.topsis()[\"barrier\"].max(), None, _y[-1], _y[-1]],\n line=dict(color=\"firebrick\", width=2, dash=\"dash\"),\n connectgaps=False,\n )\n )\n\n fig.update_layout(showlegend=False)\n return fig\n\n def get_precursor_formulas(self, include_ids=True):\n if include_ids:\n return [\n (p.entry_id, p.composition.reduced_formula)\n for p in self.precursor_library\n ]\n else:\n return [p.composition.reduced_formula for p in self.precursor_library]\n\n def get_rxn_containing(self, formulas):\n \"\"\"\n Find reactions that contain all formulas given.\n Args:\n formulas: list of formulas. string okay if one formula.\n Returns:\n reaction details\n \"\"\"\n if isinstance(formulas, str):\n formulas = list(formulas)\n return sorted(\n [\n (\n self.reactions[i][\"barrier\"],\n self.reactions[i][\"summary\"],\n self.reactions[i][\"n_competing\"],\n i,\n )\n for i in self.reactions\n if all(\n [formula in self.reactions[i][\"summary\"] for formula in formulas]\n )\n ]\n )\n\n def check_if_known_precursors(self):\n with open(\n os.path.join(settings.rxn_files, \"experimental_precursors_KononovaSciData.json\"), \"r\"\n ) as f:\n exp_precursors = set(json.load(f))\n exp_precursors = exp_precursors.union(set(self.explicit_includes))\n\n for i in self.reactions:\n ids = [\n self.reactions[i][\"precursor_ids\"][j]\n for j in range(len(self.reactions[i][\"precursor_ids\"]))\n if self.reactions[i][\"precursor_formulas\"][j] not in GASES\n ]\n frac = len(set(ids).intersection(exp_precursors)) / len(ids)\n self.reactions[i][\"exp_precursors\"] = str(np.round(frac, decimals=4))\n\n def get_pareto_front(self):\n \"\"\"\n Returns: list of reaction labels on the pareto front\n \"\"\"\n x = self.plot_data[self.plot_data[\"barrier\"] < np.inf].sort_values(\n by=[\"n_competing\", \"barrier\"]\n )[[\"n_competing\", \"barrier\"]]\n y = x.groupby(by=[\"n_competing\"], as_index=False).min()\n rows = list(y.iterrows())\n front = []\n barrier_front = []\n for row in rows:\n n_competing = row[1][\"n_competing\"]\n barrier = row[1][\"barrier\"]\n if rows.index(row) == 0:\n front.append(\n x.index[\n (x[\"barrier\"] == barrier) & (x[\"n_competing\"] == n_competing)\n ][0]\n )\n barrier_front.append(barrier)\n continue\n if barrier < barrier_front[-1]:\n front.append(\n x.index[\n (x[\"barrier\"] == barrier) & (x[\"n_competing\"] == n_competing)\n ][0]\n )\n barrier_front.append(barrier)\n return front\n\n def topsis(self, latex=False):\n \"\"\"\n Returns a ranked list of reactions based on TOPSIS method for multiobjective optimization.\n Returns:\n \"\"\"\n x = self.plot_data[[\"n_competing\", \"barrier\"]]\n x = x[x[\"barrier\"] < np.inf]\n xsum = np.sqrt((x ** 2).sum())\n mu = x / xsum\n positive_ideal = mu.min()\n negative_ideal = mu.max()\n d_pos_ideal = np.sqrt(((mu - positive_ideal) ** 2).sum(axis=1))\n d_neg_ideal = np.sqrt(((mu - negative_ideal) ** 2).sum(axis=1))\n x[\"topsis_score\"] = d_neg_ideal / (d_pos_ideal + d_neg_ideal)\n x = x.sort_values(by=\"topsis_score\", ascending=False)\n result = self.plot_data.loc[x.index]\n result[\"topsis_score\"] = x[\"topsis_score\"]\n\n if latex:\n result[\"summary\"] = result[\"summary\"].apply(latexify)\n return result\n\n @staticmethod\n def get_material_id_from_formula(formula_str: str) -> str:\n with get_mprester() as mpr:\n options = mpr.query(\n {\"pretty_formula\": Composition(formula_str).reduced_formula},\n [\"material_id\", \"e_above_hull\"]\n )\n if not options:\n raise ValueError(\"{} query failed, please enter valid formula or mp id\".format(formula_str))\n options = sorted(options, key=lambda x: x[\"e_above_hull\"])\n return options[0][\"material_id\"]\n" ]
[ [ "pandas.DataFrame.from_dict", "numpy.round" ] ]
Lee-000/tensorbay-python-sdk
[ "63dee8fe43043d60ed1c85aa88b652ef23979925" ]
[ "docs/code/use_dataset_in_pytorch.py" ]
[ "#!/usr/bin/env python3\n#\n# Copyright 2021 Graviti. Licensed under MIT License.\n#\n\n# pylint: disable=pointless-string-statement\n# pylint: disable=wrong-import-position\n# pylint: disable=import-error\n# type: ignore\n\n\"\"\"This is the example code for using dataset in Pytorch.\"\"\"\n\n\n\"\"\"Build a Segment class\"\"\"\nfrom PIL import Image\nfrom torch.utils.data import DataLoader, Dataset\nfrom torchvision import transforms\n\nfrom tensorbay import GAS\nfrom tensorbay.dataset import Dataset as TensorBayDataset\n\n\nclass MNISTSegment(Dataset):\n \"\"\"class for wrapping a MNIST segment.\"\"\"\n\n def __init__(self, gas, segment_name, transform):\n super().__init__()\n self.dataset = TensorBayDataset(\"MNIST\", gas)\n self.segment = self.dataset[segment_name]\n self.category_to_index = self.dataset.catalog.classification.get_category_to_index()\n self.transform = transform\n\n def __len__(self):\n return len(self.segment)\n\n def __getitem__(self, idx):\n data = self.segment[idx]\n with data.open() as fp:\n image_tensor = self.transform(Image.open(fp))\n\n return image_tensor, self.category_to_index[data.label.classification.category]\n # \"\"\"\"\"\"\n\n\n\"\"\"Build a dataloader and run it\"\"\"\nACCESS_KEY = \"Accesskey-*****\"\n\nto_tensor = transforms.ToTensor()\nnormalization = transforms.Normalize(mean=[0.485], std=[0.229])\nmy_transforms = transforms.Compose([to_tensor, normalization])\n\ntrain_segment = MNISTSegment(GAS(ACCESS_KEY), segment_name=\"train\", transform=my_transforms)\ntrain_dataloader = DataLoader(train_segment, batch_size=4, shuffle=True, num_workers=4)\n\nfor index, (image, label) in enumerate(train_dataloader):\n print(f\"{index}: {label}\")\n\"\"\"\"\"\"\n" ]
[ [ "torch.utils.data.DataLoader" ] ]
elliehastings/ApptClassifier
[ "2152e45e5d8d262860fec2e5430cc2ef04749b73" ]
[ "classifier.py" ]
[ "## Imports\n\nimport csv, numpy, scipy\nfrom pandas import DataFrame, Series\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.metrics import confusion_matrix, f1_score\n\n## Functions\n\ndef load_data(path):\n ''' Accepts a two column csv file with text and label data and returns a Pandas DataFrame (training) or list (testing) '''\n rows = []\n with open(path, 'r') as csvfile:\n csvreader = csv.reader(csvfile)\n line_number = 0\n for row in csvreader:\n line_number += 1\n if line_number > 1:\n lines = {'text':row[0], 'class':row[1]}\n rows.append(lines)\n\n return DataFrame(rows)\n\ndef shuffle_data(data):\n ''' Accepts a DataFrame of training data and shuffles the rows '''\n return data.reindex(numpy.random.permutation(data.index))\n\ndef create_and_classify_with_pipeline(data, examples):\n '''Accepts training data, and testing data and returns predicted results'''\n pipeline = Pipeline([\n ('vectorizer', CountVectorizer(stop_words='english', ngram_range=(1,4))),\n ('classifier', MultinomialNB()) ])\n pipeline.fit(data['text'].values, data['class'].values)\n return pipeline.predict(examples) # ['label1','label2']\n\ndef write_predictions_to_file(y_examples, predicted_results, target_file_name):\n ''' Accepts an array of examples to classify and the predicted results and writes them to a csv file '''\n\n y_examples_array = numpy.array(y_examples, dtype=Series)\n\n with open(target_file_name, 'w') as csvfile:\n writer = csv.writer(csvfile)\n writer.writerow(['Text','Class'])\n for i in range(0, len(y_examples_array)):\n writer.writerow([y_examples_array[i], predicted_results[i]])\n\ndef run_classifier(training_data_file, testing_data_file, target_file_name):\n ''' Combines loading, classifier, and writing functions to run the classifier on a given set of files. '''\n # Note: An eventual refactor would be nice, especially to identify headers + labels themselves\n training_data = shuffle_data(load_data(training_data_file))\n testing_data = shuffle_data(load_data(testing_data_file))\n y_examples, y_results = testing_data['text'], testing_data['class']\n predicted_results = create_and_classify_with_pipeline(training_data, y_examples)\n f1_score_result = f1_score(y_results, predicted_results, pos_label='Urgent')\n print(\"F1 Score is: {}\".format(f1_score_result))\n write_predictions_to_file(y_examples, predicted_results, target_file_name)\n print(\"Wrote predictions to {}\".format(target_file_name))\n\n\n\n## Testing\n\ndef test_load_data():\n training_data = [{'text':'UBER | Actue | Dizziness',\n 'class':'Urgent'},\n {'text':'Discussing - has concerns and wants to talk about her fall ',\n 'class':'Not urgent'}]\n testing_data = [{'text':'PC: Rash FU ',\n 'class':'Not urgent'},\n {'text':'Acute | Chronic Cough',\n 'class':'Urgent'}]\n\n assert DataFrame(training_data).equals(load_data('data/test_training_data.csv'))\n\n assert DataFrame(testing_data).equals(load_data('data/test_testing_data.csv'))\n\ndef test_shuffle_data():\n test_dataframe = DataFrame([i for i in range(1,101)])\n shuffled_test_dataframe = shuffle_data(test_dataframe)\n try:\n shuffled_test_dataframe.iloc[0:5] != test_dataframe.iloc[0:5]\n raise AssertionError('Shuffled DataFrame equal to source DataFrame')\n except ValueError:\n pass\n\n\n####### Tests ######\n\ntest_load_data()\ntest_shuffle_data()\n\n####### Run #######\n\n#run_classifier('data/TrainingData_925_to_1022.csv', 'data/TestingData_925_to_1022.csv', 'data/output_predicted_results.csv')\n\nrun_classifier('data/TrainingData_Andrew.csv', 'data/TestingData_Andrew.csv', 'data/output_predicted_results_Andrew.csv')" ]
[ [ "numpy.array", "pandas.DataFrame", "numpy.random.permutation", "sklearn.naive_bayes.MultinomialNB", "sklearn.feature_extraction.text.CountVectorizer", "sklearn.metrics.f1_score" ] ]
Shui-Group/TargetDIA
[ "d697390728793c20dfe4426cce250c72b42cb0d2" ]
[ "models/pdeep2/model/similarity_calc.py" ]
[ "from scipy.stats.stats import pearsonr, spearmanr, kendalltau\nimport tensorflow as tf\nimport numpy as np\n\n\ndef cosine(v1, v2):\n return np.dot(v1, v2) / (np.linalg.norm(v1)*np.linalg.norm(v2))\n\n\ndef similarity(v1, v2):\n v1 = np.array(v1)\n v2 = np.array(v2)\n pcc = pearsonr(v1, v2)[0]\n cos = cosine(v1, v2)\n spc = spearmanr(v1, v2)[0]\n kdt = kendalltau(v1, v2)[0]\n return pcc, cos, spc, kdt\n\n\ndef CompareRNNPredict_buckets_tf(predict_buckets, real_buckets):\n sess = tf.Session(config=tf.ConfigProto(intra_op_parallelism_threads=2))\n pccs = []\n spcs = []\n coses = []\n kdts = []\n SAs = []\n \n _x = tf.placeholder('float', [None, ])\n _y = tf.placeholder('float', [None, ])\n _len = tf.placeholder(tf.int32,())\n \n def spearman(x, y):\n y_rank = tf.nn.top_k(y, k = _len, sorted=True, name='y_rank').indices\n x_rank = tf.nn.top_k(x, k = _len, sorted=True, name='x_rank').indices\n rank_diff = y_rank - x_rank\n rank_diff_sq_sum = tf.reduce_sum(rank_diff * rank_diff)\n six = tf.constant(6)\n one = tf.constant(1.0)\n numerator = tf.cast(six * rank_diff_sq_sum, dtype = tf.float32)\n divider = tf.cast(_len*_len*_len - _len, dtype = tf.float32)\n return one - numerator / divider\n \n def cosine(x, y):\n norm_x = tf.nn.l2_normalize(x,0)\n norm_y = tf.nn.l2_normalize(y,0)\n return tf.reduce_sum(tf.multiply(norm_x, norm_y))\n \n def pearson(x, y):\n x = x - tf.reduce_mean(x)\n y = y - tf.reduce_mean(y)\n return cosine(x, y)\n \n def spectral_angle(cos_val):\n return 1 - 2*tf.acos(cos_val)/np.pi\n\n _pcc = pearson(_x, _y)\n _cos = cosine(_x, _y)\n _SA = spectral_angle(_cos)\n\n def similarity_tf(v1, v2):\n ret_pcc, ret_cos, ret_SA = sess.run([_pcc, _cos, _SA], feed_dict = {_x:v1, _y:v2, _len:len(v1)})\n ret_spc = spearmanr(v1, v2)[0]\n ret_kdt = kendalltau(v1, v2)[0]\n return ret_pcc, ret_cos, ret_spc, ret_kdt, ret_SA\n \n for key, value in predict_buckets.items():\n predict = value[-1]\n predict[predict < 1e-4] = 0\n real = real_buckets[key][-1]\n ypred_seq = np.reshape(predict, (predict.shape[0], predict.shape[1] * predict.shape[2]), order='C')\n ytest_seq = np.reshape(real, (real.shape[0], real.shape[1] * real.shape[2]), order='C')\n tmp_pcc = []\n tmp_spc = []\n for i in range(len(predict)):\n pcc, cos, spc, kdt, SA = similarity_tf(ypred_seq[i], ytest_seq[i])\n tmp_pcc.append(pcc)\n tmp_spc.append(spc)\n pccs.append(pcc)\n spcs.append(spc)\n coses.append(cos)\n kdts.append(kdt)\n SAs.append(SA)\n print('[I] peplen = {}, size = {}, Median: pcc = {:.3f}, spc = {:.3f}'.format(key, len(predict), np.median(tmp_pcc), np.median(tmp_spc)))\n \n sess.close()\n \n pccs, coses, spcs, kdts, SAs = np.array(pccs), np.array(coses), np.array(spcs), np.array(kdts), np.array(SAs)\n out_median = \"[R] Median: pcc = {:.3f}, cos = {:.3f}, spc = {:.3f}, kdt = {:.3f}, SA = {:.3f}\".format(np.median(pccs), np.median(coses), np.median(spcs), np.median(kdts), np.median(SAs))\n out_mean = \"[R] Mean: pcc = {:.3f}, cos = {:.3f}, spc = {:.3f}, kdt = {:.3f}, SA = {:.3f}\".format(np.mean(pccs), np.mean(coses), np.mean(spcs), np.mean(kdts), np.mean(SAs))\n \n print(out_median)\n print(out_mean)\n return pccs, coses, spcs, kdts, SAs\n\n\ndef CompareRNNPredict_buckets(predict_buckets, real_buckets):\n pccs = []\n spcs = []\n coses = []\n kdts = []\n for key, value in predict_buckets.items():\n predict = value[-1]\n predict[predict < 1e-4] = 0\n real = real_buckets[key][-1]\n ypred_seq = np.reshape(predict, (predict.shape[0], predict.shape[1] * predict.shape[2]), order='C')\n ytest_seq = np.reshape(real, (real.shape[0], real.shape[1] * real.shape[2]), order='C')\n tmp_pcc = []\n tmp_spc = []\n for i in range(len(predict)):\n pcc, cos, spc, kdt = similarity(ypred_seq[i], ytest_seq[i])\n tmp_pcc.append(pcc)\n tmp_spc.append(spc)\n pccs.append(pcc)\n spcs.append(spc)\n coses.append(cos)\n kdts.append(kdt)\n print('[I] peplen = {}, size = {}, Median: pcc = {:.3f}, spc = {:.3f}'.format(key, len(predict), np.median(tmp_pcc), np.median(tmp_spc)))\n pccs, coses, spcs, kdts = np.array(pccs), np.array(coses), np.array(spcs), np.array(kdts)\n out_median = \"[R] Median: pcc = {:.3f}, cos = {:.3f}, spc = {:.3f}, kdt = {:.3f}\".format(np.median(pccs), np.median(coses), np.median(spcs), np.median(kdts))\n out_mean = \"[R] Mean: pcc = {:.3f}, cos = {:.3f}, spc = {:.3f}, kdt = {:.3f}\".format(np.mean(pccs), np.mean(coses), np.mean(spcs), np.mean(kdts))\n \n print(out_median)\n print(out_mean)\n return pccs, coses, spcs, kdts\n\n\ndef CompareRNNPredict(predict, real, peplens):\n print(\"predict shape\", predict.shape)\n ypred_seq = np.reshape(predict, (predict.shape[0], predict.shape[1] * predict.shape[2]), order='C')\n ytest_seq = np.reshape(real, (real.shape[0], real.shape[1] * real.shape[2]), order='C')\n pccs = []\n spcs = []\n coses = []\n kdts = []\n for i in range(len(predict)):\n # sim = pearsonr(np.reshape(predict[i,:(peplens[i]-1),:],-1), np.reshape(real[i,:(peplens[i]-1),:],-1))[0]\n pcc, cos, spc, kdt = similarity(ypred_seq[i][:(peplens[i]-1) * predict.shape[2]], ytest_seq[i][:(peplens[i]-1) * predict.shape[2]])\n pccs.append(pcc)\n spcs.append(spc)\n coses.append(cos)\n kdts.append(kdt)\n sims_nan = np.array(pccs)\n sims = sims_nan[np.isnan(sims_nan) == False]\n med = np.median(sims)\n mad = np.median(np.abs(sims - med))\n avg = np.mean(sims)\n std = np.std(sims)\n out_median = \" Median pcc = %.3f, MAD pcc = %.3f\" %(med, mad)\n out_mean = \" Mean pcc = %.3f, STD pcc = %.3f\" %(avg, std)\n print(out_median)\n print(out_mean)\n return np.array(pccs), np.array(coses), np.array(spcs), np.array(kdts)\n" ]
[ [ "numpy.dot", "numpy.median", "numpy.mean", "tensorflow.cast", "numpy.linalg.norm", "tensorflow.constant", "tensorflow.ConfigProto", "numpy.array", "numpy.reshape", "numpy.std", "tensorflow.placeholder", "tensorflow.reduce_sum", "tensorflow.nn.top_k", "tensorflow.acos", "scipy.stats.stats.spearmanr", "tensorflow.multiply", "numpy.isnan", "scipy.stats.stats.pearsonr", "numpy.abs", "scipy.stats.stats.kendalltau", "tensorflow.reduce_mean", "tensorflow.nn.l2_normalize" ] ]
braingineer/neural_tree_grammar
[ "e0534b733e9a6815e97e9ab28434dae7b94a632f" ]
[ "fergus/algorithms/linearizer/__main__.py" ]
[ "from __future__ import print_function, absolute_import, division\nfrom ..linearizer import run, run_dp\nfrom sqlitedict import SqliteDict as SD\nimport numpy as np\nimport time\nfrom . import utils\nimport sys\ntry:\n input = raw_input\nexcept:\n pass\n\ndef test():\n test_datum = (u'(ROOT(S(NP)(VP(VBD ratified)(NP))))',\n [(u'(NP(NNS workers))',\n [(u'(NP*(NNS communications))', []),\n (u'(NP*(DT the))', []),\n (u'(*NP(PP(IN of)(NP)))', [(u'(NP(NNP america))', [])])]),\n (u'(NP(NP)(CC and)(NP))',\n [(u'(NP(NN contract))',\n [(u'(NP*(JJ regional))', []),\n (u'(NP*(JJ new))', []),\n (u'(NP*(DT a))', [])]),\n (u'(NP(DT all))',\n [(u'(NP*(CC but))', []),\n (u'(NP*(CD one))', []),\n (u'(*NP(PP(IN of)(NP)))',\n [(u'(NP(NNS agreements))',\n [(u'(NP*(JJ local))', []),\n (u'(NP*(DT the))', []),\n (u'(*NP(PP(IN with)(NP)))',\n [(u'(NP(NNS bell_atlantic_corp))', [])])])])])]),\n (u'(*S(. .))', [])])\n run(test_datum)\n\n\ndef crap():\n datum = ( u'(ROOT(S(NP)(VP(VBD determined)(SBAR))))',\n [ ( u'(NP(NN panel))',\n [ (u'(NP*(JJ international))', []),\n (u'(NP*(DT an))', []),\n ( u'(*NP(VP(VBN set)))',\n [ (u'(VP*(IN up))', []),\n ( u'(*VP(PP(IN under)(NP)))',\n [ ( u'(NP(NNS rules))',\n [ (u'(NP*(DT the))', []),\n ( u'(*NP(PP(IN of)(NP)))',\n [ ( u'(NP(NN agreement))',\n [ (u'(NP*(JJ general))', []),\n (u'(NP*(DT the))', []),\n ( u'(*NP(PP(IN on)(NP)))',\n [ ( u'(NP(NN trade))',\n [ (u'(NP*(CC and))', []),\n ( u'(NP*(NNS tariffs))',\n [])])]),\n ( u'(*NP(PP(IN in)(NP)))',\n [(u'(NP(NNP geneva))', [])])])])])])])]),\n (u'(S*(, ,))', []),\n (u'(S*(ADVP(RB earlier)))', []),\n ( u'(SBAR(IN that)(S))',\n [ ( u'(S(NP)(VP(VBD violated)(NP)))',\n [ ( u'(NP(NNS restrictions))',\n [ (u'(NP*(CD fish-export))', []),\n (u'(NP*(JJ canadian))', []),\n (u'(NP*(JJ original))', []),\n (u'(NP*(DT the))', [])]),\n (u'(NP(NNS rules))', [(u'(NP*(NNP gatt))', [])])])]),\n (u'(*S(. .))', [])])\n return datum\n\nif __name__ == \"__main__\":\n import sys\n if len(sys.argv) == 1:\n db_path = '/home/cogniton/research/code/gist/gist/alternate_models/fergus616_dev_R.db'\n \n with SD(db_path, tablename='indata') as db:\n data = list(db.items())\n lens = [len(sentence.split(\" \")) for _, (_, sentence) in data]\n import scipy\n print(scipy.stats.describe(lens))\n \n #test()\n elif sys.argv[1] == \"forreal\":\n from tqdm import tqdm\n db_path = '/home/cogniton/research/code/gist/gist/alternate_models/fergus616_dev_R.db'\n with SD(db_path, tablename='indata') as db:\n data = list(db.items())\n capacitor = []\n for idx, (datum, sentence) in tqdm(data):\n if len(sentence.split(\" \")) > 40: continue\n capacitor.append((idx, sentence, run(datum, verbose=0, return_results=True)))\n if len(capacitor) > 10:\n with SD(\"saving_data.db\", tablename=\"outdata\") as db:\n for idx, sent, res in capacitor:\n db[idx] = (sent, res)\n db.commit()\n capacitor = []\n \n if len(capacitor) > 0:\n with SD(\"saving_data.db\", tablename=\"outdata\") as db:\n for idx, sent, res in capacitor:\n db[idx] = (sent, res)\n db.commit()\n capacitor = []\n \n elif sys.argv[1] == \"time\":\n from . import utils\n utils.level = 0\n db_path = '/home/cogniton/research/code/gist/gist/alternate_models/fergus616_dev_R.db'\n with SD(db_path, tablename='indata') as db:\n data = list(db.items())\n\n n = len(data)\n r_times = []\n s_times = []\n start = time.time()\n last = start\n import pprint\n #for idx in np.random.choice(np.arange(len(data)), 10, False):\n for idx in range(120, len(data)):\n #pprint.PrettyPrinter(indent=2).pprint(data[idx][1][0])\n datum_size = len(data[idx][1][1].split(\" \"))\n try:\n out, difficulty = run_dp(data[idx][1][0])\n except KeyboardInterrupt as e:\n print(\"caught keyboard\")\n print(idx, \"is the current index\")\n if input(\"continue or quit? (default continue)\") == \"quit\":\n sys.exit()\n else:\n continue\n except utils.MemoryException: \n print(\"bad index: \", idx)\n with open(\"watch_these.txt\", \"a\") as fp:\n fp.write(str(idx)+'\\n')\n continue\n now = time.time()\n r_times.append(now-start)\n s_times.append(now - last)\n est_r = r_times[-1] / (idx+1) * len(data)\n est_s = np.mean(s_times) * len(data)\n last = now\n print(\"idx<{}> --- word_len<{}> --- difficulty<{}> --- result_count<{}>\".format(idx, datum_size, difficulty, len(out[0])))\n print(\"\\t[tictoc. running<{:0.2f}> single<{:0.2f}>];\".format(r_times[-1], s_times[-1]), end='--')\n print(\"\\t[est time: running<{:0.2f}> single<{:0.2f}>]\".format(est_r, est_s))\n \n\n #print(data[idx][1][1])\n\n print(\"finished. {:0.2f} seconds\".format(time.time()-start))\n\n elif sys.argv[1] == \"debug\":\n from . import utils\n utils.level = 5\n datum = ( u'(ROOT(S(S)(VP(VBZ does)(VP))))',\n [ (u'(S*(WHNP(WP what)))', []),\n (u\"(*VP(RB n't))\", []),\n (u'(S(VP(VBP belong))(NP))', [(u'(NP(RB here))', [])]),\n (u'(*VP(. ?))', [])])\n import pprint\n pprint.PrettyPrinter(indent=2).pprint(datum)\n print(\"what does n't belong here ?\")\n run(datum)\n \n elif sys.argv[1] == \"dp\":\n from . import utils\n utils.level = 5\n datum = ( u'(ROOT(S(S)(VP(VBZ does)(VP))))',\n [ (u'(S*(WHNP(WP what)))', []),\n (u\"(*VP(RB n't))\", []),\n (u'(S(VP(VBP belong))(NP))', [(u'(NP(RB here))', [])]),\n (u'(*VP(. ?))', [])])\n import pprint\n pprint.PrettyPrinter(indent=2).pprint(datum)\n print(\"what does n't belong here ?\")\n run_dp(datum)\n \n elif sys.argv[1] == \"debugcrap\":\n from . import utils\n utils.level = 1\n datum = crap()\n import pprint\n pprint.PrettyPrinter(indent=2).pprint(datum)\n print(\"earlier , an international panel set up under the rules of the general agreement on tariffs and trade in geneva determined that the original canadian fish-export restrictions violated gatt rules .\")\n run(datum)\n " ]
[ [ "scipy.stats.describe", "numpy.mean" ] ]
wubinzzu/DeepRS
[ "1f2749d08df7a22e4b3a1c420d28ca19d8756629" ]
[ "deepRS/models/xdeepfm.py" ]
[ "# -*- coding:utf-8 -*-\n\"\"\"\nAuthor:\n Weichen Shen,[email protected]\n\nReference:\n [1] Lian J, Zhou X, Zhang F, et al. xDeepFM: Combining Explicit and Implicit Feature Interactions for Recommender Systems[J]. arXiv preprint arXiv:1803.05170, 2018.(https://arxiv.org/pdf/1803.05170.pdf)\n\"\"\"\nfrom tensorflow.python.keras.layers import Dense, Concatenate, Flatten, add, Reshape\nfrom tensorflow.python.keras.models import Model\nfrom tensorflow.python.keras.regularizers import l2\nfrom deepctr.utils import get_input, get_share_embeddings\nfrom deepctr.layers import PredictionLayer, MLP, CIN\n\n\ndef xDeepFM(feature_dim_dict, embedding_size=8, hidden_size=(256, 256), cin_layer_size=(128, 128,), cin_split_half=True, cin_activation='relu', l2_reg_linear=0.00001, l2_reg_embedding=0.00001, l2_reg_deep=0, init_std=0.0001, seed=1024, keep_prob=1, activation='relu', final_activation='sigmoid', use_bn=False):\n \"\"\"Instantiates the xDeepFM architecture.\n\n :param feature_dim_dict: dict,to indicate sparse field and dense field like {'sparse':{'field_1':4,'field_2':3,'field_3':2},'dense':['field_4','field_5']}\n :param embedding_size: positive integer,sparse feature embedding_size\n :param hidden_size: list,list of positive integer or empty list, the layer number and units in each layer of deep net\n :param cin_layer_size: list,list of positive integer or empty list, the feature maps in each hidden layer of Compressed Interaction Network\n :param cin_split_half: bool.if set to True, half of the feature maps in each hidden will connect to output unit\n :param cin_activation: activation function used on feature maps\n :param l2_reg_linear: float. L2 regularizer strength applied to linear part\n :param l2_reg_embedding: L2 regularizer strength applied to embedding vector\n :param l2_reg_deep: L2 regularizer strength applied to deep net\n :param init_std: float,to use as the initialize std of embedding vector\n :param seed: integer ,to use as random seed.\n :param keep_prob: float in (0,1]. keep_prob used in deep net\n :param activation: Activation function to use in deep net\n :param final_activation: str,output activation,usually ``'sigmoid'`` or ``'linear'``\n :param use_bn: bool. Whether use BatchNormalization before activation or not.in deep net\n :return: A Keras model instance.\n \"\"\"\n if not isinstance(feature_dim_dict, dict) or \"sparse\" not in feature_dim_dict or \"dense\" not in feature_dim_dict:\n raise ValueError(\n \"feature_dim must be a dict like {'sparse':{'field_1':4,'field_2':3,'field_3':2},'dense':['field_5',]}\")\n sparse_input, dense_input = get_input(feature_dim_dict, None)\n sparse_embedding, linear_embedding, = get_share_embeddings(feature_dim_dict, embedding_size, init_std, seed, l2_reg_embedding,\n l2_reg_linear)\n\n embed_list = [sparse_embedding[i](sparse_input[i])\n for i in range(len(sparse_input))]\n linear_term = [linear_embedding[i](sparse_input[i])\n for i in range(len(sparse_input))]\n if len(linear_term) > 1:\n linear_term = add(linear_term)\n elif len(linear_term) == 1:\n linear_term = linear_term[0]\n\n if len(dense_input) > 0:\n continuous_embedding_list = list(\n map(Dense(embedding_size, use_bias=False, kernel_regularizer=l2(l2_reg_embedding), ),\n dense_input))\n continuous_embedding_list = list(\n map(Reshape((1, embedding_size)), continuous_embedding_list))\n embed_list += continuous_embedding_list\n\n dense_input_ = dense_input[0] if len(\n dense_input) == 1 else Concatenate()(dense_input)\n linear_dense_logit = Dense(\n 1, activation=None, use_bias=False, kernel_regularizer=l2(l2_reg_linear))(dense_input_)\n linear_term = add([linear_dense_logit, linear_term])\n\n linear_logit = linear_term\n\n fm_input = Concatenate(axis=1)(embed_list) if len(\n embed_list) > 1 else embed_list[0]\n\n if len(cin_layer_size) > 0:\n exFM_out = CIN(cin_layer_size, cin_activation,\n cin_split_half, seed)(fm_input)\n exFM_logit = Dense(1, activation=None,)(exFM_out)\n\n deep_input = Flatten()(fm_input)\n deep_out = MLP(hidden_size, activation, l2_reg_deep, keep_prob,\n use_bn, seed)(deep_input)\n deep_logit = Dense(1, use_bias=False, activation=None)(deep_out)\n\n if len(hidden_size) == 0 and len(cin_layer_size) == 0: # only linear\n final_logit = linear_logit\n elif len(hidden_size) == 0 and len(cin_layer_size) > 0: # linear + CIN\n final_logit = add([linear_logit, exFM_logit])\n elif len(hidden_size) > 0 and len(cin_layer_size) == 0: # linear + Deep\n final_logit = add([linear_logit, deep_logit])\n elif len(hidden_size) > 0 and len(cin_layer_size) > 0: # linear + CIN + Deep\n final_logit = add([linear_logit, deep_logit, exFM_logit])\n else:\n raise NotImplementedError\n\n output = PredictionLayer(final_activation)(final_logit)\n model = Model(inputs=sparse_input + dense_input, outputs=output)\n return model\n" ]
[ [ "tensorflow.python.keras.layers.Concatenate", "tensorflow.python.keras.layers.add", "tensorflow.python.keras.layers.Flatten", "tensorflow.python.keras.regularizers.l2", "tensorflow.python.keras.layers.Dense", "tensorflow.python.keras.layers.Reshape", "tensorflow.python.keras.models.Model" ] ]
cattech-lab/lecture1_unimolecular_reaction
[ "6187983094ba282a606e50d756643b3e9c7484e8" ]
[ "euler_heat_transfer.py" ]
[ "import matplotlib.pyplot as plt\nimport csv\nimport math\n\n# parameter\ntemp = 100.0\nta = 20.0\n\nh = 400.0\n\ntime = 0.0\ndt = 0.1\n\nd = 0.01\nden = 7870.0\ncp = 442.0\narea = math.pi * d**2\nvol = math.pi * d**3 / 6.0 \nmass = den * vol\n\n# graph data array\ngtime = []\ngtemp = []\n\n# csv file\noutfile = open('output.csv','w', newline='')\nwriter = csv.writer(outfile)\nwriter.writerow(['i', 'time', 'temperature'])\n\n# time loop\nfor i in range(1000):\n ft = h * area * (ta - temp) / (cp * mass)\n temp = temp + dt * ft\n time = time + dt\n\n print('i: {0:4d}, time: {1:6.2f}, temp: {2:9.6f}'.format(i, time, temp))\n\n gtime.append(time)\n gtemp.append(temp)\n\n writer.writerow([i, time, temp])\n\noutfile.close()\n\n# graph plot\nplt.plot(gtime, gtemp)\nplt.xlabel('Time')\nplt.ylabel('Temperature')\nplt.legend(['T'])\nplt.show()\n" ]
[ [ "matplotlib.pyplot.xlabel", "matplotlib.pyplot.plot", "matplotlib.pyplot.legend", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.show" ] ]
osigaud/rex-gym
[ "cd2a1a333fba7d7e7ee3bf2165979dfda750ddda" ]
[ "rex_gym/envs/rex_gym_env.py" ]
[ "\"\"\"This file implements the gym environment of Rex.\n\n\"\"\"\nimport collections\nimport math\nimport time\nimport gym\nimport numpy as np\nimport pybullet\nimport pybullet_data\n\nfrom gym import spaces\nfrom gym.utils import seeding\n\nfrom ..model import rex, motor, mark_constants, rex_constants\nfrom ..model.terrain import Terrain\nfrom ..util import bullet_client\n\nMOTOR_ANGLE_OBSERVATION_INDEX = 0\nOBSERVATION_EPS = 0.01\nRENDER_HEIGHT = 360\nRENDER_WIDTH = 480\nSENSOR_NOISE_STDDEV = rex.SENSOR_NOISE_STDDEV\nDEFAULT_URDF_VERSION = \"default\"\nNUM_SIMULATION_ITERATION_STEPS = 300\n\nREX_URDF_VERSION_MAP = {\n DEFAULT_URDF_VERSION: rex.Rex\n}\n\n\ndef convert_to_list(obj):\n try:\n iter(obj)\n return obj\n except TypeError:\n return [obj]\n\n\nclass RexGymEnv(gym.Env):\n \"\"\"The gym environment for Rex.\n\n It simulates the locomotion of Rex, a quadruped robot. The state space\n include the angles, velocities and torques for all the motors and the action\n space is the desired motor angle for each motor. The reward function is based\n on how far Rex walks in 1000 steps and penalizes the energy\n expenditure.\n\n \"\"\"\n metadata = {\"render.modes\": [\"human\", \"rgb_array\"], \"video.frames_per_second\": 100}\n\n def __init__(self,\n debug=False,\n urdf_root=pybullet_data.getDataPath(),\n urdf_version=None,\n distance_weight=1.0,\n energy_weight=0.0005,\n shake_weight=0.005,\n drift_weight=2.0,\n distance_limit=float(\"inf\"),\n observation_noise_stdev=SENSOR_NOISE_STDDEV,\n self_collision_enabled=True,\n motor_velocity_limit=np.inf,\n pd_control_enabled=False,\n leg_model_enabled=True,\n accurate_motor_model_enabled=False,\n remove_default_joint_damping=False,\n motor_kp=2.0,\n motor_kd=0.03,\n control_latency=0.0,\n pd_latency=0.0,\n torque_control_enabled=False,\n motor_overheat_protection=False,\n hard_reset=True,\n on_rack=False,\n render=True,\n num_steps_to_log=1000,\n action_repeat=1,\n control_time_step=None,\n env_randomizer=None,\n forward_reward_cap=float(\"inf\"),\n reflection=True,\n log_path=None,\n target_orient=None,\n init_orient=None,\n target_position=None,\n start_position=None,\n base_y=0.0,\n base_z=0.0,\n base_roll=0.0,\n base_pitch=0.0,\n base_yaw=0.0,\n step_length=None,\n step_rotation=None,\n step_angle=None,\n step_period=None,\n backwards=None,\n signal_type=\"ik\",\n terrain_type=\"plane\",\n terrain_id=\"plane\",\n mark='base'):\n \"\"\" Initialize the rex gym environment.\n\n Args:\n urdf_root: The path to the urdf data folder.\n urdf_version: [DEFAULT_URDF_VERSION] are allowable\n versions. If None, DEFAULT_URDF_VERSION is used.\n distance_weight: The weight of the distance term in the reward.\n energy_weight: The weight of the energy term in the reward.\n shake_weight: The weight of the vertical shakiness term in the reward.\n drift_weight: The weight of the sideways drift term in the reward.\n distance_limit: The maximum distance to terminate the episode.\n observation_noise_stdev: The standard deviation of observation noise.\n self_collision_enabled: Whether to enable self collision in the sim.\n motor_velocity_limit: The velocity limit of each motor.\n pd_control_enabled: Whether to use PD controller for each motor.\n leg_model_enabled: Whether to use a leg motor to reparameterize the action\n space.\n accurate_motor_model_enabled: Whether to use the accurate DC motor model.\n remove_default_joint_damping: Whether to remove the default joint damping.\n motor_kp: proportional gain for the accurate motor model.\n motor_kd: derivative gain for the accurate motor model.\n control_latency: It is the delay in the controller between when an\n observation is made at some point, and when that reading is reported\n back to the Neural Network.\n pd_latency: latency of the PD controller loop. PD calculates PWM based on\n the motor angle and velocity. The latency measures the time between when\n the motor angle and velocity are observed on the microcontroller and\n when the true state happens on the motor. It is typically (0.001-\n 0.002s).\n torque_control_enabled: Whether to use the torque control, if set to\n False, pose control will be used.\n motor_overheat_protection: Whether to shutdown the motor that has exerted\n large torque (OVERHEAT_SHUTDOWN_TORQUE) for an extended amount of time\n (OVERHEAT_SHUTDOWN_TIME). See ApplyAction() in rex.py for more\n details.\n hard_reset: Whether to wipe the simulation and load everything when reset\n is called. If set to false, reset just place Rex back to start\n position and set its pose to initial configuration.\n on_rack: Whether to place Rex on rack. This is only used to debug\n the walk gait. In this mode, Rex's base is hanged midair so\n that its walk gait is clearer to visualize.\n render: Whether to render the simulation.\n num_steps_to_log: The max number of control steps in one episode that will\n be logged. If the number of steps is more than num_steps_to_log, the\n environment will still be running, but only first num_steps_to_log will\n be recorded in logging.\n action_repeat: The number of simulation steps before actions are applied.\n control_time_step: The time step between two successive control signals.\n env_randomizer: An instance (or a list) of EnvRandomizer(s). An\n EnvRandomizer may randomize the physical property of rex, change\n the terrrain during reset(), or add perturbation forces during step().\n forward_reward_cap: The maximum value that forward reward is capped at.\n Disabled (Inf) by default.\n log_path: The path to write out logs. For the details of logging, refer to\n rex_logging.proto.\n Raises:\n ValueError: If the urdf_version is not supported.\n \"\"\"\n self.mark = mark\n self.num_motors = mark_constants.MARK_DETAILS['motors_num'][self.mark]\n self.motor_velocity_obs_index = MOTOR_ANGLE_OBSERVATION_INDEX + self.num_motors\n self.motor_torque_obs_index = self.motor_velocity_obs_index + self.num_motors\n self.base_orientation_obs_index = self.motor_torque_obs_index + self.num_motors\n # Set up logging.\n self._log_path = log_path\n # @TODO fix logging\n self.logging = None\n # PD control needs smaller time step for stability.\n if control_time_step is not None:\n self.control_time_step = control_time_step\n self._action_repeat = action_repeat\n self._time_step = control_time_step / action_repeat\n else:\n # Default values for time step and action repeat\n if accurate_motor_model_enabled or pd_control_enabled:\n self._time_step = 0.002\n self._action_repeat = 5\n else:\n self._time_step = 0.01\n self._action_repeat = 1\n self.control_time_step = self._time_step * self._action_repeat\n # TODO: Fix the value of self._num_bullet_solver_iterations.\n self._num_bullet_solver_iterations = int(NUM_SIMULATION_ITERATION_STEPS / self._action_repeat)\n self._urdf_root = urdf_root\n self._self_collision_enabled = self_collision_enabled\n self._motor_velocity_limit = motor_velocity_limit\n self._observation = []\n self._true_observation = []\n self._objectives = []\n self._objective_weights = [distance_weight, energy_weight, drift_weight, shake_weight]\n self._env_step_counter = 0\n self._num_steps_to_log = num_steps_to_log\n self._is_render = render\n self._is_debug = debug\n self._last_base_position = [0, 0, 0]\n self._last_base_orientation = [0, 0, 0, 1]\n self._distance_weight = distance_weight\n self._energy_weight = energy_weight\n self._drift_weight = drift_weight\n self._shake_weight = shake_weight\n self._distance_limit = distance_limit\n self._observation_noise_stdev = observation_noise_stdev\n self._action_bound = 1\n self._pd_control_enabled = pd_control_enabled\n self._leg_model_enabled = leg_model_enabled\n self._accurate_motor_model_enabled = accurate_motor_model_enabled\n self._remove_default_joint_damping = remove_default_joint_damping\n self._motor_kp = motor_kp\n self._motor_kd = motor_kd\n self._torque_control_enabled = torque_control_enabled\n self._motor_overheat_protection = motor_overheat_protection\n self._on_rack = on_rack\n self._cam_dist = 1.0\n self._cam_yaw = 0\n self._cam_pitch = -30\n self._forward_reward_cap = forward_reward_cap\n self._hard_reset = True\n self._last_frame_time = 0.0\n self._control_latency = control_latency\n self._pd_latency = pd_latency\n self._urdf_version = urdf_version\n self._ground_id = None\n self._reflection = reflection\n self._env_randomizers = convert_to_list(env_randomizer) if env_randomizer else []\n # @TODO fix logging\n self._episode_proto = None\n if self._is_render:\n self._pybullet_client = bullet_client.BulletClient(connection_mode=pybullet.GUI)\n else:\n self._pybullet_client = bullet_client.BulletClient()\n if self._urdf_version is None:\n self._urdf_version = DEFAULT_URDF_VERSION\n self._pybullet_client.setPhysicsEngineParameter(enableConeFriction=0)\n self._signal_type = signal_type\n # gait inputs\n self.step_length = step_length\n self.step_rotation = step_rotation\n self.step_angle = step_angle\n self.step_period = step_period\n # poses inputs\n self._base_x = 0.01\n self._base_y = base_y\n self._base_z = base_z\n self._base_roll = base_roll\n self._base_pitch = base_pitch\n self._base_yaw = base_yaw\n # envs inputs\n self._target_orient = target_orient\n self._init_orient = init_orient\n self._target_position = target_position\n self._start_position = start_position\n # computation support params\n self._random_pos_target = False\n self._random_pos_start = False\n self._random_orient_target = False\n self._random_orient_start = False\n self._companion_obj = {}\n self._queue = collections.deque([\"base_y\", \"base_z\", \"roll\", \"pitch\", \"yaw\"])\n self._ranges = {\n \"base_x\": (-0.02, 0.02, 0.01),\n \"base_y\": (-0.007, 0.007, 0),\n \"base_z\": (-0.048, 0.021, 0),\n \"roll\": (-np.pi / 4, np.pi / 4, 0),\n \"pitch\": (-np.pi / 4, np.pi / 4, 0),\n \"yaw\": (-np.pi / 4, np.pi / 4, 0)\n }\n self.seed()\n self._backwards = backwards\n self._terrain_type = \"plane\"\n self._terrain_id = terrain_id\n self.reset()\n self._terrain_type = terrain_type\n self.terrain = Terrain(self._terrain_type, self._terrain_id)\n if self._terrain_type is not \"plane\":\n self.terrain.generate_terrain(self)\n observation_high = (self._get_observation_upper_bound() + OBSERVATION_EPS)\n observation_low = (self._get_observation_lower_bound() - OBSERVATION_EPS)\n action_dim = self.num_motors\n action_high = np.array([self._action_bound] * action_dim)\n self.action_space = spaces.Box(-action_high, action_high, dtype=np.float32)\n self.observation_space = spaces.Box(observation_low, observation_high, dtype=np.float32)\n self.viewer = None\n self._hard_reset = hard_reset # This assignment need to be after reset()\n self.env_goal_reached = False\n\n def close(self):\n # @TODO fix logger\n # if self._env_step_counter > 0:\n # self.logging.save_episode(self._episode_proto)\n self.rex.Terminate()\n\n def add_env_randomizer(self, env_randomizer):\n self._env_randomizers.append(env_randomizer)\n\n def reset(self, initial_motor_angles=None, reset_duration=1.0):\n self.env_goal_reached = False\n self._pybullet_client.configureDebugVisualizer(self._pybullet_client.COV_ENABLE_RENDERING, 0)\n # @TODO fix logger\n # if self._env_step_counter > 0:\n # self.logging.save_episode(self._episode_proto)\n # self._episode_proto = rex_logging_pb2.RexEpisode()\n # rex_logging.preallocate_episode_proto(self._episode_proto, self._num_steps_to_log)\n if self._hard_reset:\n self._pybullet_client.resetSimulation()\n self._pybullet_client.setPhysicsEngineParameter(\n numSolverIterations=int(self._num_bullet_solver_iterations))\n self._pybullet_client.setTimeStep(self._time_step)\n self._ground_id = self._pybullet_client.loadURDF(\"%s/plane.urdf\" % self._urdf_root)\n if self._reflection:\n self._pybullet_client.changeVisualShape(self._ground_id, -1, rgbaColor=[1, 1, 1, 0.8])\n self._pybullet_client.configureDebugVisualizer(\n self._pybullet_client.COV_ENABLE_PLANAR_REFLECTION, self._ground_id)\n self._pybullet_client.setGravity(0, 0, -10)\n acc_motor = self._accurate_motor_model_enabled\n motor_protect = self._motor_overheat_protection\n if self._urdf_version not in REX_URDF_VERSION_MAP:\n raise ValueError(\"%s is not a supported urdf_version.\" % self._urdf_version)\n else:\n self.rex = (REX_URDF_VERSION_MAP[self._urdf_version](\n pybullet_client=self._pybullet_client,\n action_repeat=self._action_repeat,\n urdf_root=self._urdf_root,\n time_step=self._time_step,\n self_collision_enabled=self._self_collision_enabled,\n motor_velocity_limit=self._motor_velocity_limit,\n pd_control_enabled=self._pd_control_enabled,\n accurate_motor_model_enabled=acc_motor,\n remove_default_joint_damping=self._remove_default_joint_damping,\n motor_kp=self._motor_kp,\n motor_kd=self._motor_kd,\n control_latency=self._control_latency,\n pd_latency=self._pd_latency,\n observation_noise_stdev=self._observation_noise_stdev,\n torque_control_enabled=self._torque_control_enabled,\n motor_overheat_protection=motor_protect,\n on_rack=self._on_rack,\n terrain_id=self._terrain_id,\n mark=self.mark))\n self.rex.Reset(reload_urdf=False,\n default_motor_angles=initial_motor_angles,\n reset_time=reset_duration)\n\n # Loop over all env randomizers.\n for env_randomizer in self._env_randomizers:\n env_randomizer.randomize_env(self)\n if self._terrain_type is not \"plane\":\n self.terrain.update_terrain()\n self._pybullet_client.setPhysicsEngineParameter(enableConeFriction=0)\n self._env_step_counter = 0\n self._last_base_position = [0, 0, 0]\n self._last_base_orientation = [0, 0, 0, 1]\n self._objectives = []\n self._pybullet_client.resetDebugVisualizerCamera(self._cam_dist, self._cam_yaw,\n self._cam_pitch, [0, 0, 0])\n self._pybullet_client.configureDebugVisualizer(self._pybullet_client.COV_ENABLE_RENDERING, 1)\n return self._get_observation()\n\n def seed(self, seed=None):\n self.np_random, seed = seeding.np_random(seed)\n return [seed]\n\n def _transform_action_to_motor_command(self, action):\n if len(action) != mark_constants.MARK_DETAILS['motors_num'][self.mark]:\n # extend with arm rest pose\n action = np.concatenate((action, rex_constants.ARM_POSES[\"rest\"]))\n return action\n\n def step(self, action):\n \"\"\"Step forward the simulation, given the action.\n\n Args:\n action: A list of desired motor angles for eight motors.\n\n Returns:\n observations: The angles, velocities and torques of all motors.\n reward: The reward for the current state-action pair.\n done: Whether the episode has ended.\n info: A dictionary that stores diagnostic information.\n\n Raises:\n ValueError: The action dimension is not the same as the number of motors.\n ValueError: The magnitude of actions is out of bounds.\n \"\"\"\n self._last_base_position = self.rex.GetBasePosition()\n self._last_base_orientation = self.rex.GetBaseOrientation()\n if self._is_render:\n # Sleep, otherwise the computation takes less time than real time,\n # which will make the visualization like a fast-forward video.\n time_spent = time.time() - self._last_frame_time\n self._last_frame_time = time.time()\n time_to_sleep = self.control_time_step - time_spent\n if time_to_sleep > 0:\n time.sleep(time_to_sleep)\n base_pos = self.rex.GetBasePosition()\n # Keep the previous orientation of the camera set by the user.\n [yaw, pitch, dist] = self._pybullet_client.getDebugVisualizerCamera()[8:11]\n self._pybullet_client.resetDebugVisualizerCamera(dist, yaw, pitch, base_pos)\n\n for env_randomizer in self._env_randomizers:\n env_randomizer.randomize_step(self)\n\n action = self._transform_action_to_motor_command(action)\n self.rex.Step(action)\n # print(\"rex step\")\n reward = self._reward()\n done = self._termination()\n # @TODO fix logging\n # if self._log_path is not None:\n # rex_logging.update_episode_proto(self._episode_proto, self.rex, action,\n # self._env_step_counter)\n self._env_step_counter += 1\n if done:\n self.rex.Terminate()\n print(\"done :\", self._env_step_counter)\n return np.array(self._get_observation()), reward, done, {'action': action}\n\n def render(self, mode=\"rgb_array\", close=False):\n if mode != \"rgb_array\":\n return np.array([])\n base_pos = self.rex.GetBasePosition()\n view_matrix = self._pybullet_client.computeViewMatrixFromYawPitchRoll(\n cameraTargetPosition=base_pos,\n distance=self._cam_dist,\n yaw=self._cam_yaw,\n pitch=self._cam_pitch,\n roll=0,\n upAxisIndex=2)\n proj_matrix = self._pybullet_client.computeProjectionMatrixFOV(fov=60,\n aspect=float(RENDER_WIDTH) / RENDER_HEIGHT,\n nearVal=0.1,\n farVal=100.0)\n (_, _, px, _, _) = self._pybullet_client.getCameraImage(\n width=RENDER_WIDTH,\n height=RENDER_HEIGHT,\n renderer=self._pybullet_client.ER_BULLET_HARDWARE_OPENGL,\n viewMatrix=view_matrix,\n projectionMatrix=proj_matrix)\n rgb_array = np.array(px)\n rgb_array = rgb_array[:, :, :3]\n return rgb_array\n\n def get_rex_motor_angles(self):\n \"\"\"Get the rex's motor angles.\n\n Returns:\n A numpy array of motor angles.\n \"\"\"\n return np.array(self._observation[MOTOR_ANGLE_OBSERVATION_INDEX:MOTOR_ANGLE_OBSERVATION_INDEX + self.num_motors])\n\n def get_rex_motor_velocities(self):\n \"\"\"Get the rex's motor velocities.\n\n Returns:\n A numpy array of motor velocities.\n \"\"\"\n return np.array(\n self._observation[self.motor_velocity_obs_index:self.motor_velocity_obs_index + self.num_motors])\n\n def get_rex_motor_torques(self):\n \"\"\"Get the rex's motor torques.\n\n Returns:\n A numpy array of motor torques.\n \"\"\"\n return np.array(\n self._observation[self.motor_torque_obs_index:self.motor_torque_obs_index + self.num_motors])\n\n def get_rex_base_orientation(self):\n \"\"\"Get the rex's base orientation, represented by a quaternion.\n\n Returns:\n A numpy array of rex's orientation.\n \"\"\"\n return np.array(self._observation[self.base_orientation_obs_index:])\n\n def is_fallen(self):\n \"\"\"Decide whether Rex has fallen.\n\n If the up directions between the base and the world is larger (the dot\n product is smaller than 0.85) or the base is very low on the ground\n (the height is smaller than 0.13 meter), rex is considered fallen.\n\n Returns:\n Boolean value that indicates whether rex has fallen.\n \"\"\"\n orientation = self.rex.GetBaseOrientation()\n rot_mat = self._pybullet_client.getMatrixFromQuaternion(orientation)\n local_up = rot_mat[6:]\n return np.dot(np.asarray([0, 0, 1]), np.asarray(local_up)) < 0.85\n\n def _termination(self):\n if self.is_fallen():\n print(\"FALLING DOWN!\")\n if self._out_of_trajectory():\n print(\"OUT OF TRAJECTORY!\")\n return self.is_fallen() or self.env_goal_reached or self._out_of_trajectory()\n\n @staticmethod\n def _out_of_trajectory():\n return False\n\n def _reward(self):\n current_base_position = self.rex.GetBasePosition()\n # observation = self._get_observation()\n # forward gait\n current_x = -current_base_position[0]\n if self._backwards:\n # backwards gait\n current_x = -current_x\n if self._target_position is not None:\n self._target_position = abs(self._target_position)\n # 0.15 tolerance\n if current_x > self._target_position + 0.15:\n forward_reward = self._target_position - current_x\n elif self._target_position <= current_x <= self._target_position + 0.15:\n forward_reward = 1.0\n # stationary reward must be null: tolerance 5%\n elif current_x <= 0.05:\n forward_reward = 0.0\n else:\n forward_reward = current_x / self._target_position\n else:\n # the far the better..\n forward_reward = current_x\n # Cap the forward reward if a cap is set.\n forward_reward = min(forward_reward, self._forward_reward_cap)\n # Penalty for sideways translation.\n # drift_reward = -abs(current_base_position[1] - self._last_base_position[1])\n drift_reward = -abs(current_base_position[1])\n # Penalty for sideways rotation of the body.\n orientation = self.rex.GetBaseOrientation()\n rot_matrix = pybullet.getMatrixFromQuaternion(orientation)\n local_up_vec = rot_matrix[6:]\n shake_reward = -abs(np.dot(np.asarray([1, 1, 0]), np.asarray(local_up_vec)))\n # shake_reward = -abs(observation[4])\n energy_reward = -np.abs(\n np.dot(self.rex.GetMotorTorques(),\n self.rex.GetMotorVelocities())) * self._time_step\n objectives = [forward_reward, energy_reward, drift_reward, shake_reward]\n weighted_objectives = [o * w for o, w in zip(objectives, self._objective_weights)]\n reward = sum(weighted_objectives)\n self._objectives.append(objectives)\n return reward\n\n def get_objectives(self):\n return self._objectives\n\n @property\n def objective_weights(self):\n \"\"\"Accessor for the weights for all the objectives.\n\n Returns:\n List of floating points that corresponds to weights for the objectives in\n the order that objectives are stored.\n \"\"\"\n return self._objective_weights\n\n def _get_observation(self):\n \"\"\"Get observation of this environment, including noise and latency.\n\n rex class maintains a history of true observations. Based on the\n latency, this function will find the observation at the right time,\n interpolate if necessary. Then Gaussian noise is added to this observation\n based on self.observation_noise_stdev.\n\n Returns:\n The noisy observation with latency.\n \"\"\"\n\n observation = []\n observation.extend(self.rex.GetMotorAngles().tolist())\n observation.extend(self.rex.GetMotorVelocities().tolist())\n observation.extend(self.rex.GetMotorTorques().tolist())\n observation.extend(list(self.rex.GetBaseOrientation()))\n self._observation = observation\n return self._observation\n\n def _get_true_observation(self):\n \"\"\"Get the observations of this environment.\n\n It includes the angles, velocities, torques and the orientation of the base.\n\n Returns:\n The observation list. observation[0:8] are motor angles. observation[8:16]\n are motor velocities, observation[16:24] are motor torques.\n observation[24:28] is the orientation of the base, in quaternion form.\n \"\"\"\n observation = []\n observation.extend(self.rex.GetTrueMotorAngles().tolist())\n observation.extend(self.rex.GetTrueMotorVelocities().tolist())\n observation.extend(self.rex.GetTrueMotorTorques().tolist())\n observation.extend(list(self.rex.GetTrueBaseOrientation()))\n\n self._true_observation = observation\n return self._true_observation\n\n def _get_observation_upper_bound(self):\n \"\"\"Get the upper bound of the observation.\n\n Returns:\n The upper bound of an observation. See GetObservation() for the details\n of each element of an observation.\n \"\"\"\n upper_bound = np.zeros(self._get_observation_dimension())\n num_motors = self.rex.num_motors\n upper_bound[0:num_motors] = math.pi # Joint angle.\n upper_bound[num_motors:2 * num_motors] = motor.MOTOR_SPEED_LIMIT # Joint velocity.\n upper_bound[2 * num_motors:3 * num_motors] = motor.OBSERVED_TORQUE_LIMIT # Joint torque.\n upper_bound[3 * num_motors:] = 1.0 # Quaternion of base orientation.\n return upper_bound\n\n def _get_observation_lower_bound(self):\n \"\"\"Get the lower bound of the observation.\"\"\"\n return -self._get_observation_upper_bound()\n\n def _get_observation_dimension(self):\n \"\"\"Get the length of the observation list.\n\n Returns:\n The length of the observation list.\n \"\"\"\n return len(self._get_observation())\n\n def set_time_step(self, control_step, simulation_step=0.001):\n \"\"\"Sets the time step of the environment.\n\n Args:\n control_step: The time period (in seconds) between two adjacent control\n actions are applied.\n simulation_step: The simulation time step in PyBullet. By default, the\n simulation step is 0.001s, which is a good trade-off between simulation\n speed and accuracy.\n Raises:\n ValueError: If the control step is smaller than the simulation step.\n \"\"\"\n if control_step < simulation_step:\n raise ValueError(\"Control step should be larger than or equal to simulation step.\")\n self.control_time_step = control_step\n self._time_step = simulation_step\n self._action_repeat = int(round(control_step / simulation_step))\n self._num_bullet_solver_iterations = (NUM_SIMULATION_ITERATION_STEPS / self._action_repeat)\n self._pybullet_client.setPhysicsEngineParameter(\n numSolverIterations=self._num_bullet_solver_iterations)\n self._pybullet_client.setTimeStep(self._time_step)\n self.rex.SetTimeSteps(action_repeat=self._action_repeat, simulation_step=self._time_step)\n\n @property\n def pybullet_client(self):\n return self._pybullet_client\n\n @property\n def ground_id(self):\n return self._ground_id\n\n @ground_id.setter\n def ground_id(self, new_ground_id):\n self._ground_id = new_ground_id\n\n @property\n def env_step_counter(self):\n return self._env_step_counter\n" ]
[ [ "numpy.concatenate", "numpy.array", "numpy.asarray" ] ]
autocorr/astroML
[ "9bdeff87b9ae1993849bfc04d7f2865c05c8e52e" ]
[ "book_figures/chapter5/fig_signal_background.py" ]
[ "\"\"\"\nFinding a signal in a background\n--------------------------------\nFigure 5.26\n\nFitting a model of a signal in an unknown background. The histogram in the\ntop-right panel visualizes a sample drawn from a Gaussian signal plus a\nuniform background model given by eq. 5.83 and shown by the line. The remaining\npanels show projections of the three-dimensional posterior pdf, based on a\n20,000 point MCMC chain.\n\"\"\"\n# Author: Jake VanderPlas\n# License: BSD\n# The figure produced by this code is published in the textbook\n# \"Statistics, Data Mining, and Machine Learning in Astronomy\" (2013)\n# For more information, see http://astroML.github.com\n# To report a bug or issue, use the following forum:\n# https://groups.google.com/forum/#!forum/astroml-general\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom scipy import stats\n\n# Hack to fix import issue in older versions of pymc\nimport scipy\nimport scipy.misc\nscipy.derivative = scipy.misc.derivative\nimport pymc\n\nfrom astroML.plotting import plot_mcmc\n\n#----------------------------------------------------------------------\n# This function adjusts matplotlib settings for a uniform feel in the textbook.\n# Note that with usetex=True, fonts are rendered with LaTeX. This may\n# result in an error if LaTeX is not installed on your system. In that case,\n# you can set usetex to False.\nfrom astroML.plotting import setup_text_plots\nsetup_text_plots(fontsize=8, usetex=True)\n\n#----------------------------------------------------------------------\n# Set up dataset: gaussian signal in a uniform background\nnp.random.seed(0)\n\nN = 100\n\nA_true = 0.3\nW_true = 10\nx0_true = 6\nsigma_true = 0.3\n\nsignal = stats.norm(x0_true, sigma_true)\nbackground = stats.uniform(0, W_true)\n\nx = np.random.random(N)\ni_sig = x < A_true\ni_bg = ~i_sig\nx[i_sig] = signal.rvs(np.sum(i_sig))\nx[i_bg] = background.rvs(np.sum(i_bg))\n\n#----------------------------------------------------------------------\n# Set up MCMC sampling\nA = pymc.Uniform('A', 0, 1, value=0.5)\nx0 = pymc.Uniform('x0', 0, 10, value=5)\nlog_sigma = pymc.Uniform('log_sigma', -5, 5, value=0)\n\n\[email protected]\ndef sigma(log_sigma=log_sigma):\n return np.exp(log_sigma)\n\n\ndef sigbg_like(x, A, x0, sigma):\n \"\"\"signal + background likelihood\"\"\"\n return np.sum(np.log(A * np.exp(-0.5 * ((x - x0) / sigma) ** 2)\n / np.sqrt(2 * np.pi) / sigma\n + (1 - A) / W_true))\n\nSigBG = pymc.stochastic_from_dist('sigbg',\n logp=sigbg_like,\n dtype=np.float, mv=True)\n\nM = SigBG('M', A, x0, sigma, observed=True, value=x)\n\nmodel = dict(M=M, A=A, x0=x0, log_sigma=log_sigma, sigma=sigma)\n\n#----------------------------------------------------------------------\n# Run the MCMC sampling\nS = pymc.MCMC(model)\nS.sample(iter=25000, burn=5000)\n\n#------------------------------------------------------------\n# Plot the results\nfig = plt.figure(figsize=(5, 5))\nax_list = plot_mcmc([S.trace(s)[:] for s in ['A', 'x0', 'sigma']],\n limits=[(0.05, 0.65), (5.75, 6.65), (0.05, 0.85)],\n labels=['$A$', '$\\mu$', r'$\\sigma$'],\n bounds=(0.1, 0.1, 0.95, 0.95),\n true_values=[A_true, x0_true, sigma_true],\n fig=fig, colors='k')\n\nax = plt.axes([0.62, 0.62, 0.33, 0.33])\nx_pdf = np.linspace(0, 10, 100)\ny_pdf = A_true * signal.pdf(x_pdf) + (1 - A_true) * background.pdf(x_pdf)\n\nax.hist(x, 15, normed=True, histtype='stepfilled', alpha=0.5)\nax.plot(x_pdf, y_pdf, '-k')\n\nax.set_xlim(0, 10)\nax.set_ylim(0, 0.5)\nax.set_xlabel('$x$')\nax.set_ylabel(r'$y_{\\rm obs}$')\n\nplt.show()\n" ]
[ [ "scipy.stats.norm", "scipy.stats.uniform", "numpy.random.seed", "numpy.sum", "numpy.exp", "matplotlib.pyplot.figure", "matplotlib.pyplot.show", "numpy.sqrt", "numpy.random.random", "numpy.linspace", "matplotlib.pyplot.axes" ] ]
Milwaukee-Bugs-NTUA/AdvancedDB20-21
[ "7fc1208a74459dfe1f09b7ae430ddca7cfa03e60" ]
[ "src/test_queries.py" ]
[ "#!/usr/bin/env python\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport sys\n\nfrom query1 import *\nfrom query2 import *\nfrom query3 import *\nfrom query4 import *\nfrom query5 import *\nfrom query1_rdd import *\nfrom query2_rdd import *\nfrom query3_rdd import *\nfrom query4_rdd import *\nfrom query5_rdd import *\n\ndef plot_results(x1, x2, x3):\n\n labels = [\"Q1\",\"Q2\",\"Q3\",\"Q4\",\"Q5\"]\n x = np.arange(len(labels))\n width = 0.20 \n\n # Figure\n fig, ax = plt.subplots()\n ax.bar(x - width, x1, width, label='csv')\n ax.bar(x, x2, width, label='parquet')\n ax.bar(x + width, x3, width, label='rdd')\n ax.set_ylabel('Execution time')\n ax.set_xlabel('Queries')\n ax.set_title('Execution Times per query & technology')\n ax.set_xticks(x)\n ax.set_xticklabels(labels)\n ax.legend()\n fig.tight_layout()\n # Save figure\n plt.savefig(\"../results/plot.png\",dpi=300)\n\ndef plot_sql_results(x1, x2):\n\n labels = [\"Q1\",\"Q2\",\"Q3\",\"Q4\",\"Q5\"]\n x = np.arange(len(labels))\n width = 0.35 \n\n # Figure\n fig, ax = plt.subplots()\n ax.bar(x - width/2, x1, width, label='csv')\n ax.bar(x + width/2, x2, width, label='parquet')\n ax.set_ylabel('Execution time')\n ax.set_xlabel('Queries')\n ax.set_title('Execution Times per query & technology')\n ax.set_xticks(x)\n ax.set_xticklabels(labels)\n ax.legend()\n fig.tight_layout()\n # Save figure\n plt.savefig(\"../results/plot_sql.png\",dpi=300)\n\n\nif __name__ == \"__main__\":\n\n if len(sys.argv) < 2:\n print(\"Please provide number of iterations for each query\")\n exit()\n if int(sys.argv[1]) <= 0:\n print(\"Please provide a non negative number of iterations for each query\")\n exit()\n tests = {\"csv\":[], \"parquet\":[],\"rdd\":[]}\n\n for i in range(1,6):\n print(\"== Query {} ==\".format(i))\n for f in [\"csv\", \"parquet\"]:\n t_sum = 0\n print(\"Executing Q{} for {} format...\".format(i,f))\n for n in range(int(sys.argv[1])):\n t_sum += locals()[\"query{}\".format(i)](f)\n t = t_sum / (n + 1)\n tests[f].append(t)\n t_sum = 0\n print(\"Executing Q{} with rdd...\".format(i))\n for n in range(int(sys.argv[1])):\n t_sum += locals()[\"query{}_rdd\".format(i)]()\n t = t_sum / (n + 1)\n tests[\"rdd\"].append(t)\n print()\n\n\n # Save output to disk\n with open(\"../results/execution_time.txt\", \"wt\") as f:\n print(\"Q1\\tQ2\\tQ3\\tQ4\\tQ5\\t\",file=f)\n print(*tests[\"csv\"],file=f)\n print(*tests[\"parquet\"],file=f)\n print(*tests[\"rdd\"],file=f)\n \n plot_results(tests[\"csv\"],tests[\"parquet\"],tests[\"rdd\"])\n plot_sql_results(tests[\"csv\"],tests[\"parquet\"])\n" ]
[ [ "matplotlib.pyplot.savefig", "matplotlib.pyplot.subplots" ] ]
marcomameli1992/FakeNews
[ "ff0eabd848402fefc66062d05b0c4fa6647ea0f4" ]
[ "models/mixed_model.py" ]
[ "import torch\nimport torch.nn as nn\nfrom models.bert import BertForSentimentClassification\nfrom models.vgg import VGG16FT\nfrom models.classification import Classification\nfrom models.vit import ViTFT\n\nclass MixModel(nn.Module):\n def __init__(self, config, n_classes=2, bert_path=None, vit = False, vgg_path=None, classification_path=None):\n super(MixModel, self).__init__()\n if bert_path is not None:\n self.bert = BertForSentimentClassification.from_pretrained(bert_path)\n else:\n self.bert = BertForSentimentClassification(config)\n\n text_feature_dim = config.hidden_size\n\n self.use_vit = vit\n\n if vit:\n self.image_feature_extractor = ViTFT()\n #image_feature_dim = self.image_feature_extractor.vit.size * self.image_feature_extractor.vit.size * 3 #TODO make it more general\n image_feature_dim = self.image_feature_extractor.vit.num_features\n else:\n self.image_feature_extractor = VGG16FT(n_classes)\n if vgg_path is not None:\n self.image_feature_extractor.load_state_dict(torch.load(vgg_path))\n\n image_feature_dim = self.image_feature_extractor.vgg.features[-3].out_channels * 6 * 6 # the 6 is calculated inside from pytorchconv2d\n\n linear_input_dimension = text_feature_dim + image_feature_dim #614400#config.hidden_size + 4096 # 4096 è il numero di features estrate da vgg\n\n if classification_path is not None:\n self.classification = Classification(linear_input_dimension, n_classes)\n self.classification.load_state_dict(torch.load(classification_path))\n else:\n self.classification = Classification(linear_input_dimension, n_classes)\n\n def forward(self, text, text_input_mask, image):\n with torch.no_grad():\n text_features, logit = self.bert.forward(text, text_input_mask)\n if self.use_vit:\n image_features = self.image_feature_extractor(image)\n else:\n image_features, cls = self.image_feature_extractor(image)\n\n mixed_features = torch.cat((torch.flatten(text_features, start_dim=1), torch.flatten(image_features, start_dim=1)), dim=1)\n classification = self.classification(mixed_features)\n return classification\n\nif __name__ == \"__main__\":\n import torch\n from transformers import AutoConfig\n\n bertModelNameOrPath = 'bert-base-uncased'\n config = AutoConfig.from_pretrained(bertModelNameOrPath)\n feature_extractor = MixModel(config, vit=True)\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n feature_extractor.to(device)" ]
[ [ "torch.flatten", "torch.no_grad", "torch.cuda.is_available", "torch.load" ] ]
mlaves/imes4d
[ "d1505f75487ced0a10c05f1c937af91ff666e3d4" ]
[ "stitch_n_volumes.py" ]
[ "#!/usr/bin/env python\n\nimport numpy as np\nfrom imes4d.PyrLK3D import PyrLK3D\nfrom imes4d.utils import Timer, ransac, blend_collection\n\n\nif __name__ == \"__main__\":\n\n N = 7\n scale = 2\n transformations = []\n data_prefix = 'data/sb_'\n\n a = np.load(data_prefix + '0.npz')\n a = a[a.files[0]][::scale, ::scale, ::scale].astype(np.float32)\n\n # first, calculate flow and transformation matrices\n for n in range(1, N):\n # load two adjacent volumes\n with Timer('loading ' + str(n)):\n b = np.load(data_prefix + str(n) + '.npz')\n b = b[b.files[0]][::scale, ::scale, ::scale].astype(np.float32)\n\n with Timer('harris ' + str(n)):\n prev_pts = PyrLK3D.harris_corner_3d(a)\n\n lk = PyrLK3D(a, b, prev_pts, win_size=(5, 5, 5), levels=5, eps=1e-3, max_iterations=200)\n\n with Timer('pyr_lk ' + str(n)):\n flow, err, it = lk.calc_flow()\n\n # find best 50 % matches\n mean_err = np.mean(np.sort(err)[:int(len(err) / 2)])\n best_flow = np.array([i for i, e in zip(flow, err) if e < mean_err])\n best_prev = np.array([i for i, e in zip(prev_pts, err) if e < mean_err])\n\n print('best_flow.shape =', best_flow.shape)\n\n # find transformations, iteratively increase inlier threshold\n with Timer('ransac ' + str(n)):\n i_t = 0.5\n inlier_idx = []\n while len(inlier_idx) < 10:\n t, inlier_idx = ransac(best_prev, (best_prev+best_flow), 'rigid', inlier_threshold=i_t, ransac_it=1000)\n i_t = i_t + 0.5\n\n print('inliers:', len(inlier_idx))\n print(t)\n transformations.append(t)\n\n a = b\n\n # stitch volumes\n with Timer('blending'):\n volumes = []\n for n in range(N):\n vol = np.load(data_prefix + str(n)+'.npz')\n vol = vol[vol.files[0]][::scale, ::scale, ::scale].astype(np.float32)\n volumes.append(vol)\n\n stitched = blend_collection(volumes, transformations)\n\n np.savez_compressed('stitched_total.npz', stitched)\n" ]
[ [ "numpy.savez_compressed", "numpy.load", "numpy.sort" ] ]
KUASWoodyLIN/Udacity_self_driving_car_challenge_5
[ "af94d5232795925580f74eca2468ec3de6cd4b48" ]
[ "svm_training.py" ]
[ "import os\nimport time\nimport pickle\nfrom glob import glob\n\nimport numpy as np\nimport cv2\nimport matplotlib.pyplot as plt\n\nfrom sklearn.svm import LinearSVC\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.model_selection import train_test_split\n\nfrom image_processing.vehicles_detect_model import custom_extract_features, custom_search_windows\nfrom image_processing.sliding_window import slide_window, draw_boxes\n\n# RGB 0.9673\n# HSV 0.9868\n# SV 0.9856\n# HLS 0.98\n# LS 0.9823\n# HLS HL, YUV U0.9885\n\n\n# --------------------- 前處理 特徵擷取 --------------------- #\ndef pre_processing():\n # car_features = extract_features(cars, color_space=color_space,\n # spatial_size=spatial_size, hist_bins=hist_bins,\n # orient=orient, pix_per_cell=pix_per_cell,\n # cell_per_block=cell_per_block,\n # hog_channel=hog_channel, spatial_feat=spatial_feat,\n # hist_feat=hist_feat, hog_feat=hog_feat)\n # notcar_features = extract_features(notcars, color_space=color_space,\n # spatial_size=spatial_size, hist_bins=hist_bins,\n # orient=orient, pix_per_cell=pix_per_cell,\n # cell_per_block=cell_per_block,\n # hog_channel=hog_channel, spatial_feat=spatial_feat,\n # hist_feat=hist_feat, hog_feat=hog_feat)\n car_features = custom_extract_features(cars, spatial_size=spatial_size, hist_bins=hist_bins,\n orient=orient, pix_per_cell=pix_per_cell,\n cell_per_block=cell_per_block, spatial_feat=spatial_feat,\n hist_feat=hist_feat, hog_feat=hog_feat)\n notcar_features = custom_extract_features(notcars, spatial_size=spatial_size, hist_bins=hist_bins,\n orient=orient, pix_per_cell=pix_per_cell,\n cell_per_block=cell_per_block, spatial_feat=spatial_feat,\n hist_feat=hist_feat, hog_feat=hog_feat)\n\n X = np.vstack((car_features, notcar_features)).astype(np.float64)\n y = np.hstack((np.ones(len(car_features)), np.zeros(len(notcar_features))))\n\n # --------------------- 分成將數據分為 ---------------------- #\n # --------------- training and testing set --------------- #\n rand_state = np.random.randint(0, 100)\n X_train, X_test, y_train, y_test = train_test_split(\n X, y, test_size=0.2, random_state=rand_state, shuffle=True)\n\n # ---------------------- 前處理 正規化 ---------------------- #\n X_scaler = StandardScaler().fit(X_train)\n X_train = X_scaler.transform(X_train)\n X_test = X_scaler.transform(X_test)\n\n print('Using:', orient, 'orientations', pix_per_cell,\n 'pixels per cell and', cell_per_block, 'cells per block')\n print('Feature vector length:', len(X_train[0]))\n return X_train, X_test, y_train, y_test, X_scaler\n\n\n# ------------------------ SVM 訓練 ----------------------- #\ndef training(X_train, X_test, y_train, y_test):\n svc = LinearSVC()\n # Check the training time for the SVC\n t=time.time()\n svc.fit(X_train, y_train)\n t2 = time.time()\n print(round(t2-t, 2), 'Seconds to train SVC...')\n # Check the score of the SVC\n accuracy = round(svc.score(X_test, y_test), 4)\n print('Test Accuracy of SVC = ', accuracy)\n return svc, accuracy\n\n\n# ------------------------ SVM 測試 ----------------------- #\ndef testing_svm(image, svc, X_scaler, y_start_stop=[400, 656],\n spatial_size=(32, 32), hist_bins=32,\n orient=9, pix_per_cell=8, cell_per_block=2,\n spatial_feat=True, hist_feat=True, hog_feat=True, vis=True):\n draw_image = np.copy(image)\n windows = slide_window(image, x_start_stop=[None, None], y_start_stop=y_start_stop,\n xy_window=(64, 64), xy_overlap=(0.5, 0.5))\n\n windows.extend(slide_window(image, x_start_stop=[None, None], y_start_stop=y_start_stop,\n xy_window=(96, 96), xy_overlap=(0.5, 0.5)))\n\n windows.extend(slide_window(image, x_start_stop=[None, None], y_start_stop=y_start_stop,\n xy_window=(128, 128), xy_overlap=(0.7, 0.7)))\n\n windows.extend(slide_window(image, x_start_stop=[None, None], y_start_stop=y_start_stop,\n xy_window=(200, 200), xy_overlap=(0.75, 0.75)))\n\n start = time.time()\n hot_windows = custom_search_windows(image, windows, svc, X_scaler,\n spatial_size=spatial_size, hist_bins=hist_bins,\n orient=orient, pix_per_cell=pix_per_cell,\n cell_per_block=cell_per_block,\n spatial_feat=spatial_feat,\n hist_feat=hist_feat, hog_feat=hog_feat)\n print('test process running time {:.3}s'.format(time.time() - start))\n if vis is True:\n window_img = draw_boxes(draw_image, hot_windows, color=(0, 0, 255), thick=6)\n return window_img\n else:\n return hot_windows\n\n\nif __name__ == \"__main__\":\n # PATH definition\n ROOT_PATH = os.getcwd()\n DATA_PATH = os.path.join(ROOT_PATH, 'data')\n MODEL_PATH = os.path.join(ROOT_PATH, 'model')\n VEHICLES = os.path.join(DATA_PATH, 'vehicles')\n NON_VEHICLES = os.path.join(DATA_PATH, 'non-vehicles')\n SVC_PICKLE_FILE = os.path.join(MODEL_PATH, 'svc_pickle.p')\n IMAGES_TEST = os.path.join(ROOT_PATH, 'test_images')\n IMAGES_OUTPUT = os.path.join(ROOT_PATH, 'output_images')\n\n # Read in cars and notcars\n cars = glob(VEHICLES + '/*/*')\n notcars = glob(NON_VEHICLES + '/*/*')\n\n # TODO: 測試更改這些參數\n # Color space and color channel\n color_space = 'YCrCb' # Can be RGB, HSV, LUV, HLS, YUV, YCrCb\n hog_channel = [0, 1, 2] # Can be list [0, 1, 2]\n\n # bin_spatial parameter\n spatial_size = (16, 16) # Spatial binning dimensions\n spatial_feat = True # Spatial features on or off\n\n # color_hist\n hist_bins = 16 # Number of histogram bins\n hist_feat = True # Histogram features on or off\n\n # HOG parameter\n orient = 9 # HOG orientations 9\n pix_per_cell = 8 # HOG pixels per cell 8\n cell_per_block = 2 # HOG cells per block\n hog_feat = True # HOG features on or off\n\n # sliding window parameter\n y_start_stop = [400, 656] # Min and max in y to search in slide_window()\n\n MODE = 'training'\n MODE = 'testing'\n\n if MODE == 'training':\n x_train, x_test, y_train, y_test, x_scaler = pre_processing()\n svc, accuracy = training(x_train, x_test, y_train, y_test)\n if not os.path.exists(SVC_PICKLE_FILE):\n print('Pickle File {} is not exists, create one now.'.format(SVC_PICKLE_FILE))\n dist_pickle = {}\n dist_pickle[\"svc\"] = svc\n dist_pickle[\"scaler\"] = x_scaler\n dist_pickle[\"orient\"] = orient\n dist_pickle[\"pix_per_cell\"] = pix_per_cell\n dist_pickle[\"cell_per_block\"] = cell_per_block\n dist_pickle[\"spatial_size\"] = spatial_size\n dist_pickle[\"hist_bins\"] = hist_bins\n dist_pickle[\"accuracy\"] = accuracy\n pickle.dump(dist_pickle, open(SVC_PICKLE_FILE, \"wb\"))\n\n # testing\n img = cv2.imread('./test_images/test1.jpg')\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n out_img1 = testing_svm(img, svc, x_scaler, y_start_stop,\n spatial_size, hist_bins,\n orient, pix_per_cell, cell_per_block,\n spatial_feat, hist_feat, hist_feat)\n plt.figure()\n plt.title('out_img1')\n plt.imshow(out_img1)\n\n ystart = 400\n ystop = 656\n scale = 1.5\n # out_img2 = find_cars(img, ystart, ystop, scale, svc, x_scaler, color_space, orient,\n # pix_per_cell, cell_per_block, spatial_size, hist_bins, hog_channel)\n # plt.figure()\n # plt.title('out_img2')\n # plt.imshow(out_img2)\n plt.show()\n\n # Check is this model need to save\n dist_pickle = pickle.load(open(SVC_PICKLE_FILE, \"rb\"))\n pre_accuracy = dist_pickle[\"accuracy\"]\n print(\"Accuracy {}, Pre-accuracy {}\".format(accuracy, pre_accuracy))\n\n ans = input(\"是否要儲存這次的model(y/n): \")\n if ans == 'y':\n print('The parameters have more higher performance, Save {} File.'.format(SVC_PICKLE_FILE))\n dist_pickle = {}\n dist_pickle[\"svc\"] = svc\n dist_pickle[\"scaler\"] = x_scaler\n dist_pickle[\"orient\"] = orient\n dist_pickle[\"pix_per_cell\"] = pix_per_cell\n dist_pickle[\"cell_per_block\"] = cell_per_block\n dist_pickle[\"spatial_size\"] = spatial_size\n dist_pickle[\"hist_bins\"] = hist_bins\n dist_pickle[\"accuracy\"] = accuracy\n pickle.dump(dist_pickle, open(SVC_PICKLE_FILE, \"wb\"))\n\n else:\n # load a pe-trained svc model from a serialized (pickle) file\n dist_pickle = pickle.load(open(SVC_PICKLE_FILE, \"rb\"))\n\n # get attributes of our svc object\n svc = dist_pickle[\"svc\"]\n x_scaler = dist_pickle[\"scaler\"]\n orient = dist_pickle[\"orient\"]\n pix_per_cell = dist_pickle[\"pix_per_cell\"]\n cell_per_block = dist_pickle[\"cell_per_block\"]\n spatial_size = dist_pickle[\"spatial_size\"]\n hist_bins = dist_pickle[\"hist_bins\"]\n accuracy = dist_pickle[\"accuracy\"]\n images_path = glob(IMAGES_TEST + '/*')\n print(\"Accuracy {}\".format(accuracy))\n # testing\n print('Start testing images')\n plt.figure(figsize=(12, 10))\n for index, path in enumerate(images_path, 1):\n img = cv2.imread(path)\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n out_img = testing_svm(img, svc, x_scaler, y_start_stop,\n spatial_size, hist_bins,\n orient, pix_per_cell, cell_per_block,\n spatial_feat, hist_feat, hog_feat)\n\n # Image Show\n plt.subplot(3, 2, index)\n plt.title(os.path.split(path)[-1])\n plt.imshow(out_img)\n\n # Image save\n file_name = 'output_svm_{}.png'.format(os.path.split(path)[-1].split('.')[0])\n file_path = os.path.join(IMAGES_OUTPUT, file_name)\n plt.imsave(file_path, out_img)\n\n file_name = 'output_svm_test_all.png'\n file_path = os.path.join(IMAGES_OUTPUT, file_name)\n plt.savefig(file_path, bbox_inches='tight')\n plt.show()\n" ]
[ [ "matplotlib.pyplot.subplot", "sklearn.preprocessing.StandardScaler", "matplotlib.pyplot.imsave", "matplotlib.pyplot.savefig", "numpy.copy", "matplotlib.pyplot.title", "matplotlib.pyplot.figure", "numpy.random.randint", "numpy.vstack", "sklearn.model_selection.train_test_split", "matplotlib.pyplot.show", "sklearn.svm.LinearSVC", "matplotlib.pyplot.imshow" ] ]
hrsu/disturb
[ "38396fceb6c7b11fbc369166c7eea048c4188391" ]
[ "Bayes/Multinomial_Bayes.py" ]
[ "from sklearn.naive_bayes import MultinomialNB #多项式分布朴素贝叶斯\nimport numpy as np\nimport sklearn.model_selection as train\nfrom sklearn.metrics import accuracy_score\nimport os\n\n#数据目录\nFilePath = os.path.abspath('..')+\"\\\\data\"\n\n\ndef loadData(filename,type):\n data = np.loadtxt(filename, dtype=type, delimiter=',',skiprows=2)\n x,y=np.split(data,indices_or_sections=(1,),axis=1)\n #后十个为属性值,第一个为标签\n x ,y= y[:,1:],x\n #前十个为属性值\n x_train,x_test,y_train,y_test=train.train_test_split(x,y,random_state=1,train_size=0.6)\n #随机划分训练集与测试集\n return x_train,x_test,y_train,y_test\n\ndef Train_Bayes(x_train,y_train):\n clf = MultinomialNB()\n clf.fit(x_train, y_train.ravel())\n return clf\n\n\ndef Test_Bayes(x_train,x_test,y_train,y_test,clf):\n if clf is None:\n raise IOError(\"Must input a clf!\")\n y_hat = clf.predict(x_train)\n score = accuracy_score(y_hat, y_train)\n print('训练集准确率:{}'.format(score))\n y_hat=clf.predict(x_test)\n score=accuracy_score(y_hat,y_test)\n print('测试集准确率:{}'.format(score))\n\n\n\n\nif __name__ == '__main__':\n x_train1, x_test1, y_train1, y_test1 = loadData(FilePath + '\\\\new_data.txt', float)\n clf1 = Train_Bayes(x_train1, y_train1)\n print('随机干扰前:')\n Test_Bayes(x_train1, x_test1, y_train1, y_test1, clf1)\n\n print('-------------------------------------------------------------------')\n print('random=5,max=10数据:')\n x_train2, x_test2, y_train2, y_test2 = loadData(FilePath + '\\\\random=5,max=10.txt', int)\n clf2 = Train_Bayes(x_train2, y_train2)\n Test_Bayes(x_train2, x_test2, y_train2, y_test2, clf2)\n\n print('-------------------------------------------------------------------')\n print('random=10,max=10数据:')\n x_train2, x_test2, y_train2, y_test2 = loadData(FilePath + '\\\\random=10,max=10.txt', int)\n clf2 = Train_Bayes(x_train2, y_train2)\n Test_Bayes(x_train2, x_test2, y_train2, y_test2, clf2)\n\n print('-------------------------------------------------------------------')\n print('random=15,max=10数据:')\n x_train2, x_test2, y_train2, y_test2 = loadData(FilePath + '\\\\random=15,max=10.txt', int)\n clf2 = Train_Bayes(x_train2, y_train2)\n Test_Bayes(x_train2, x_test2, y_train2, y_test2, clf2)\n\n print('-------------------------------------------------------------------')\n print('random=20,max=10数据:')\n x_train2, x_test2, y_train2, y_test2 = loadData(FilePath + '\\\\random=20,max=10.txt', int)\n clf2 = Train_Bayes(x_train2, y_train2)\n Test_Bayes(x_train2, x_test2, y_train2, y_test2, clf2)\n\n print('-------------------------------------------------------------------')\n print('random=25,max=10数据:')\n x_train2, x_test2, y_train2, y_test2 = loadData(FilePath + '\\\\random=25,max=10.txt', int)\n clf2 = Train_Bayes(x_train2, y_train2)\n Test_Bayes(x_train2, x_test2, y_train2, y_test2, clf2)\n\n print('-------------------------------------------------------------------')\n print('random=30,max=10数据:')\n x_train2, x_test2, y_train2, y_test2 = loadData(FilePath + '\\\\random=30,max=10.txt', int)\n clf2 = Train_Bayes(x_train2, y_train2)\n Test_Bayes(x_train2, x_test2, y_train2, y_test2, clf2)\n" ]
[ [ "numpy.split", "sklearn.metrics.accuracy_score", "sklearn.naive_bayes.MultinomialNB", "numpy.loadtxt", "sklearn.model_selection.train_test_split" ] ]
HacksForHugs/ray
[ "4af42d5bb6ab3fef7dad80c722249218bb9cc061" ]
[ "python/ray/tune/logger.py" ]
[ "from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport csv\nimport json\nimport numpy as np\nimport os\nimport yaml\n\nfrom ray.tune.result import TrainingResult\nfrom ray.tune.log_sync import get_syncer\n\ntry:\n import tensorflow as tf\nexcept ImportError:\n tf = None\n print(\"Couldn't import TensorFlow - this disables TensorBoard logging.\")\n\n\nclass Logger(object):\n \"\"\"Logging interface for ray.tune; specialized implementations follow.\n\n By default, the UnifiedLogger implementation is used which logs results in\n multiple formats (TensorBoard, rllab/viskit, plain json) at once.\n \"\"\"\n\n def __init__(self, config, logdir, upload_uri=None):\n self.config = config\n self.logdir = logdir\n self.uri = upload_uri\n self._init()\n\n def _init(self):\n pass\n\n def on_result(self, result):\n \"\"\"Given a result, appends it to the existing log.\"\"\"\n\n raise NotImplementedError\n\n def close(self):\n \"\"\"Releases all resources used by this logger.\"\"\"\n\n pass\n\n def flush(self):\n \"\"\"Flushes all disk writes to storage.\"\"\"\n\n pass\n\n\nclass UnifiedLogger(Logger):\n \"\"\"Unified result logger for TensorBoard, rllab/viskit, plain json.\n\n This class also periodically syncs output to the given upload uri.\"\"\"\n\n def _init(self):\n self._loggers = []\n for cls in [_JsonLogger, _TFLogger, _VisKitLogger]:\n if cls is _TFLogger and tf is None:\n print(\"TF not installed - cannot log with {}...\".format(cls))\n continue\n self._loggers.append(cls(self.config, self.logdir, self.uri))\n self._log_syncer = get_syncer(self.logdir, self.uri)\n\n def on_result(self, result):\n for logger in self._loggers:\n logger.on_result(result)\n self._log_syncer.set_worker_ip(result.node_ip)\n self._log_syncer.sync_if_needed()\n\n def close(self):\n for logger in self._loggers:\n logger.close()\n self._log_syncer.sync_now(force=True)\n\n def flush(self):\n self._log_syncer.sync_now(force=True)\n self._log_syncer.wait()\n\n\nclass NoopLogger(Logger):\n def on_result(self, result):\n pass\n\n\nclass _JsonLogger(Logger):\n def _init(self):\n config_out = os.path.join(self.logdir, \"params.json\")\n with open(config_out, \"w\") as f:\n json.dump(self.config, f, sort_keys=True, cls=_CustomEncoder)\n local_file = os.path.join(self.logdir, \"result.json\")\n self.local_out = open(local_file, \"w\")\n\n def on_result(self, result):\n json.dump(result._asdict(), self, cls=_CustomEncoder)\n self.write(\"\\n\")\n\n def write(self, b):\n self.local_out.write(b)\n self.local_out.flush()\n\n def close(self):\n self.local_out.close()\n\n\ndef to_tf_values(result, path):\n values = []\n for attr, value in result.items():\n if value is not None:\n if type(value) in [int, float]:\n values.append(tf.Summary.Value(\n tag=\"/\".join(path + [attr]),\n simple_value=value))\n elif type(value) is dict:\n values.extend(to_tf_values(value, path + [attr]))\n return values\n\n\nclass _TFLogger(Logger):\n def _init(self):\n self._file_writer = tf.summary.FileWriter(self.logdir)\n\n def on_result(self, result):\n tmp = result._asdict()\n for k in [\n \"config\", \"pid\", \"timestamp\", \"time_total_s\",\n \"timesteps_total\"]:\n del tmp[k] # not useful to tf log these\n values = to_tf_values(tmp, [\"ray\", \"tune\"])\n train_stats = tf.Summary(value=values)\n self._file_writer.add_summary(train_stats, result.timesteps_total)\n\n def close(self):\n self._file_writer.close()\n\n\nclass _VisKitLogger(Logger):\n def _init(self):\n # Note that we assume params.json was already created by JsonLogger\n self._file = open(os.path.join(self.logdir, \"progress.csv\"), \"w\")\n self._csv_out = csv.DictWriter(self._file, TrainingResult._fields)\n self._csv_out.writeheader()\n\n def on_result(self, result):\n self._csv_out.writerow(result._asdict())\n\n def close(self):\n self._file.close()\n\n\nclass _CustomEncoder(json.JSONEncoder):\n def __init__(self, nan_str=\"null\", **kwargs):\n super(_CustomEncoder, self).__init__(**kwargs)\n self.nan_str = nan_str\n\n def iterencode(self, o, _one_shot=False):\n if self.ensure_ascii:\n _encoder = json.encoder.encode_basestring_ascii\n else:\n _encoder = json.encoder.encode_basestring\n\n def floatstr(o, allow_nan=self.allow_nan, nan_str=self.nan_str):\n return repr(o) if not np.isnan(o) else nan_str\n\n _iterencode = json.encoder._make_iterencode(\n None, self.default, _encoder, self.indent, floatstr,\n self.key_separator, self.item_separator, self.sort_keys,\n self.skipkeys, _one_shot)\n return _iterencode(o, 0)\n\n def default(self, value):\n if np.isnan(value):\n return None\n if np.issubdtype(value, float):\n return float(value)\n if np.issubdtype(value, int):\n return int(value)\n\n\ndef pretty_print(result):\n result = result._replace(config=None) # drop config from pretty print\n out = {}\n for k, v in result._asdict().items():\n if v is not None:\n out[k] = v\n\n cleaned = json.dumps(out, cls=_CustomEncoder)\n return yaml.dump(json.loads(cleaned), default_flow_style=False)\n" ]
[ [ "tensorflow.Summary", "tensorflow.summary.FileWriter", "numpy.issubdtype", "numpy.isnan" ] ]
reneevdw/GenNet
[ "e30f0cce4372c770f8d4692ce6a6f61a160c0d5d" ]
[ "GenNet_utils/LocallyDirectedConnected.py" ]
[ "# For the article see https://www.biorxiv.org/content/10.1101/2020.06.19.159152v1\n# For an explenation how to use this layer see https://github.com/ArnovanHilten/GenNet\n# Locallyconnected1D is used as a basis to write the LocallyDirected layer\n# ==============================================================================\n# Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"LocallyDirected1D layer.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.python.keras import activations\nfrom tensorflow.python.keras import backend as K\nfrom tensorflow.python.keras import constraints\nfrom tensorflow.python.keras import initializers\nfrom tensorflow.python.keras import regularizers\nfrom tensorflow.python.keras.engine.base_layer import InputSpec\nfrom tensorflow.python.keras.engine.base_layer import Layer\nfrom tensorflow.python.keras.utils import conv_utils\nfrom tensorflow.python.keras.utils import tf_utils\nfrom tensorflow.python.util.tf_export import tf_export\n\n\n@tf_export('keras.layers.LocallyDirected1D')\nclass LocallyDirected1D(Layer):\n \"\"\"Locally-Directed1D layer for 1D inputs.\n\n The `LocallyDirected1D` layer works similarly to\n the `Conv1D` layer, except that weights are unshared,\n that is, a different set of filters is applied at each different patch\n of the input.\n\n Example:\n ```python\n # apply a unshared weight convolution 1d of length 3 to a sequence with\n # 10 timesteps, with 64 output filters\n model = Sequential()\n model.add(LocallyDirected1D(64, 3, input_shape=(10, 32)))\n # now model.output_shape == (None, 8, 64)\n # add a new conv1d on top\n model.add(LocallyDirected1D(32, 3))\n # now model.output_shape == (None, 6, 32)\n ```\n\n Arguments:\n mask: sparse matrix with shape (input, output) connectivity matrix,\n True defines connection between (in_i, out_j), should be sparse (False,0) >> True\n should be scipy sparese matrix in COO Format!\n filters: Integer, the dimensionality of the output space\n (i.e. the number of output filters in the convolution).\n kernel_size: An integer or tuple/list of a single integer,\n specifying the length of the 1D convolution window.\n strides: An integer or tuple/list of a single integer,\n specifying the stride length of the convolution.\n Specifying any stride value != 1 is incompatible with specifying\n any `dilation_rate` value != 1.\n padding: Currently only supports `\"valid\"` (case-insensitive).\n `\"same\"` may be supported in the future.\n data_format: A string,\n one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch, length, channels)` while `channels_first`\n corresponds to inputs with shape\n `(batch, channels, length)`.\n It defaults to the `image_data_format` value found in your\n Keras config file at `~/.keras/keras.json`.\n If you never set it, then it will be \"channels_last\".\n activation: Activation function to use.\n If you don't specify anything, no activation is applied\n (ie. \"linear\" activation: `a(x) = x`).\n use_bias: Boolean, whether the layer uses a bias vector.\n kernel_initializer: Initializer for the `kernel` weights matrix.\n bias_initializer: Initializer for the bias vector.\n kernel_regularizer: Regularizer function applied to\n the `kernel` weights matrix.\n bias_regularizer: Regularizer function applied to the bias vector.\n activity_regularizer: Regularizer function applied to\n the output of the layer (its \"activation\")..\n kernel_constraint: Constraint function applied to the kernel matrix.\n bias_constraint: Constraint function applied to the bias vector.\n\n Input shape:\n 3D tensor with shape: `(batch_size, steps, input_dim)`\n\n Output shape:\n 3D tensor with shape: `(batch_size, new_steps, filters)`\n `steps` value might have changed due to padding or strides.\n \"\"\"\n\n def __init__(self,\n mask,\n filters,\n padding='valid',\n data_format=None,\n activation=None,\n use_bias=True,\n kernel_initializer='glorot_uniform',\n bias_initializer='zeros',\n kernel_regularizer=None,\n bias_regularizer=None,\n activity_regularizer=None,\n kernel_constraint=None,\n bias_constraint=None,\n **kwargs):\n super(LocallyDirected1D, self).__init__(**kwargs)\n self.filters = filters\n self.padding = conv_utils.normalize_padding(padding)\n self.data_format = conv_utils.normalize_data_format(data_format)\n self.activation = activations.get(activation)\n self.use_bias = use_bias\n self.kernel_initializer = initializers.get(kernel_initializer)\n self.bias_initializer = initializers.get(bias_initializer)\n self.kernel_regularizer = regularizers.get(kernel_regularizer)\n self.bias_regularizer = regularizers.get(bias_regularizer)\n self.activity_regularizer = regularizers.get(activity_regularizer)\n self.kernel_constraint = constraints.get(kernel_constraint)\n self.bias_constraint = constraints.get(bias_constraint)\n self.input_spec = InputSpec(ndim=3)\n self.mask = mask\n\n @tf_utils.shape_type_conversion\n def build(self, input_shape):\n if self.data_format == 'channels_first':\n input_dim, input_length = input_shape[1], input_shape[2]\n else:\n input_dim, input_length = input_shape[2], input_shape[1]\n\n if input_dim is None:\n raise ValueError('Axis 2 of input should be fully-defined. '\n 'Found shape:', input_shape)\n self.output_length = self.mask.shape[1]\n# print(\"output length is \" + str(self.output_length))\n if self.data_format == 'channels_first':\n self.kernel_shape = (input_dim, input_length,\n self.filters, self.output_length)\n else:\n self.kernel_shape = (input_length, input_dim,\n self.output_length, self.filters)\n\n self.kernel = self.add_weight(shape=(len(self.mask.data),), # sum of all nonzero values in mask sum(sum(mask))\n initializer=self.kernel_initializer,\n name='kernel',\n regularizer=self.kernel_regularizer,\n constraint=self.kernel_constraint)\n\n self.kernel_mask = get_locallyDirected1D_mask(self.mask, self.kernel,\n data_format=self.data_format,\n dtype=self.kernel.dtype\n )\n\n if self.use_bias:\n self.bias = self.add_weight(\n shape=(self.output_length, self.filters),\n initializer=self.bias_initializer,\n name='bias',\n regularizer=self.bias_regularizer,\n constraint=self.bias_constraint)\n else:\n self.bias = None\n\n if self.data_format == 'channels_first':\n self.input_spec = InputSpec(ndim=3, axes={1: input_dim})\n else:\n self.input_spec = InputSpec(ndim=3, axes={-1: input_dim})\n self.built = True\n\n def call(self, inputs):\n\n # output = local_conv_matmul(inputs, self.kernel_mask,\n # self.output_length)\n\n output = local_conv_matmul_sparse(inputs, self.kernel_mask,\n self.output_length, self.filters)\n\n if self.use_bias:\n output = K.bias_add(output, self.bias, data_format=self.data_format)\n\n output = self.activation(output)\n return output\n\n def get_config(self): # delete this?\n config = {\n 'filters':\n self.filters,\n 'padding':\n self.padding,\n 'data_format':\n self.data_format,\n 'activation':\n activations.serialize(self.activation),\n 'use_bias':\n self.use_bias,\n 'kernel_initializer':\n initializers.serialize(self.kernel_initializer),\n 'bias_initializer':\n initializers.serialize(self.bias_initializer),\n 'kernel_regularizer':\n regularizers.serialize(self.kernel_regularizer),\n 'bias_regularizer':\n regularizers.serialize(self.bias_regularizer),\n 'activity_regularizer':\n regularizers.serialize(self.activity_regularizer),\n 'kernel_constraint':\n constraints.serialize(self.kernel_constraint),\n 'bias_constraint':\n constraints.serialize(self.bias_constraint),\n }\n base_config = super(LocallyDirected1D, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\ndef get_locallyDirected1D_mask(mask, kernel, data_format,\n dtype):\n \"\"\"Return a mask representing connectivity of a locally-connected operation.\n\n This method returns a masking tensor of 0s and 1s (of type `dtype`) that,\n when element-wise multiplied with a fully-connected weight tensor, masks out\n the weights between disconnected input-output pairs and thus implements local\n connectivity through a sparse fully-connected weight tensor.\n\n Assume an unshared convolution with given parameters is applied to an input\n having N spatial dimensions with `input_shape = (d_in1, ..., d_inN)`\n to produce an output with spatial shape `(d_out1, ..., d_outN)` (determined\n by layer parameters such as `strides`).\n\n This method returns a mask which can be broadcast-multiplied (element-wise)\n with a 2*(N+1)-D weight matrix (equivalent to a fully-connected layer between\n (N+1)-D activations (N spatial + 1 channel dimensions for input and output)\n to make it perform an unshared convolution with given `kernel_shape`,\n `strides`, `padding` and `data_format`.\n\n Arguments:\n mask: sparse connectivity matrix matrix\n kernel: weights with len(sum(non-sparse values)\n data_format: a string, `\"channels_first\"` or `\"channels_last\"`.\n dtype: type of the layer operation, e.g. `tf.float64`.\n\n Returns:\n a `dtype`-tensor of shape\n `(1, d_in1, ..., d_inN, 1, d_out1, ..., d_outN)`\n if `data_format == `\"channels_first\"`, or\n `(d_in1, ..., d_inN, 1, d_out1, ..., d_outN, 1)`\n if `data_format == \"channels_last\"`.\n\n Adaption by arno is now a sparse matrix.\n Raises:\n ValueError: if `data_format` is neither `\"channels_first\"` nor\n `\"channels_last\"`.\n \"\"\"\n\n ndims = int(mask.ndim / 2)\n indices = np.mat([mask.row, mask.col]).transpose()\n# print(mask.shape)\n mask = tf.SparseTensor(indices, kernel, [mask.shape[0], mask.shape[1]])\n\n if data_format == 'channels_first':\n mask = tf.sparse.expand_dims(mask, 0)\n mask = tf.sparse.expand_dims(mask, - ndims - 1)\n\n elif data_format == 'channels_last':\n mask = tf.sparse.expand_dims(mask, ndims)\n mask = tf.sparse.expand_dims(mask, -1)\n\n else:\n raise ValueError('Unrecognized data_format: ' + str(data_format))\n\n return mask\n\n\ndef local_conv_matmul_sparse(inputs, kernel_mask, output_length, filters):\n \"\"\"Apply N-D convolution with un-shared weights using a single matmul call.\n\n This method outputs `inputs . (kernel * kernel_mask)`\n (with `.` standing for matrix-multiply and `*` for element-wise multiply)\n and requires a precomputed `kernel_mask` to zero-out weights in `kernel` and\n hence perform the same operation as a convolution with un-shared\n (the remaining entries in `kernel`) weights. It also does the necessary\n reshapes to make `inputs` and `kernel` 2-D and `output` (N+2)-D.\n\n Arguments:\n inputs: (N+2)-D tensor with shape\n `(batch_size, channels_in, d_in1, ..., d_inN)`\n or\n `(batch_size, d_in1, ..., d_inN, channels_in)`.\n kernel: the unshared weights for N-D convolution,\n an (N+2)-D tensor of shape:\n `(d_in1, ..., d_inN, channels_in, d_out2, ..., d_outN, channels_out)`\n or\n `(channels_in, d_in1, ..., d_inN, channels_out, d_out2, ..., d_outN)`,\n with the ordering of channels and spatial dimensions matching\n that of the input.\n Each entry is the weight between a particular input and\n output location, similarly to a fully-connected weight matrix.\n kernel_mask: a float 0/1 mask tensor of shape:\n `(d_in1, ..., d_inN, 1, d_out2, ..., d_outN, 1)`\n or\n `(1, d_in1, ..., d_inN, 1, d_out2, ..., d_outN)`,\n with the ordering of singleton and spatial dimensions\n matching that of the input.\n Mask represents the connectivity pattern of the layer and is\n precomputed elsewhere based on layer parameters: stride,\n padding, and the receptive field shape.\n output_shape: a tuple of (N+2) elements representing the output shape:\n `(batch_size, channels_out, d_out1, ..., d_outN)`\n or\n `(batch_size, d_out1, ..., d_outN, channels_out)`,\n with the ordering of channels and spatial dimensions matching that of\n the input.\n\n Returns:\n Output (N+2)-D tensor with shape `output_shape`.\n \"\"\"\n inputs_flat = K.reshape(inputs, (K.shape(inputs)[0], -1))\n kernel_mask = make_2d_sparse(kernel_mask, split_dim=K.ndim(kernel_mask) // 2)\n output_flat = tf.sparse.matmul(kernel_mask, inputs_flat, adjoint_a=True, adjoint_b=True)\n output_flat = tf.transpose(output_flat)\n output = K.reshape(output_flat, [-1, output_length, filters])\n\n return output\n\n\ndef make_2d_sparse(tensor, split_dim):\n \"\"\"Reshapes an N-dimensional tensor into a 2D tensor.\n\n Dimensions before (excluding) and after (including) `split_dim` are grouped\n together.\n\n Arguments:\n tensor: a tensor of shape `(d0, ..., d(N-1))`.\n split_dim: an integer from 1 to N-1, index of the dimension to group\n dimensions before (excluding) and after (including).\n\n Returns:\n Tensor of shape\n `(d0 * ... * d(split_dim-1), d(split_dim) * ... * d(N-1))`.\n \"\"\"\n\n shape = K.array_ops.shape(tensor)\n in_dims = shape[:split_dim]\n out_dims = shape[split_dim:]\n\n in_size = K.math_ops.reduce_prod(in_dims)\n out_size = K.math_ops.reduce_prod(out_dims)\n\n return tf.sparse.reshape(tensor, (in_size, out_size))\n\n\ndef local_conv_matmul(inputs, kernel_mask, output_length):\n \"\"\"Apply N-D convolution with un-shared weights using a single matmul call.\n\n This method outputs `inputs . (kernel * kernel_mask)`\n (with `.` standing for matrix-multiply and `*` for element-wise multiply)\n and requires a precomputed `kernel_mask` to zero-out weights in `kernel` and\n hence perform the same operation as a convolution with un-shared\n (the remaining entries in `kernel`) weights. It also does the necessary\n reshapes to make `inputs` and `kernel` 2-D and `output` (N+2)-D.\n\n Arguments:\n inputs: (N+2)-D tensor with shape\n `(batch_size, channels_in, d_in1, ..., d_inN)`\n or\n `(batch_size, d_in1, ..., d_inN, channels_in)`.\n kernel: the unshared weights for N-D convolution,\n an (N+2)-D tensor of shape:\n `(d_in1, ..., d_inN, channels_in, d_out2, ..., d_outN, channels_out)`\n or\n `(channels_in, d_in1, ..., d_inN, channels_out, d_out2, ..., d_outN)`,\n with the ordering of channels and spatial dimensions matching\n that of the input.\n Each entry is the weight between a particular input and\n output location, similarly to a fully-connected weight matrix.\n kernel_mask: a float 0/1 mask tensor of shape:\n `(d_in1, ..., d_inN, 1, d_out2, ..., d_outN, 1)`\n or\n `(1, d_in1, ..., d_inN, 1, d_out2, ..., d_outN)`,\n with the ordering of singleton and spatial dimensions\n matching that of the input.\n Mask represents the connectivity pattern of the layer and is\n precomputed elsewhere based on layer parameters: stride,\n padding, and the receptive field shape.\n output_shape: a tuple of (N+2) elements representing the output shape:\n `(batch_size, channels_out, d_out1, ..., d_outN)`\n or\n `(batch_size, d_out1, ..., d_outN, channels_out)`,\n with the ordering of channels and spatial dimensions matching that of\n the input.\n\n Returns:\n Output (N+2)-D tensor with shape `output_shape`.\n \"\"\"\n inputs_flat = K.reshape(inputs, (K.shape(inputs)[0], -1))\n\n kernel = make_2d_sparse(kernel_mask, split_dim=K.ndim(kernel_mask) // 2)\n\n output_flat = tf.sparse_tensor_dense_matmul(inputs_flat, kernel, b_is_sparse=True)\n output = K.reshape(output_flat, [-1, output_length, 1])\n return output\n\n\ndef make_2d(tensor, split_dim):\n \"\"\"Reshapes an N-dimensional tensor into a 2D tensor.\n\n Dimensions before (excluding) and after (including) `split_dim` are grouped\n together.\n\n Arguments:\n tensor: a tensor of shape `(d0, ..., d(N-1))`.\n split_dim: an integer from 1 to N-1, index of the dimension to group\n dimensions before (excluding) and after (including).\n\n Returns:\n Tensor of shape\n `(d0 * ... * d(split_dim-1), d(split_dim) * ... * d(N-1))`.\n \"\"\"\n# print(tensor.shape)\n shape = K.array_ops.shape(tensor)\n in_dims = shape[:split_dim]\n out_dims = shape[split_dim:]\n\n in_size = K.math_ops.reduce_prod(in_dims)\n out_size = K.math_ops.reduce_prod(out_dims)\n\n return K.array_ops.reshape(tensor, (in_size, out_size))\n\n# %%\n" ]
[ [ "tensorflow.python.keras.utils.conv_utils.normalize_data_format", "tensorflow.python.keras.backend.bias_add", "tensorflow.sparse.reshape", "tensorflow.sparse.expand_dims", "tensorflow.sparse_tensor_dense_matmul", "numpy.mat", "tensorflow.SparseTensor", "tensorflow.python.keras.backend.ndim", "tensorflow.python.keras.activations.serialize", "tensorflow.transpose", "tensorflow.python.keras.initializers.get", "tensorflow.python.keras.constraints.get", "tensorflow.python.keras.backend.array_ops.shape", "tensorflow.python.keras.backend.array_ops.reshape", "tensorflow.python.keras.activations.get", "tensorflow.python.keras.utils.conv_utils.normalize_padding", "tensorflow.python.keras.backend.shape", "tensorflow.python.keras.regularizers.get", "tensorflow.python.keras.initializers.serialize", "tensorflow.python.keras.backend.math_ops.reduce_prod", "tensorflow.python.keras.engine.base_layer.InputSpec", "tensorflow.python.keras.backend.reshape", "tensorflow.python.keras.constraints.serialize", "tensorflow.python.keras.regularizers.serialize", "tensorflow.python.util.tf_export.tf_export", "tensorflow.sparse.matmul" ] ]
wei-mao-2019/gsps
[ "7f8de905f49bc739747174ade343a431ec8fe74e" ]
[ "motion_pred/utils/dataset.py" ]
[ "import numpy as np\n\n\nclass Dataset:\n\n def __init__(self, mode, t_his, t_pred, actions='all'):\n self.mode = mode\n self.t_his = t_his\n self.t_pred = t_pred\n self.t_total = t_his + t_pred\n self.actions = actions\n self.prepare_data()\n self.std, self.mean = None, None\n self.data_len = sum([seq.shape[0] for data_s in self.data.values() for seq in data_s.values()])\n self.traj_dim = (self.kept_joints.shape[0] - 1) * 3\n self.normalized = False\n # iterator specific\n self.sample_ind = None\n\n def prepare_data(self):\n raise NotImplementedError\n\n def normalize_data(self, mean=None, std=None):\n if mean is None:\n all_seq = []\n for data_s in self.data.values():\n for seq in data_s.values():\n all_seq.append(seq[:, 1:])\n all_seq = np.concatenate(all_seq)\n self.mean = all_seq.mean(axis=0)\n self.std = all_seq.std(axis=0)\n else:\n self.mean = mean\n self.std = std\n for data_s in self.data.values():\n for action in data_s.keys():\n data_s[action][:, 1:] = (data_s[action][:, 1:] - self.mean) / self.std\n self.normalized = True\n\n def sample(self):\n subject = np.random.choice(self.subjects)\n dict_s = self.data[subject]\n action = np.random.choice(list(dict_s.keys()))\n seq = dict_s[action]\n fr_start = np.random.randint(seq.shape[0] - self.t_total)\n fr_end = fr_start + self.t_total\n traj = seq[fr_start: fr_end]\n return traj[None, ...]\n\n def sampling_generator(self, num_samples=1000, batch_size=8):\n for i in range(num_samples // batch_size):\n sample = []\n for i in range(batch_size):\n sample_i = self.sample()\n sample.append(sample_i)\n sample = np.concatenate(sample, axis=0)\n yield sample\n\n def iter_generator(self, step=25):\n for data_s in self.data.values():\n for seq in data_s.values():\n seq_len = seq.shape[0]\n for i in range(0, seq_len - self.t_total, step):\n traj = seq[None, i: i + self.t_total]\n yield traj\n\n\n\n" ]
[ [ "numpy.concatenate", "numpy.random.randint", "numpy.random.choice" ] ]
nb-377/OPF-Tutorial
[ "186d97edde9dff3ab631006bf7e426853e0cb1f3" ]
[ "OPF_Tutotial_Islanded_charging_git.py" ]
[ "# This script was written by Nicholas Barry on 2/16/2022. It is part of a tutorial on optimum power flow.\r\n# This script demonstrates ESS charging on an islanded microgrid using optimal power flow.\r\n# It connects to OpenDSS for some inputs and validation of the resulting voltage and powers.\r\n# This is intended for educational purposes as a spring board for further research in electrical power systems.\r\n\r\n# Import libraries\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\n#import pyomo.environ as pyo\r\nfrom pyomo.environ import *\r\nfrom pyomo.opt import SolverStatus, TerminationCondition\r\nimport numpy as np\r\nfrom dss import DSS\r\nimport os\r\nfrom pyomo.core import *\r\nfrom pyomo.opt import SolverFactory\r\n\r\n\r\nclass Object(object): # setup object class\r\n pass # do nothing\r\n\r\n# set the path to you OpenDSS file here:\r\ndssFileName = r'C:\\Users\\nicho\\OneDrive - The University of Texas at Austin\\Desktop\\Research\\OPF Nanogrid\\OPF Nanogrid Tutorial\\OpenDSS Files\\islanded_charging_git.dss'\r\n\r\n#------------------------------ Load system and extract admittance matrix---------------------------------------------#\r\nDSS.Start(0) # initiate DSS COM interface\r\nText = DSS.Text # name DSS Text interface to control\r\nCircuit = DSS.Circuits # setup circuit instance\r\nSolution = DSS.Circuits.Solution # setup solution instance\r\n\r\nCircuitPath, CircuitName = os.path.split(dssFileName) # break file name off from path\r\nCircuitName_No_Ext= os.path.splitext(CircuitName)[0]\r\n\r\nText.Command = r\"Clear\" # clear circuit for fresh run\r\nText.Command = f\"Compile ({dssFileName})\" # compile DSS file\r\nText.Command = 'vsource.source.enabled=no' # disable source for Y matrix build\r\nText.Command = \"batchedit load..* enabled=false\" # disable all loads to build Y matrix\r\nText.Command = \"batchedit PVsystem..* enabled=false\" # disable all loads to build Y matrix\r\nText.Command = \"batchedit storage..* enabled=false\" # disable all loads to build Y matrix\r\nText.Command = \"disable vsource.source\" # disable voltage source\r\nText.Command = \"CalcV\" # calculate voltage bases\r\nText.Command = \"Solve\" # solve circuit\r\n\r\nY = Circuit.SystemY # collect Y matrix of file\r\nY = np.array(Y, dtype = float) # convert Y to a numpy array to do math\r\nY = np.reshape(Y, (int(np.sqrt(np.size(Y)/2)), -1)) # reshape Y into a node x node matrix\r\n# print(Y) # prints Y matrix for inspection\r\nG = Y[: , ::2] # seperate G from Y (real) for rectangular calcs\r\nB = Y[: , 1::2] # seperate B from Y (imag)\r\n\r\n# Form G matrix for phase A\r\nG_A =G\r\nG_A = np.delete(G_A,2,axis=1)\r\nG_A = np.delete(G_A,2,axis=1)\r\nG_A = np.delete(G_A,3,axis=1)\r\nG_A = np.delete(G_A,3,axis=1)\r\nG_A = np.delete(G_A,4,axis=1)\r\nG_A = np.delete(G_A,4,axis=1)\r\n\r\nG_A = np.delete(G_A,2,axis=0)\r\nG_A = np.delete(G_A,2,axis=0)\r\nG_A = np.delete(G_A,3,axis=0)\r\nG_A = np.delete(G_A,3,axis=0)\r\nG_A = np.delete(G_A,4,axis=0)\r\nG_A = np.delete(G_A,4,axis=0)\r\n\r\n# Form G matrix for phase B\r\nG_B = G\r\nG_B = np.delete(G_B, 0, axis=1)\r\nG_B = np.delete(G_B, 0, axis=1)\r\nG_B = np.delete(G_B, 1, axis=1)\r\nG_B = np.delete(G_B, 1, axis=1)\r\nG_B = np.delete(G_B, 2, axis=1)\r\nG_B = np.delete(G_B, 2, axis=1)\r\nG_B = np.delete(G_B, 3, axis=1)\r\n\r\nG_B = np.delete(G_B, 0, axis=0)\r\nG_B = np.delete(G_B, 0, axis=0)\r\nG_B = np.delete(G_B, 1, axis=0)\r\nG_B = np.delete(G_B, 1, axis=0)\r\nG_B = np.delete(G_B, 2, axis=0)\r\nG_B = np.delete(G_B, 2, axis=0)\r\nG_B = np.delete(G_B, 3, axis=0)\r\n\r\n# From G matrix for phase C\r\nG_C = G\r\nG_C = np.delete(G_C, 0, axis=1)\r\nG_C = np.delete(G_C, 0, axis=1)\r\nG_C = np.delete(G_C, 0, axis=1)\r\nG_C = np.delete(G_C, 1, axis=1)\r\nG_C = np.delete(G_C, 1, axis=1)\r\nG_C = np.delete(G_C, 2, axis=1)\r\nG_C = np.delete(G_C, 2, axis=1)\r\n\r\nG_C = np.delete(G_C, 0, axis=0)\r\nG_C = np.delete(G_C, 0, axis=0)\r\nG_C = np.delete(G_C, 0, axis=0)\r\nG_C = np.delete(G_C, 1, axis=0)\r\nG_C = np.delete(G_C, 1, axis=0)\r\nG_C = np.delete(G_C, 2, axis=0)\r\nG_C = np.delete(G_C, 2, axis=0)\r\n\r\n# Form B matrix for phase A\r\nB_A =B\r\nB_A = np.delete(B_A,2,axis=1)\r\nB_A = np.delete(B_A,2,axis=1)\r\nB_A = np.delete(B_A,3,axis=1)\r\nB_A = np.delete(B_A,3,axis=1)\r\nB_A = np.delete(B_A,4,axis=1)\r\nB_A = np.delete(B_A,4,axis=1)\r\n\r\nB_A = np.delete(B_A,2,axis=0)\r\nB_A = np.delete(B_A,2,axis=0)\r\nB_A = np.delete(B_A,3,axis=0)\r\nB_A = np.delete(B_A,3,axis=0)\r\nB_A = np.delete(B_A,4,axis=0)\r\nB_A = np.delete(B_A,4,axis=0)\r\n\r\n# Form B matrix for phase B\r\nB_B = B\r\nB_B = np.delete(B_B, 0, axis=1)\r\nB_B = np.delete(B_B, 0, axis=1)\r\nB_B = np.delete(B_B, 1, axis=1)\r\nB_B = np.delete(B_B, 1, axis=1)\r\nB_B = np.delete(B_B, 2, axis=1)\r\nB_B = np.delete(B_B, 2, axis=1)\r\nB_B = np.delete(B_B, 3, axis=1)\r\n\r\nB_B = np.delete(B_B, 0, axis=0)\r\nB_B = np.delete(B_B, 0, axis=0)\r\nB_B = np.delete(B_B, 1, axis=0)\r\nB_B = np.delete(B_B, 1, axis=0)\r\nB_B = np.delete(B_B, 2, axis=0)\r\nB_B = np.delete(B_B, 2, axis=0)\r\nB_B = np.delete(B_B, 3, axis=0)\r\n\r\n# From B matrix for phase C\r\nB_C = B\r\nB_C = np.delete(B_C, 0, axis=1)\r\nB_C = np.delete(B_C, 0, axis=1)\r\nB_C = np.delete(B_C, 0, axis=1)\r\nB_C = np.delete(B_C, 1, axis=1)\r\nB_C = np.delete(B_C, 1, axis=1)\r\nB_C = np.delete(B_C, 2, axis=1)\r\nB_C = np.delete(B_C, 2, axis=1)\r\n\r\nB_C = np.delete(B_C, 0, axis=0)\r\nB_C = np.delete(B_C, 0, axis=0)\r\nB_C = np.delete(B_C, 0, axis=0)\r\nB_C = np.delete(B_C, 1, axis=0)\r\nB_C = np.delete(B_C, 1, axis=0)\r\nB_C = np.delete(B_C, 2, axis=0)\r\nB_C = np.delete(B_C, 2, axis=0)\r\n\r\n# check to see order of node names for match to Y matrix order\r\nnode_names = Circuit.AllNodeNames # collect node names in order\r\nprint(\"Admittance calculation node order:\")\r\nprint(node_names) # print results\r\n\r\ndss_var = Object()\r\nText.Command = r\"Clear\" # clear circuit for fresh run\r\nText.Command = f\"Compile ({dssFileName})\" # compile DSS file\r\nText.Command = \"CalcV\" # calculate voltage bases\r\nText.Command = 'Solve' # solve the circuit in OpenDSS\r\nText.Command = 'show voltages LN nodes' # use for validation\r\nText.Command = 'show powers elements' # use for validation\r\n\r\n# Get voltages\r\nV = np.array(Circuit.AllBusVolts)\r\nV = np.reshape(V, (-1,2))\r\nVC = np.ravel(V[:,::2]) + 1.0j*np.ravel(V[:,1::2])\r\ndss_var.Vang = np.angle(VC) # in rad\r\ndss_var.Vmag = np.abs(VC) # in V.\r\ndss_var.Vpu = dss_var.Vmag/120 # in V.\r\n\r\n# all node names\r\ndss_var.allNodeNames = np.asarray(Circuit.AllNodeNames, dtype=str)\r\nnode_names = np.asarray(DSS.Circuits.AllNodeNames, dtype=str)\r\nprint(\"Un-altered node order:\")\r\nprint(node_names)\r\n\r\ndss_var.allNodeNames = node_names\r\ndss_var.Vang = dss_var.Vang # in rad\r\ndss_var.Vmag = dss_var.Vmag # in V.\r\ndss_var.Vpu = dss_var.Vpu # in V.\r\ndss_var.timestep = 60*15 # time step in seconds\r\nit = 0 # initiate iteration counter\r\n\r\n# -------------------------------------set simulation configuration options ---------------------------------------- #\r\n\r\noutput = \"robust\" # provides voltages by bus in output\r\n\r\nstart_hour = 0 # initialize start time, fractional hour\r\nit = int(start_hour * dss_var.timestep) # calculate iteration number based on starting time\r\nhour = start_hour # set hour to starting hour\r\nit = 0\r\nobj = 'max soc max PV min Q' # set objective\r\n\r\n############### -------------------- End of Simualation configuration --------------------------------------############\r\nirrad = .9 # sets irradiation to 90% of rated value\r\n\r\n# pull in load shapes\r\nload = pd.read_csv(r\"C:\\Users\\nicho\\OneDrive - The University of Texas at Austin\\Desktop\\Research\\OPF Nanogrid\\OPF Nanogrid Tutorial\\OpenDSS Files\\loadshape.csv\")\r\n\r\nload_2_P_A = load.iloc[:, 0].values\r\nload_2_Q_A = load.iloc[:, 1].values\r\nload_2_P_B = load.iloc[:, 2].values\r\nload_2_Q_B = load.iloc[:, 3].values\r\nload_2_P_C = load.iloc[:, 4].values\r\nload_2_Q_C = load.iloc[:, 5].values\r\nload_1_P_A = load.iloc[:, 6].values\r\nload_1_Q_A = load.iloc[:, 7].values\r\nload_1_P_B = load.iloc[:, 8].values\r\nload_1_Q_B = load.iloc[:, 9].values\r\nload_1_P_C = load.iloc[:, 10].values\r\nload_1_Q_C = load.iloc[:, 11].values\r\nload_3_P_A = load.iloc[:, 12].values\r\nload_3_Q_A = load.iloc[:, 13].values\r\n\r\n# --------------------- Setup Output Variables------------------------------------------------------#\r\ntime = [None]\r\nPV_A_P = [0]\r\nPV_A_Q = [0]\r\nPV_B_P = [0]\r\nPV_B_Q = [0]\r\nPV_C_P = [0]\r\nPV_C_Q = [0]\r\nV_PV_A = [0]\r\nV_PV_B = [0]\r\nV_PV_C = [0]\r\nload_P = [0]\r\nload_Q = [0]\r\nES_SOC = [0]\r\nES_A_P = [0]\r\nES_B_P = [0]\r\nES_C_P = [0]\r\nES_A_Q = [0]\r\nES_B_Q = [0]\r\nES_C_Q = [0]\r\nV_load_1_A = [0]\r\nV_load_1_B = [0]\r\nV_load_1_C = [0]\r\nV_load_2_A = [0]\r\nV_load_2_B = [0]\r\nV_load_2_C = [0]\r\nV_load_3 =[0]\r\n\r\nES = Object() # setup energy storage object\r\nES.P_rated = 25000 # ES rated power (W)\r\nES.A_P_rated = ES.P_rated / 3 # Phase A rated ESS Real power\r\nES.A_S_rated = 1.5 * ES.P_rated / 3 # ES rated complex power in VA\r\nES.B_P_rated = ES.P_rated / 3 # Phase A rated ESS Real power\r\nES.B_S_rated = 1.5 * ES.P_rated / 3 # ES rated complex power in VA\r\nES.C_P_rated = ES.P_rated / 3 # Phase A rated ESS Real power\r\nES.C_S_rated = 1.5 * ES.P_rated / 3 # ES rated complex power in VA\r\nES.E_rated = 25000 # ES rated energy in Wh\r\nES.P_A = ES.A_P_rated # set to rated power to start\r\nES.P_B = ES.B_P_rated # set to rated power to start\r\nES.P_C = ES.C_P_rated # set to rated power to start\r\nES.pf = 0.9 # ES power factor\r\nES.A_Q = np.sqrt((ES.A_P_rated/ES.pf)**2 - ES.A_P_rated**2) # set to corresponding Q pf for P discharge\r\nES.B_Q = np.sqrt((ES.B_P_rated/ES.pf)**2 - ES.B_P_rated**2) # set to corresponding Q pf for P discharge\r\nES.A_Q = np.sqrt((ES.C_P_rated/ES.pf)**2 - ES.C_P_rated**2) # set to corresponding Q pf for P discharge\r\nES.SOC = 0.50 # set ES state of charge (%, 0-1)\r\nES.SOC_updated = ES.SOC # setup SoC updated instance\r\n# ES.N = 0.965 # one way efficiency of ESS\r\n\r\n# define load objects\r\nload_3_A = Object()\r\nload_3_A.P_rated = 10000\r\nload_3_A.Q_rated = 5000\r\nload_3_A.P = load_3_A.P_rated * load_3_P_A[it]\r\nload_3_A.Q = load_3_A.Q_rated * load_3_Q_A[it]\r\n\r\nload_2_A = Object()\r\nload_2_A.P_rated = 10000\r\nload_2_A.Q_rated = 10000\r\nload_2_A.P = load_2_A.P_rated * load_2_P_A[it]\r\nload_2_A.Q = load_2_A.Q_rated * load_2_Q_A[it]\r\n\r\nload_2_B = Object()\r\nload_2_B.P_rated = 10000\r\nload_2_B.Q_rated = 10000\r\nload_2_B.P = load_2_B.P_rated * load_2_P_B[it]\r\nload_2_B.Q = load_2_B.Q_rated * load_2_Q_B[it]\r\n\r\nload_2_C = Object()\r\nload_2_C.P_rated = 10000\r\nload_2_C.Q_rated = 10000\r\nload_2_C.P = load_2_C.P_rated * load_2_P_C[it]\r\nload_2_C.Q = load_2_C.Q_rated * load_2_Q_C[it]\r\n\r\nload_1_A = Object()\r\nload_1_A.P_rated = 10000\r\nload_1_A.Q_rated = 10000\r\nload_1_A.P = load_1_A.P_rated * load_1_P_A[it]\r\nload_1_A.Q = load_1_A.Q_rated * load_1_Q_A[it]\r\n\r\nload_1_B = Object()\r\nload_1_B.P_rated = 10000\r\nload_1_B.Q_rated = 10000\r\nload_1_B.P = load_1_B.P_rated * load_1_P_B[it]\r\nload_1_B.Q = load_1_B.Q_rated * load_1_Q_B[it]\r\n\r\nload_1_C = Object()\r\nload_1_C.P_rated = 10000\r\nload_1_C.Q_rated = 10000\r\nload_1_C.P = load_1_C.P_rated * load_1_P_C[it]\r\nload_1_C.Q = load_1_C.Q_rated * load_1_Q_C[it]\r\n\r\nPV_A = Object() # setup the first PV system parameters\r\nPV_A.P_rated = 8000 # PV1 rated power in W\r\nPV_A.S_rated = 12000 # PV1 rated complex power in VA\r\nPV_A.pf = 1 # PV 1 power factor\r\nPV_A.Q = 0 # PV 1 reactive power\r\nPV_A.P0 = PV_A.P_rated * irrad # calculated P given irrad\r\n\r\nPV_B = Object() # setup the first PV system parameters\r\nPV_B.P_rated = 8000 # PV1 rated power in W\r\nPV_B.S_rated = 12000 # PV1 rated complex power in VA\r\nPV_B.pf = 1 # PV 1 power factor\r\nPV_B.Q = 0 # PV 1 reactive power\r\nPV_B.P0 = PV_B.P_rated * irrad # calculated P given irrad\r\nPV_C = Object() # setup the first PV system parameters\r\nPV_C.P_rated = 8000 # PV1 rated power in W\r\nPV_C.S_rated = 12000 # PV1 rated complex power in VA\r\nPV_C.pf = 1 # PV 1 power factor\r\nPV_C.Q = 0 # PV 1 reactive power\r\n# PV_C.P0 = PV_C.P_rated * irrad[it] # calculated P given irrad\r\nPV_C.P0 = PV_C.P_rated * irrad # calculated P given irrad\r\n\r\nES.SOC = ES.SOC_updated # update SoC for next iteration\r\n\r\nbus_voltage = 120 # sets per unit voltage base in line to neutral\r\n# -------------------------------------------setup OPF model----------------------------------------------------------#\r\nopf = ConcreteModel() # setup model instance in Pyomo\r\nopf.n = range(len(node_names)) # set up number of nodes in Pyomo\r\n\r\nnode_names_A = np.array([0,3,4,7]) # create array of node names for phase A\r\nopf.n_A = range(len(node_names_A))\r\n\r\nnode_names_B = np.array([1,5,8]) # create array of node names for phase A\r\nopf.n_B = range(len(node_names_B))\r\n\r\nnode_names_C = np.array([2,6,9]) # create array of node names for phase A\r\nopf.n_C = range(len(node_names_C))\r\n\r\n# define variables for optimization\r\nopf.V_A = Var(opf.n_A, initialize=bus_voltage) # initialize voltage magnitude at 1.0 pu for phase A nodes\r\nopf.V_B = Var(opf.n_B, initialize=bus_voltage) # initialize voltage magnitude at 1.0 pu for phase B nodes\r\nopf.V_C = Var(opf.n_C, initialize=bus_voltage) # initialize voltage magnitude at 1.0 pu for phase C nodes\r\n\r\nopf.Vang_A = Var(opf.n_A, initialize=0) # initialize voltage angle for phase A nodes\r\nopf.Vang_B = Var(opf.n_B, initialize=-2.0944) # initialize voltage angle for phase B nodes (rads)\r\nopf.Vang_C = Var(opf.n_C, initialize=2.0944) # initialize voltage angle for phase C nodes (rads)\r\n\r\nopf.P_A = Var(opf.n_A, initialize=0) # initialize node real power\r\nopf.P_B = Var(opf.n_B, initialize=0) # initialize node real power\r\nopf.P_C = Var(opf.n_C, initialize=0) # initialize node real power\r\nopf.Q_A = Var(opf.n_A, initialize=0) # initialize node real power\r\nopf.Q_B = Var(opf.n_B, initialize=0) # initialize node real power\r\nopf.Q_C = Var(opf.n_C, initialize=0) # initialize node real power\r\n\r\nopf.ES_P_A = Var(initialize=2000) # initialize ES phase A\r\nopf.ES_P_B = Var(initialize=2000) # initialize ES phase B\r\nopf.ES_P_C = Var(initialize=2000) # initialize ES phase C\r\nopf.ES_Q_A = Var(initialize=0) # initialize ES phase A\r\nopf.ES_Q_B = Var(initialize=0) # initialize ES phase B\r\nopf.ES_Q_C = Var(initialize=0)\r\n\r\nopf.PV_P_A = Var(initialize=PV_A.P0) # initialize PV A real power\r\nopf.PV_P_B = Var(initialize=PV_B.P0) # initialize PV B real power\r\nopf.PV_P_C = Var(initialize=PV_C.P0) # initialize PV C real power\r\nopf.PV_Q_A = Var(initialize=0) # initialize PV A reactive power\r\nopf.PV_Q_B = Var(initialize=0) # initialize PV B reactive power\r\nopf.PV_Q_C = Var(initialize=0) # initialize PV C reactive power\r\n\r\n#----------------------------- define constraints for optimization----------------------------------------------------#\r\n# Constraints for P and Q calculations to tied with voltage and phase angles\r\ndef constraint_P_A(opf, i): # real power balance equation\r\n return opf.P_A[i] == opf.V_A[i]*sum(opf.V_A[j]*(G_A[i,j]*cos(opf.Vang_A[i] - opf.Vang_A[j]) + B_A[i,j]*sin(opf.Vang_A[i] - opf.Vang_A[j])) for j in opf.n_A)\r\nopf.constraint_P_A = Constraint(opf.n_A, rule=constraint_P_A) # set as rule in Pyomo\r\n\r\ndef constraint_P_B(opf, i): # real power balance equation\r\n return opf.P_B[i] == opf.V_B[i]*sum( opf.V_B[j]*(G_B[i,j]*cos(opf.Vang_B[i] - opf.Vang_B[j]) + B_B[i,j]*sin(opf.Vang_B[i] - opf.Vang_B[j])) for j in opf.n_B)\r\nopf.constraint_P_B = Constraint(opf.n_B, rule=constraint_P_B) # set as rule in Pyomo\r\n\r\ndef constraint_P_C(opf, i): # real power balance equation\r\n return opf.P_C[i] == opf.V_C[i]*sum( opf.V_C[j]*(G_C[i,j]*cos(opf.Vang_C[i] - opf.Vang_C[j]) + B_C[i,j]*sin(opf.Vang_C[i] - opf.Vang_C[j])) for j in opf.n_C)\r\nopf.constraint_P_C = Constraint(opf.n_C, rule=constraint_P_C) # set as rule in Pyomo\r\n\r\ndef constraint_Q_A(opf, i): # reactive power balance equation\r\n return opf.Q_A[i] == opf.V_A[i]*sum( opf.V_A[j]*(G_A[i,j]*sin(opf.Vang_A[i] - opf.Vang_A[j]) - B_A[i,j]*cos(opf.Vang_A[i] - opf.Vang_A[j])) for j in opf.n_A)\r\nopf.constraint_Q_A = Constraint(opf.n_A, rule=constraint_Q_A) # set as rule in Pyomo\r\n\r\ndef constraint_Q_B(opf, i): # reactive power balance equation\r\n return opf.Q_B[i] == opf.V_B[i]*sum( opf.V_B[j]*(G_B[i,j]*sin(opf.Vang_B[i] - opf.Vang_B[j]) - B_B[i,j]*cos(opf.Vang_B[i] - opf.Vang_B[j])) for j in opf.n_B)\r\nopf.constraint_Q_B = Constraint(opf.n_B, rule=constraint_Q_B) # set as rule in Pyomo\r\n\r\ndef constraint_Q_C(opf, i): # reactive power balance equation\r\n return opf.Q_C[i] == opf.V_C[i]*sum( opf.V_C[j]*(G_C[i,j]*sin(opf.Vang_C[i] - opf.Vang_C[j]) - B_C[i,j]*cos(opf.Vang_C[i] - opf.Vang_C[j])) for j in opf.n_C)\r\nopf.constraint_Q_C = Constraint(opf.n_C, rule=constraint_Q_C) # set as rule in Pyomo\r\n\r\n# constraints for real and reactive power injections\r\ndef constraint_inject_P_A(opf, n):\r\n if n == 0:\r\n return opf.P_A[0] == opf.ES_P_A\r\n elif n == 1:\r\n return opf.P_A[1] == -1*load_3_A.P\r\n elif n == 2:\r\n return opf.P_A[2] == -1*load_1_A.P\r\n elif n == 3:\r\n return opf.P_A[3] == -1*load_2_A.P + opf.PV_P_A\r\nopf.constraint_inject_P_A = Constraint(opf.n_A, rule=constraint_inject_P_A)\r\n\r\ndef constraint_inject_P_B(opf, n):\r\n if n == 0:\r\n return opf.P_B[0] == opf.ES_P_B\r\n elif n == 1:\r\n return opf.P_B[1] == -1*load_1_B.P\r\n elif n == 2:\r\n return opf.P_B[2] == -1*load_2_B.P + opf.PV_P_B\r\nopf.constraint_inject_P_B = Constraint(opf.n_B, rule=constraint_inject_P_B)\r\n\r\ndef constraint_inject_P_C(opf, n):\r\n if n == 0:\r\n return opf.P_C[0] == opf.ES_P_C\r\n elif n == 1:\r\n return opf.P_C[1] == -1*load_1_C.P\r\n elif n == 2:\r\n return opf.P_C[2] == -1*load_2_C.P + opf.PV_P_C\r\nopf.constraint_inject_P_C = Constraint(opf.n_C, rule=constraint_inject_P_C)\r\n\r\ndef constraint_inject_Q_A(opf, n):\r\n if n == 0:\r\n return opf.Q_A[0] == opf.ES_Q_A\r\n elif n == 1:\r\n return opf.Q_A[1] == -1*load_3_A.Q\r\n elif n == 2:\r\n return opf.Q_A[2] == -1*load_1_A.Q\r\n elif n == 3:\r\n return opf.Q_A[3] == -1*load_2_A.Q + opf.PV_Q_A\r\nopf.constraint_inject_Q_A = Constraint(opf.n_A, rule=constraint_inject_Q_A)\r\n\r\ndef constraint_inject_Q_B(opf, n):\r\n if n == 0:\r\n return opf.Q_B[0] == opf.ES_Q_B\r\n elif n == 1:\r\n return opf.Q_B[1] == -1*load_1_B.Q\r\n elif n == 2:\r\n return opf.Q_B[2] == -1*load_2_B.Q + opf.PV_Q_B\r\nopf.constraint_inject_Q_B = Constraint(opf.n_B, rule=constraint_inject_Q_B)\r\n\r\ndef constraint_inject_Q_C(opf, n):\r\n if n == 0:\r\n return opf.Q_C[0] == opf.ES_Q_C\r\n elif n == 1:\r\n return opf.Q_C[1] == -1*load_1_C.Q\r\n elif n == 2:\r\n return opf.Q_C[2] == -1*load_2_C.Q + opf.PV_Q_C\r\nopf.constraint_inject_Q_C = Constraint(opf.n_C, rule=constraint_inject_Q_C)\r\n\r\n# -----------------------------Constraints for PV system -------------------------------------------------------#\r\ndef constraint_PV_A_max(opf): # max P output constraint\r\n return opf.PV_P_A <= irrad * PV_A.P_rated\r\nopf.constrint_PV_A_max = Constraint(rule=constraint_PV_A_max)\r\n\r\ndef constraint_PV_B_max(opf): # max P output constraint\r\n return opf.PV_P_B <= irrad * PV_B.P_rated\r\nopf.constrint_PV_B_max = Constraint(rule=constraint_PV_B_max)\r\n\r\ndef constraint_PV_C_max(opf): # max P output constraint\r\n return opf.PV_P_C <= irrad * PV_C.P_rated\r\nopf.constraint_PV_C_max = Constraint(rule=constraint_PV_C_max)\r\n\r\ndef constraint_PV_A_min(opf):\r\n return opf.PV_P_A >= 0\r\nopf.constraint_PV_A_min = Constraint(rule=constraint_PV_A_min)\r\n\r\ndef constraint_PV_B_min(opf):\r\n return opf.PV_P_B >= 0\r\nopf.constraint_PV_B_min = Constraint(rule=constraint_PV_B_min)\r\n\r\ndef constraint_PV_C_min(opf):\r\n return opf.PV_P_C >= 0\r\nopf.constraint_PV_C_min = Constraint(rule=constraint_PV_C_min)\r\n\r\ndef constraint_PV_A_S_max(opf):\r\n return (opf.PV_P_A**2 + opf.PV_Q_A**2 <= PV_A.S_rated**2)\r\nopf.constraint_PV_A_S_max = Constraint(rule=constraint_PV_A_max)\r\n\r\ndef constraint_PV_B_S_max(opf):\r\n return (opf.PV_P_B**2 + opf.PV_Q_B**2 <= PV_B.S_rated**2)\r\nopf.constraint_PV_B_S_max = Constraint(rule=constraint_PV_B_max)\r\n\r\ndef constraint_PV_C_S_max(opf):\r\n return (opf.PV_C_B**2 + opf.PV_Q_C**2 <= PV_C.S_rated**2)\r\nopf.constraint_PV_C_S_max = Constraint(rule=constraint_PV_C_max)\r\n\r\n#------------------------constraints bus voltages and angles ---------------------------------------------------#\r\ndef constraint_slack_A_vmag(opf):\r\n return opf.V_A[0] == dss_var.Vmag[0] # enforce 1.0 pu at Gen bus\r\nopf.constraint_slack_A_vmag = Constraint(rule=constraint_slack_A_vmag)\r\n\r\ndef constraint_slack_B_vmag(opf):\r\n return opf.V_B[0] == dss_var.Vmag[1] # enforce 1.0 pu at Gen bus\r\nopf.constraint_slack_B_vmag = Constraint(rule=constraint_slack_B_vmag)\r\n\r\ndef constraint_slack_C_vmag(opf):\r\n return opf.V_C[0] == dss_var.Vmag[2] # enforce 1.0 pu at Gen bus\r\nopf.constraint_slack_C_vmag = Constraint(rule=constraint_slack_C_vmag)\r\n\r\ndef constraint_bus_V_mag_A_max(opf,n):\r\n if n == 1 or 2 or 3 or 0:\r\n return opf.V_A[n] <= 1.05 * bus_voltage # limit bus voltage to 1.05 pu\r\n else:\r\n return Constraint.Skip\r\nopf.constraint_bus_V_mag_A_max = Constraint(opf.n_A, rule=constraint_bus_V_mag_A_max)\r\n\r\ndef constraint_bus_V_mag_B_max(opf,n):\r\n if n == 1 or 2 or 0:\r\n return opf.V_B[n] <= 1.05 * bus_voltage # limit bus voltage to 1.05 pu\r\n else:\r\n return Constraint.Skip\r\nopf.constraint_bus_V_mag_B_max = Constraint(opf.n_B, rule=constraint_bus_V_mag_B_max)\r\n\r\ndef constraint_bus_V_mag_C_max(opf,n):\r\n if n == 1 or 2 or 0:\r\n return opf.V_C[n] <= 1.05 * bus_voltage # limit bus voltage to 1.05 pu\r\n else:\r\n return Constraint.Skip\r\nopf.constraint_bus_V_mag_C_max = Constraint(opf.n_C, rule=constraint_bus_V_mag_C_max)\r\n\r\ndef constraint_bus_V_mag_A_min(opf,n):\r\n if n == 1 or 2 or 3 or 0:\r\n return opf.V_A[n] >= 0.94 * bus_voltage # limit bus voltage to 1.05 pu\r\n else:\r\n return Constraint.Skip\r\nopf.constraint_bus_V_mag_A_min = Constraint(opf.n_A, rule=constraint_bus_V_mag_A_min)\r\n\r\ndef constraint_bus_V_mag_B_min(opf,n):\r\n if n == 1 or 2 or 0:\r\n return opf.V_B[n] >= 0.94 * bus_voltage # limit bus voltage to 1.05 pu\r\n else:\r\n return Constraint.Skip\r\nopf.constraint_bus_V_mag_B_min = Constraint(opf.n_B, rule=constraint_bus_V_mag_B_min)\r\n\r\ndef constraint_bus_V_mag_C_min(opf,n):\r\n if n == 1 or 2 or 0:\r\n return opf.V_C[n] >= 0.94 * bus_voltage # limit bus voltage to 1.05 pu\r\n else:\r\n return Constraint.Skip\r\nopf.constraint_bus_V_mag_C_min = Constraint(opf.n_C, rule=constraint_bus_V_mag_C_min)\r\n\r\ndef constraint_GEN_A_vangle(opf):\r\n return opf.Vang_A[0] == dss_var.Vang[0] # enforce slack bus angle = 0\r\nopf.constraint_GEN_A_vangle = Constraint(rule=constraint_GEN_A_vangle)\r\n\r\ndef constraint_GEN_B_vangle(opf):\r\n return opf.Vang_B[0] == dss_var.Vang[1] # enforce slack bus angle = -120 deg\r\nopf.constraint_GEN_B_vangle = Constraint(rule=constraint_GEN_B_vangle)\r\n#\r\ndef constraint_GEN_C_vangle(opf):\r\n return opf.Vang_C[0] == dss_var.Vang[2] # enforce slack bus angle = 120 deg\r\nopf.constraint_GEN_C_vangle = Constraint(rule=constraint_GEN_C_vangle)\r\n\r\ndef constraint_bus_V_ang_A(opf,n):\r\n if n == 1 or 2 or 3:\r\n return opf.Vang_A[n] <= 15 / 180 * np.pi # limit angle to 15 deg\r\n else:\r\n return Constraint.Skip\r\nopf.constraint_bus_ang_A = Constraint(opf.n_A, rule=constraint_bus_V_ang_A)\r\n\r\ndef constraint_bus_V_ang_B(opf,n):\r\n if n == 1 or 2:\r\n return opf.Vang_B[n] <= 15 / 180 * np.pi - 120 / 180 * np.pi # limit angle to 15 -120 deg\r\n else:\r\n return Constraint.Skip\r\nopf.constraint_bus_ang_B = Constraint(opf.n_B, rule=constraint_bus_V_ang_B)\r\n\r\ndef constraint_bus_V_ang_C(opf,n):\r\n if n == 1 or 2:\r\n return opf.Vang_C[n] <= 15 / 180 * np.pi + 120 / 180 * np.pi # limit angle to 15 + 120 deg\r\n else:\r\n return Constraint.Skip\r\nopf.constraint_bus_ang_C = Constraint(opf.n_C, rule=constraint_bus_V_ang_C)\r\n\r\ndef constraint_bus_V_ang_A_min(opf,n):\r\n if n == 1 or 2 or 3:\r\n return opf.Vang_A[n] >= -15 / 180 * np.pi # limit angle to 15 deg\r\n else:\r\n return Constraint.Skip\r\nopf.constraint_bus_ang_A_min = Constraint(opf.n_A, rule=constraint_bus_V_ang_A_min)\r\n\r\ndef constraint_bus_V_ang_B_min(opf,n):\r\n if n == 1 or 2:\r\n return opf.Vang_B[n] >= -15 / 180 * np.pi - 120 / 180 * np.pi # limit angle to 15 -120 deg\r\n else:\r\n return Constraint.Skip\r\nopf.constraint_bus_ang_B_min = Constraint(opf.n_B, rule=constraint_bus_V_ang_B_min)\r\n\r\ndef constraint_bus_V_ang_C_min(opf,n):\r\n if n == 1 or 2:\r\n return opf.Vang_C[n] >= -15 / 180 * np.pi + 120 / 180 * np.pi # limit angle to 15 + 120 deg\r\n else:\r\n return Constraint.Skip\r\nopf.constraint_bus_ang_C_min = Constraint(opf.n_C, rule=constraint_bus_V_ang_C_min)\r\n\r\n# ------------------------------- ESS Constraints --------------------------------------------------------------#\r\ndef constraint_ES_P_A_max(opf):\r\n return opf.ES_P_A <= ES.A_P_rated # limit active power output\r\nopf.constraint_ES_A_P_max = Constraint(rule=constraint_ES_P_A_max)\r\n\r\ndef constraint_ES_P_B_max(opf):\r\n return opf.ES_P_B <= ES.B_P_rated # limit active power output\r\nopf.constraint_ES_B_P_max = Constraint(rule=constraint_ES_P_B_max)\r\n\r\ndef constraint_ES_P_C_max(opf):\r\n return opf.ES_P_C <= ES.C_P_rated # limit active power output\r\nopf.constraint_ES_C_P_max = Constraint(rule=constraint_ES_P_C_max)\r\n\r\ndef constraint_ES_P_A_min(opf):\r\n return opf.ES_P_A >= -ES.A_P_rated # limit active power charging\r\nopf.constraint_ES_A_P_min = Constraint(rule=constraint_ES_P_A_min)\r\n\r\ndef constraint_ES_P_B_min(opf):\r\n return opf.ES_P_B >= -ES.B_P_rated # limit active power charging\r\nopf.constraint_ES_B_P_min = Constraint(rule=constraint_ES_P_B_min)\r\n\r\ndef constraint_ES_P_C_min(opf):\r\n return opf.ES_P_C >= -ES.C_P_rated # limit active power charging\r\nopf.constraint_ES_C_P_min = Constraint(rule=constraint_ES_P_C_min)\r\n\r\ndef constraint_ES_S_A_max(opf):\r\n return opf.ES_P_A**2 + opf.ES_Q_A**2 <= ES.A_S_rated**2 # limit S output from ES phase A\r\nopf.constraint_ES_S_A_max = Constraint(rule=constraint_ES_S_A_max)\r\n\r\ndef constraint_ES_S_B_max(opf):\r\n return opf.ES_P_B**2 + opf.ES_Q_B**2 <= ES.B_S_rated**2 # limit S output from ES phase B\r\nopf.constraint_ES_S_B_max = Constraint(rule=constraint_ES_S_B_max)\r\n\r\ndef constraint_ES_S_C_max(opf):\r\n return opf.ES_P_C**2 + opf.ES_Q_C**2 <= ES.C_S_rated**2 # limit S output from ES phase C\r\nopf.constraint_ES_S_C_max = Constraint(rule=constraint_ES_S_C_max)\r\n\r\ndef constraint_ES_soc_max(opf):\r\n return (ES.SOC - ((opf.ES_P_A + opf.ES_P_B + opf.ES_P_C) * dss_var.timestep / 3600) / ES.E_rated) <= 1\r\nopf.constraint_ES_soc_max = Constraint(rule=constraint_ES_soc_max)\r\n\r\ndef constraint_ES_soc_min(opf):\r\n return (ES.SOC - ((opf.ES_P_A + opf.ES_P_B + opf.ES_P_C) * dss_var.timestep / 3600) / ES.E_rated) >= 0.05\r\nopf.constraint_ES_soc_min = Constraint(rule=constraint_ES_soc_min)\r\n\r\n\r\n# ------------------------------Run optimization for power flow ------------------------------------------------#\r\n\r\n# ------------------- Define Objectives ------------------------------------------------------------------------#\r\n\r\ndef objective_max_soc_max_PV_min_Q(opf):\r\n # return - 1000 * (ES.SOC - ((opf.ES_P_A + opf.ES_P_B + opf.ES_P_C) * dss_var.timestep / 3600) / ES.E_rated) - 10000 * (opf.PV_P_A + opf.PV_P_B + opf.PV_P_C) / (PV_A.P_rated + PV_B.P_rated + PV_C.P_rated)\r\n return -(ES.SOC - ((opf.ES_P_A + opf.ES_P_B + opf.ES_P_C) * dss_var.timestep / 3600) / ES.E_rated) - (opf.PV_P_A + opf.PV_P_B + opf.PV_P_C) / (PV_A.P_rated + PV_B.P_rated + PV_C.P_rated) + 1000 * (opf.PV_Q_A**2 + opf.PV_Q_B**2 + opf.PV_Q_C**2 + opf.ES_Q_A**2 + opf.ES_Q_B**2 + opf.ES_Q_C**2) / ((PV_A.S_rated**2 + PV_B.S_rated**2 + PV_C.S_rated**2) + (ES.A_S_rated**2 + ES.B_S_rated**2 + ES.C_S_rated**2))\r\n\r\nif obj == 'max soc max PV min Q':\r\n opf.objective = Objective(rule=objective_max_soc_max_PV_min_Q, sense=minimize) # objective is to min neg SOC\r\n\r\n##Create the ipopt solver plugin using the ASL interface\r\nsolver = 'ipopt' # select IPOPT as solver\r\nsolver_io = 'nl' # setups proper solver interface\r\nstream_solver = False # True prints solver output to screen\r\nkeepfiles = False # True prints intermediate file names (.nl,.sol,...)\r\nopt = SolverFactory(solver, solver_io=solver_io) # setup solver\r\nopt.options['max_iter'] = '5000' # limit iterations\r\nresults = opt.solve(opf, keepfiles=keepfiles, tee=False) # show results file is tee=true\r\n\r\n# print(results.solver) # print solver results (confirms convergence)\r\n# print('\\n') # skip line for readability\r\n\r\n# re-sort voltages by node to compare with OpenDSS\r\nV_out = [None] * len(node_names)\r\nV_out[0] = opf.V_A.get_values()[0] # gen phase A\r\nV_out[1] = opf.V_B.get_values()[0] # gen phase B\r\nV_out[2] = opf.V_C.get_values()[0] # gen phase C\r\nV_out[3] = opf.V_A.get_values()[1] # load_3\r\nV_out[4] = opf.V_A.get_values()[2] # load_1 phase A\r\nV_out[5] = opf.V_B.get_values()[1] # load_1 phase B\r\nV_out[6] = opf.V_C.get_values()[1] # load_1 phase C\r\nV_out[7] = opf.V_A.get_values()[3] # load_2 phase A\r\nV_out[8] = opf.V_B.get_values()[2] # load_2 phase B\r\nV_out[9] = opf.V_C.get_values()[2] # load_2 phase C\r\n\r\n# re-sort voltage angles by node to compare with OpenDSS\r\nV_angle = [None] * len(node_names)\r\nV_angle[0] = opf.Vang_A.get_values()[0]\r\nV_angle[1] = opf.Vang_B.get_values()[0]\r\nV_angle[2] = opf.Vang_C.get_values()[0]\r\nV_angle[3] = opf.Vang_A.get_values()[1]\r\nV_angle[4] = opf.Vang_A.get_values()[2]\r\nV_angle[5] = opf.Vang_B.get_values()[1]\r\nV_angle[6] = opf.Vang_C.get_values()[1]\r\nV_angle[7] = opf.Vang_A.get_values()[3]\r\nV_angle[8] = opf.Vang_B.get_values()[2]\r\nV_angle[9] = opf.Vang_C.get_values()[2]\r\n\r\ntotal_load_P = load_1_A.P + load_3_A.P + load_2_A.P + load_1_B.P + load_2_B.P + load_1_C.P + load_2_C.P # sum load P\r\ntotal_load_Q = load_1_A.Q + load_3_A.Q + load_2_A.Q + load_1_B.Q + load_2_B.Q + load_1_C.Q + load_2_C.Q # sum load Q\r\n\r\nES.SOC_updated = (ES.SOC - ((opf.ES_P_A.value + opf.ES_P_B.value + opf.ES_P_C.value) * dss_var.timestep / 3600) / ES.E_rated)\r\n\r\n# ----------------------------- Print bus voltages ----------------------------------------------------------------#\r\nif output == \"robust\":\r\n # Extract results from opf object and print\r\n print(\"OPF Bus Voltages\")\r\n for i in range(0, len(node_names)):\r\n print(str(node_names[i]) + \" voltage is \" + str(round(V_out[i], 2)) + \" < \" + str(round(V_angle[i]*180/np.pi, 2)) + \" deg.\")\r\n\r\n print(\"\\n\")\r\n print(\"ES Active Power\")\r\n print(\"Phase A \" + str(round(opf.ES_P_A.value/1000, 2)) + \" kW, Phase B \" + str(round(opf.ES_P_B.value/1000, 2)) + \" kW, Phase C \" + str(round(opf.ES_P_C.value/1000, 2)) + \" kW\")\r\n print(\"Total ES real power is \" + str(round((opf.ES_P_A.value+opf.ES_P_B.value+opf.ES_P_C.value)/1000,2)) + \" kW\")\r\n\r\n print(\"\\n\")\r\n print(\"ES Reactive Power\")\r\n print(\"Phase A \" + str(round(opf.ES_Q_A.value/1000, 2)) + \" kvar, Phase B \" + str(round(opf.ES_Q_B.value/1000, 2)) + \" kvar, Phase C \" + str(round(opf.ES_Q_C.value/1000, 2)) + \" kvar\")\r\n print(\"Total ES reactive power is \" + str(round((opf.ES_Q_A.value+opf.ES_Q_B.value+opf.ES_Q_C.value)/1000,2)) + \" kvar\")\r\n\r\n print(\"\\n\")\r\n print(\"PV Active Power\")\r\n print(\"Phase A \" + str(round(opf.PV_P_A.value/1000, 2)) + \" kW, Phase B \" + str(round(opf.PV_P_B.value/1000, 2)) + \" kW, Phase C \" + str(round(opf.PV_P_C.value/1000, 2)) + \" kW\")\r\n print(\"Total PV real power is \" + str(round((opf.PV_P_A.value+opf.PV_P_B.value+opf.PV_P_C.value)/1000,2)) + \" kW\")\r\n\r\n print(\"\\n\")\r\n print(\"PV Reactive Power\")\r\n print(\"Phase A \" + str(round(opf.PV_Q_A.value/1000, 2)) + \" kvar, Phase B \" + str(round(opf.PV_Q_B.value/1000, 2)) + \" kvar, Phase C \" + str(round(opf.PV_Q_C.value/1000, 2)) + \" kvar\")\r\n print(\"Total PV reactive power is \" + str(round((opf.PV_Q_A.value+opf.PV_Q_B.value+opf.PV_Q_C.value)/1000,2)) + \" kvar\")\r\n\r\n print(\"\\n\")\r\n print(\"Circuit Losses\")\r\n print(\"Active power losses were \" + str(round((opf.ES_P_A.value+opf.ES_P_B.value+opf.ES_P_C.value+opf.PV_P_A.value+opf.PV_P_B.value+opf.PV_P_C.value )/1000 - total_load_P/1000,2)) + \" kW\")\r\n print(\"Reactive power losses were \" + str(round((opf.ES_Q_A.value+opf.ES_Q_B.value+opf.ES_Q_C.value+opf.PV_Q_A.value+opf.PV_Q_B.value+opf.PV_Q_C.value)/1000 - total_load_Q/1000, 2)) + \" kvar\")\r\n\r\n # need SoC updated from original\r\n print(\"\\n\")\r\n print(\"The ending SoC is \" + str(ES.SOC_updated))\r\n" ]
[ [ "numpy.array", "numpy.delete", "numpy.angle", "numpy.reshape", "numpy.asarray", "numpy.ravel", "numpy.abs", "numpy.sqrt", "numpy.size", "pandas.read_csv" ] ]
callbarian/vidsurveil_application
[ "6ced0f65ee9859d45cccfa2979ddd7a8b469d336" ]
[ "miniview.py" ]
[ "import os\nimport cv2\nimport numpy as np\nimport subprocess\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtGui import QPen, QBrush\nfrom PyQt5.Qt import Qt\nfrom PyQt5 import QtCore\n\nclass Miniview():\n def __init__(self):\n self.scene = QGraphicsScene()\n def draw_anomalous_time(self,time_frame,total_frames):\n time_frame = time_frame.reshape(-1,2)\n #self.scene.setSceneRect(0,0,894,24)\n \n #self.scene.addRect(int(886*time_frame[0,0]/total_frames),0,int(886*(time_frame[0,1]-time_frame[0,0])/total_frames),20,QPen(Qt.red),QBrush(Qt.red))\n mat = np.zeros((18,880,3),np.uint8)\n \n for i,time in enumerate(time_frame):\n if i==0:\n # the length of timeline container is 894\n start_frame = int(880*time[0]/total_frames)\n end_frame = int(880*time[1]/total_frames)\n \n pixels = [0,0,255] # red,green,blue\n for j,pixel in enumerate(pixels):\n mat[:18,start_frame:end_frame+1,j] = pixel\n \n if time[0]>0:\n # draw white for previous frame if first start_frame is bigger than 0\n mat[:18,0:start_frame-1,:] = 255\n \n else:\n # the length of timeline container is 894\n start_frame = int(880*time[0]/total_frames)\n end_frame = int(880*time[1]/total_frames)\n \n pixels = [0,0,255] # red,green,blue\n for j,pixel in enumerate(pixels):\n mat[:18,start_frame:end_frame+1,j] = pixel\n \n # draw white for previous empty timeline\n white_start_frame = int(880*time_frame[i-1,1]/total_frames) + 1 # previous end frame +1\n white_end_frame = int(880*time[0]/total_frames) - 1 # current start frame -1\n # white is [255,255,255] but rgbwill be swapped\n mat[:18,white_start_frame:white_end_frame,:] = 255\n\n # if this is the last time set \n if(i==len(time_frame)-1):\n if end_frame<total_frames:\n white_start_frame = end_frame + 1 # start frame for the last white space\n white_end_frame = 880 # last frame, int(880*(total_frames/total_frames)) -> 880\n # white is [255,255,255] but rgbwill be swapped\n mat[:18,white_start_frame:white_end_frame,:] = 255\n \n\n img = QImage(mat,mat.shape[1],mat.shape[0],QImage.Format_RGB888).rgbSwapped()\n pixMap = QPixmap.fromImage(img)\n item = QGraphicsPixmapItem(pixMap)\n self.scene.addItem(item)\n return self.scene\n\n def merge_frame(self,curr_fileName,npy_merge,interval=500):\n # find fps\n result = subprocess.Popen(['ffprobe','-v','error','-select_streams','v','-of','default=noprint_wrappers=1:nokey=1','-show_entries','stream=r_frame_rate',curr_fileName],stdout=subprocess.PIPE,stderr=subprocess.PIPE)\n result.wait()\n out = result.communicate()\n message = out[0].decode()\n message = message.split('\\n')[0]\n fps = int(message.split('/')[0])/int(message.split('/')[1])\n print('fps: ',fps)\n # initial start and end frame\n final_time = []\n start_frame = npy_merge[0,0]\n end_frame = npy_merge[0,1]\n\n added_frame = 0\n for i in range(1,len(npy_merge)):\n if (npy_merge[i,0] - start_frame) > (interval+added_frame):\n # if the difference of start frames are more than \n # interval (default=500) frames, then they are regarded as independent(different) incidents\n final_time.append([start_frame,end_frame])\n start_frame = npy_merge[i,0]\n end_frame = npy_merge[i,1]\n\n # reset added_frame \n added_frame = 0\n # the most inclusive end frame to include as many incidents(frames)\n elif npy_merge[i,1] > end_frame:\n end_frame = npy_merge[i,1]\n added_frame += npy_merge[i,0]-npy_merge[i-1,0]\n # add frame to allow including consecutive events. \n print('start frame: {}, end frame: {}, added_frame: {},total_frame: {}'.format(start_frame,end_frame,added_frame,final_time))\n final_time.append([start_frame,end_frame])\n final_time = np.array(final_time)\n \n return fps,final_time\n\n def draw_miniview(self,dir):\n image = self.show_miniview(dir)\n #self.imgQ = ImageQt.ImageQt(image)\n #print(image.shape[1],image.shape[0])\n img = QImage(image.data,image.shape[1],image.shape[0],QImage.Format_RGB888).rgbSwapped()\n pixMap = QPixmap.fromImage(img)\n item = QGraphicsPixmapItem(pixMap)\n self.scene.addItem(item)\n return self.scene\n \n def cal_timeline(self,dir):\n f = cv2.VideoCapture(dir)\n total_frames = f.get(cv2.CAP_PROP_FRAME_COUNT)\n frame_rate = f.get(cv2.CAP_PROP_FPS)\n total_length = int(total_frames/frame_rate)\n\n time_list = []\n time_interval =int(total_frames/4)\n for i in range(0,4):\n time_list.append(int(i*time_interval/frame_rate))\n time_list.append(int(total_frames/frame_rate))\n\n return time_list\n \n def show_miniview(self,dir):\n f = cv2.VideoCapture(dir)\n total_frames = f.get(cv2.CAP_PROP_FRAME_COUNT)\n frame_rate = f.get(cv2.CAP_PROP_FPS)\n total_length = int(total_frames/frame_rate)\n print('total frames:{}, frame_rate :{} '.format(total_frames,frame_rate))\n print('total length:{} '.format(total_length))\n #print(f.get(cv2.CAP_PROP_POS_FRAMES))\n # the size will be 80*80*11 (width 80, length 80, 11 images)\n\n interval = int(total_frames/11)\n frame_list = []\n for i in range(0,11):\n f_num = i*interval\n f.set(cv2.CAP_PROP_POS_FRAMES,f_num)\n ret,frame = f.read()\n assert ret\n frame_list.append(cv2.resize(frame,(80,80)))\n frame_concat = cv2.hconcat(frame_list)\n return frame_concat\n" ]
[ [ "numpy.array", "numpy.zeros" ] ]
visma-prodsec/columbo
[ "8ed803833755e41a6872a505dea6ba4baf50f355" ]
[ "runningProcesses.py" ]
[ "import forRunningProcesses\nimport os\nimport run\n\n\nimport pandas as pd\nfrom colorama import Fore\nfrom pandas import DataFrame\n\ndir_path = os.path.dirname(os.path.realpath(__file__))\n\n\ndef live_process():\n \"\"\"\n Identify live processes in combination with traceability combined with ML.\n \"\"\"\n wmic = 'wmic /output:' + dir_path + r'\\csvFiles\\Process.csv' + ' ' + 'process get Caption,ParentProcessId,' \\\n 'ProcessId,CommandLine /format:csv '\n os.system(wmic)\n\n output_ml = dir_path + r'\\csvFiles\\Process.csv'\n\n df = pd.read_csv(output_ml, delimiter=',', encoding='utf-16',\n names=['Services', 'CommandLine', 'ParentProcessId', 'ProcessId'], header=None)\n\n df1 = df[['Services', 'ParentProcessId', 'ProcessId']]\n print(Fore.WHITE)\n grouped = df1.groupby(df1['ParentProcessId'])\n for name, group in grouped:\n print('\\n')\n print(name)\n print(DataFrame(group).to_string(index=False, header=True))\n print('\\n')\n print(Fore.YELLOW + 'Above output represents clusters, organised according to their parent processes')\n print(Fore.GREEN)\n print('Type Process ID for traceability')\n process = input('Enter process ID : ')\n\n if process.isdigit():\n\n s = forRunningProcesses.loop_through(process, df)\n data = s[['Services', 'ProcessId', 'ParentProcessId', 'CommandLine']].to_string(index=False, header=False)\n\n data = list(data.split())\n # print (data)\n s0 = forRunningProcesses.loop_through(data[2], df)\n f_ind = df.loc[df['ProcessId'] == data[1]]\n ist = list()\n ist.append(data[1])\n # print (s0)\n if s0.empty or data[2] == '4' or data[2] == data[1]:\n print('\\n')\n print(Fore.YELLOW + 'Process traceability\\n')\n print(Fore.WHITE)\n print('Process ' + data[0] + '(' + process + ')' + ' has a root process of ' + ' ' + data[2])\n\n print('\\n')\n print(Fore.YELLOW + 'Involved Commands if exist - read from top to bottom:\\n')\n print(Fore.WHITE)\n p = f_ind[['Services', 'CommandLine']]\n print(f_ind[['Services', 'CommandLine']].to_string(index=False, header=True))\n forRunningProcesses.process_ml(p)\n print(Fore.WHITE)\n print('-----------------------------------')\n forRunningProcesses.forward_process(process, df)\n print(Fore.GREEN)\n forRunningProcesses.more_processes()\n\n else:\n data1 = data[2]\n # print (data1)\n s1 = forRunningProcesses.loop_through(data1, df)\n data1 = s1[['Services', 'ProcessId', 'ParentProcessId', 'CommandLine']].to_string(index=False, header=False)\n data1 = list(data1.split())\n s1 = forRunningProcesses.loop_through(data1[2], df)\n # print(data1)\n f_ind1 = df.loc[df['ProcessId'] == data1[1]]\n ist.append(data1[1])\n if s1.empty or data1[2] == '4' or data1[2] in ist:\n print('\\n')\n print(Fore.YELLOW + 'Process traceability \\n')\n print(Fore.WHITE)\n print('process ' + data[0] + '(' + process + ')' + ' executed by ' + data1[0] + '(' + data1[\n 1] + ')' + ' root process is ' + ' ' + data1[2])\n print('\\n')\n print(Fore.YELLOW + 'Involved Commands if exist - read from top to bottom:\\n')\n print(Fore.WHITE)\n p = f_ind[['Services', 'CommandLine']]\n print(f_ind[['Services', 'CommandLine']].to_string(index=False, header=True))\n forRunningProcesses.process_ml(p)\n print(Fore.WHITE)\n print('-----------------------------------')\n print(f_ind1[['Services', 'CommandLine']].to_string(index=False, header=True))\n print('-----------------------------------')\n forRunningProcesses.forward_process(process, df)\n\n print(Fore.GREEN)\n forRunningProcesses.more_processes()\n\n else:\n data2 = data1[2]\n # print(data2)\n s2 = forRunningProcesses.loop_through(data2, df)\n data2 = s2[['Services', 'ProcessId', 'ParentProcessId', 'CommandLine']].to_string(index=False,\n header=False)\n data2 = list(data2.split())\n s2 = forRunningProcesses.loop_through(data2[2], df)\n # print(data2)\n\n f_ind2 = df.loc[df['ProcessId'] == data2[1]]\n\n ist.append(data2[1])\n if s2.empty or data2[2] == '4' or data2[2] in ist:\n print('\\n')\n print(Fore.YELLOW + 'Process traceability \\n')\n print(Fore.WHITE)\n print('process ' + data[0] + '(' + process + ')' ' executed by ' + '\\n' + ' ' + data1[0] + '(' +\n data1[1] + ')' + ' <- ' + data2[0] + '(' + data2[1] + ')'\n + ' root process is ' + ' ' + data2[2])\n\n print('\\n')\n print(Fore.YELLOW + 'Involved Commands if exist - read from top to bottom:\\n')\n print(Fore.WHITE)\n p = f_ind[['Services', 'CommandLine']]\n print(f_ind[['Services', 'CommandLine']].to_string(index=False, header=True))\n forRunningProcesses.process_ml(p)\n print(Fore.WHITE)\n print('-----------------------------------')\n print(f_ind1[['Services', 'CommandLine']].to_string(index=False, header=True))\n print('-----------------------------------')\n print(f_ind2[['Services', 'CommandLine']].to_string(index=False, header=True))\n forRunningProcesses.forward_process(process, df)\n\n print(Fore.GREEN)\n forRunningProcesses.more_processes()\n\n else:\n data3 = data2[2]\n # print(data3)\n s3 = forRunningProcesses.loop_through(data3, df)\n data3 = s3[['Services', 'ProcessId', 'ParentProcessId', 'CommandLine']].to_string(index=False,\n header=False)\n data3 = list(data3.split())\n s3 = forRunningProcesses.loop_through(data3[2], df)\n\n # print(data3)\n f_ind3 = df.loc[df['ProcessId'] == data3[1]]\n # print (Fore.YELLOW)\n # print (f_ind3)\n ist.append(data3[1])\n if s3.empty or data3[2] == '4' or data3[2] in ist:\n print('\\n')\n print(Fore.YELLOW + 'Process traceability \\n')\n print(Fore.WHITE)\n print('process ' + data[0] + '(' + process + ')' + ' executed by ' + '\\n' + ' ' + data1[\n 0] + '(' + data1[1] + ')'\n + ' <- ' + data2[0] + '(' + data2[1] + ')'\n + ' <- ' + data3[0] + '(' + data3[1] + ')'\n + ' root process is ' + ' ' + data3[2])\n print('\\n')\n print(Fore.YELLOW + 'Involved Commands if exist - read from top to bottom:\\n')\n print(Fore.WHITE)\n p = f_ind[['Services', 'CommandLine']]\n print(f_ind[['Services', 'CommandLine']].to_string(index=False, header=True))\n forRunningProcesses.process_ml(p)\n print(Fore.WHITE)\n print('-----------------------------------')\n print(f_ind1[['Services', 'CommandLine']].to_string(index=False, header=True))\n print('-----------------------------------')\n print(f_ind2[['Services', 'CommandLine']].to_string(index=False, header=True))\n print('-----------------------------------')\n print(f_ind3[['Services', 'CommandLine']].to_string(index=False, header=True))\n print('-----------------------------------')\n forRunningProcesses.forward_process(process, df)\n\n print(Fore.GREEN)\n forRunningProcesses.more_processes()\n\n else:\n data4 = data3[2]\n # print(data4)\n s4 = forRunningProcesses.loop_through(data4, df)\n data4 = s4[['Services', 'ProcessId', 'ParentProcessId', 'CommandLine']].to_string(index=False,\n header=False)\n data4 = list(data4.split())\n s4 = forRunningProcesses.loop_through(data4[2], df)\n f_ind4 = df.loc[df['ProcessId'] == data4[1]]\n ist.append(data4[1])\n # print(data4)\n if s4.empty or data4[2] == '4' or data4[2] in ist:\n print('\\n')\n print(Fore.YELLOW + 'Process traceability \\n')\n print(Fore.WHITE)\n print('process ' + data[0] + '(' + process + ')' + ' executed by ' + '\\n' + ' ' + data1[\n 0] + '(' + data1[1] + ')' + ' <- ' + data2[0]\n + '(' + data2[1] + ')' + ' <- ' + data3[0] + '(' + data3[1] + ')' + ' <- ' + data4[\n 0] + '(' + data4[1] + ')'\n + ' ' + ' root process is ' + ' ' + data4[2])\n print('\\n')\n print(Fore.YELLOW + 'Involved Commands if exist - read from top to bottom:\\n')\n print(Fore.WHITE)\n p = f_ind[['Services', 'CommandLine']]\n print(f_ind[['Services', 'CommandLine']].to_string(index=False, header=True))\n forRunningProcesses.process_ml(p)\n print(Fore.WHITE)\n print('-----------------------------------')\n print(f_ind1[['Services', 'CommandLine']].to_string(index=False, header=False))\n print('-----------------------------------')\n print(f_ind2[['Services', 'CommandLine']].to_string(index=False, header=False))\n print('-----------------------------------')\n print(f_ind3[['Services', 'CommandLine']].to_string(index=False, header=False))\n print('-----------------------------------')\n print(f_ind4[['Services', 'CommandLine']].to_string(index=False, header=False))\n forRunningProcesses.forward_process(process, df)\n\n print(Fore.GREEN)\n forRunningProcesses.more_processes()\n\n else:\n data5 = data4[2]\n # print(data5)\n s5 = forRunningProcesses.loop_through(data5, df)\n data5 = s5[['Services', 'ProcessId', 'ParentProcessId', 'CommandLine']].to_string(\n index=False,\n header=False)\n data5 = list(data5.split())\n s5 = forRunningProcesses.loop_through(data5[2], df)\n f_ind5 = df.loc[df['ProcessId'] == data5[1]]\n # print(data5)\n ist.append(data5[1])\n if s5.empty or data5[2] == '4' or data5[2] in ist:\n print('\\n')\n print(Fore.YELLOW + 'Process traceability \\n')\n print(Fore.WHITE)\n print('process ' + data[0] + '(' + process + ')' +\n ' executed by ' + '\\n' + ' ' + data1[0] + '(' + data1[1] + ')' + ' <- ' + data2[\n 0] +\n '(' + data2[1] + ')' + ' <- ' + data3[0] + '(' + data3[1] + ')' + ' <- ' + data4[\n 0] + '(' + data4[1] + ')' + ' <- ' +\n data5[0] + '(' + data5[1] + ')'\n + ' root process is ' + ' ' + data5[2])\n print('\\n')\n print(Fore.YELLOW + 'Involved Commands if exist - read from top to bottom:\\n')\n print(Fore.WHITE)\n p = f_ind[['Services', 'CommandLine']]\n print(f_ind[['Services', 'CommandLine']].to_string(index=False, header=True))\n forRunningProcesses.process_ml(p)\n print(Fore.WHITE)\n print('-----------------------------------')\n print(f_ind1[['Services', 'CommandLine']].to_string(index=False, header=False))\n print('-----------------------------------')\n print(f_ind2[['Services', 'CommandLine']].to_string(index=False, header=False))\n print('-----------------------------------')\n print(f_ind3[['Services', 'CommandLine']].to_string(index=False, header=False))\n print('-----------------------------------')\n print(f_ind4[['Services', 'CommandLine']].to_string(index=False, header=False))\n print('-----------------------------------')\n print(f_ind5[['Services', 'CommandLine']].to_string(index=False, header=False))\n forRunningProcesses.forward_process(process, df)\n\n print(Fore.GREEN)\n forRunningProcesses.more_processes()\n\n else:\n data6 = data5[2]\n # print(data6)\n s6 = forRunningProcesses.loop_through(data6, df)\n data6 = s6[['Services', 'ProcessId', 'ParentProcessId', 'CommandLine']].to_string(\n index=False, header=False)\n data6 = list(data6.split())\n s6 = forRunningProcesses.loop_through(data6[2], df)\n f_ind6 = df.loc[df['ProcessId'] == data6[1]]\n # print(data6)\n ist.append(data6[1])\n if s6.empty or data6[2] == '4' or data6[2] in ist:\n print('\\n')\n print(Fore.YELLOW + 'Process traceability \\n')\n print(Fore.WHITE)\n print('process ' + data[0] + '(' + process + ')' + ' executed by ' + '\\n' + ' ' +\n data1[0] + '(' + data1[1] + ')'\n + ' <- ' + data2[0] + '(' + data2[1] + ')' + ' <- ' +\n data3[0] + '(' + data3[1] + ')' ' <- ' + data4[0] + '(' + data4[\n 1] + ')' + ' <- ' +\n data5[0] + '(' + data5[1] + ')' + ' <- ' + data6[0] + '(' + data6[1] + ')'\n + ' root process is ' + ' ' + data6[2])\n\n print('\\n')\n print(Fore.YELLOW + 'Involved Commands if exist - read from top to bottom:\\n')\n print(Fore.WHITE)\n p = f_ind[['Services', 'CommandLine']]\n print(f_ind[['Services', 'CommandLine']].to_string(index=False, header=True))\n forRunningProcesses.process_ml(p)\n print(Fore.WHITE)\n print('-----------------------------------')\n print(f_ind1[['Services', 'CommandLine']].to_string(index=False, header=False))\n print('-----------------------------------')\n print(f_ind2[['Services', 'CommandLine']].to_string(index=False, header=False))\n print('-----------------------------------')\n print(f_ind3[['Services', 'CommandLine']].to_string(index=False, header=False))\n print('-----------------------------------')\n print(f_ind4[['Services', 'CommandLine']].to_string(index=False, header=False))\n print('-----------------------------------')\n print(f_ind5[['Services', 'CommandLine']].to_string(index=False, header=False))\n print('-----------------------------------')\n print(f_ind6[['Services', 'CommandLine']].to_string(index=False, header=False))\n forRunningProcesses.forward_process(process, df)\n\n print(Fore.GREEN)\n forRunningProcesses.more_processes()\n\n else:\n data7 = data6[2]\n # print(data7)\n s7 = forRunningProcesses.loop_through(data7, df)\n data7 = s7[['Services', 'ProcessId', 'ParentProcessId', 'CommandLine']].to_string(\n index=False, header=False)\n data7 = list(data7.split())\n s7 = forRunningProcesses.loop_through(data7[2], df)\n f_ind7 = df.loc[df['ProcessId'] == data7[1]]\n # print(data7)\n ist.append(data7[1])\n if s7.empty or data7[2] == '4' or data7[2] in ist:\n print('\\n')\n print(Fore.YELLOW + 'Process traceability \\n')\n print(Fore.WHITE)\n print(\n 'process ' + data[0] + '(' + process + ')' + ' executed by ' + '\\n' + ' ' +\n data1[0] + '(' + data1[\n 1] + ')' + ' <- ' + data2[0] + '(' + data2[1] + ')' + ' <- ' +\n data3[0] + '(' + data3[1] + ')' + ' <- ' + data4[0] + '(' + data4[\n 1] + ')' + ' <- ' +\n data5[0] + '(' + data5[1] + ')' + ' <- ' + data6[0] + '(' + data6[\n 1] + ')' + ' <- ' + data7[0] + '(' + data7[1] + ')'\n + ' root process is ' + ' ' +\n data7[2])\n print('\\n')\n print(Fore.YELLOW + 'Involved Commands if exist - read from top to bottom:\\n')\n print(Fore.WHITE)\n p = f_ind[['Services', 'CommandLine']]\n print(f_ind[['Services', 'CommandLine']].to_string(index=False, header=True))\n forRunningProcesses.process_ml(p)\n print(Fore.WHITE)\n print('-----------------------------------')\n print(f_ind1[['Services', 'CommandLine']].to_string(index=False, header=False))\n print('-----------------------------------')\n print(f_ind2[['Services', 'CommandLine']].to_string(index=False, header=False))\n print('-----------------------------------')\n print(f_ind3[['Services', 'CommandLine']].to_string(index=False, header=False))\n print('-----------------------------------')\n print(f_ind4[['Services', 'CommandLine']].to_string(index=False, header=False))\n print('-----------------------------------')\n print(f_ind5[['Services', 'CommandLine']].to_string(index=False, header=False))\n print('-----------------------------------')\n print(f_ind6[['Services', 'CommandLine']].to_string(index=False, header=False))\n print('-----------------------------------')\n print(f_ind7[['Services', 'CommandLine']].to_string(index=False, header=False))\n forRunningProcesses.forward_process(process, df)\n\n print(Fore.GREEN)\n forRunningProcesses.more_processes()\n\n else:\n data8 = data7[2]\n # print(data8)\n s8 = forRunningProcesses.loop_through(data8, df)\n data8 = s8[\n ['Services', 'ProcessId', 'ParentProcessId', 'CommandLine']].to_string(\n index=False, header=False)\n data8 = list(data8.split())\n s8 = forRunningProcesses.loop_through(data8[2], df)\n f_ind8 = df.loc[df['ProcessId'] == data8[1]]\n # print(data8)\n ist.append(data8[1])\n if s8.empty or data8[2] == '4' or data8[2] in ist:\n print('\\n')\n print(Fore.YELLOW + 'Process traceability \\n')\n print(Fore.WHITE)\n print('process ' + data[\n 0] + '(' + process + ')' + '/' + ' executed by ' + '\\n' + ' ' +\n data1[0] + '(' + data1[1] + ')' + ' <- ' + data2[0] + '(' + data2[\n 1] + ')' + ' <- ' +\n data3[0] + '(' + data3[1] + ')' + ' <- ' + data4[0] + '(' + data4[\n 1] + ')' + ' <- ' +\n data5[0] + '(' + data5[1] + ')' + ' <- ' + data6[0] + '(' + data6[\n 1] + ')' + ' <- ' + data7[0] + '(' +\n data7[1] + ')' + ' <- ' + data8[\n 0] + '(' + data8[1] + ')' + ' root process is ' +\n data8[2])\n\n print('\\n')\n print(\n Fore.YELLOW + 'Involved Commands if exist - read from top to bottom:\\n')\n print(Fore.WHITE)\n p = f_ind[['Services', 'CommandLine']]\n print(\n f_ind[['Services', 'CommandLine']].to_string(index=False, header=True))\n forRunningProcesses.process_ml(p)\n print(Fore.WHITE)\n print('-----------------------------------')\n print(f_ind1[['Services', 'CommandLine']].to_string(index=False,\n header=False))\n print('-----------------------------------')\n print(f_ind2[['Services', 'CommandLine']].to_string(index=False,\n header=False))\n print('-----------------------------------')\n print(f_ind3[['Services', 'CommandLine']].to_string(index=False,\n header=False))\n print('-----------------------------------')\n print(f_ind4[['Services', 'CommandLine']].to_string(index=False,\n header=False))\n print('-----------------------------------')\n print(f_ind5[['Services', 'CommandLine']].to_string(index=False,\n header=False))\n print('-----------------------------------')\n print(f_ind6[['Services', 'CommandLine']].to_string(index=False,\n header=False))\n print('-----------------------------------')\n print(f_ind7[['Services', 'CommandLine']].to_string(index=False,\n header=False))\n print('-----------------------------------')\n print(f_ind8[['Services', 'CommandLine']].to_string(index=False,\n header=False))\n forRunningProcesses.forward_process(process, df)\n\n print('\\n')\n print(Fore.GREEN)\n forRunningProcesses.more_processes()\n\n else:\n data9 = data8[2]\n # print(data9)\n s9 = forRunningProcesses.loop_through(data9, df)\n data9 = s9[\n ['Services', 'ProcessId', 'ParentProcessId', 'CommandLine']].to_string(\n index=False, header=False)\n data9 = list(data9.split())\n s9 = forRunningProcesses.loop_through(data9[2], df)\n f_ind9 = df.loc[df['ProcessId'] == data9[1]]\n # print(data9)\n ist.append(data9[1])\n if s9.empty or data9[2] == '4' or data9[2] in ist:\n print('\\n')\n print(Fore.YELLOW + 'Process traceability \\n')\n print(Fore.WHITE)\n print('process ' + data[\n 0] + '(' + process + ')' + ' executed by ' + '\\n' + ' ' +\n data1[0] + '(' + data1[1] + ')' + ' <- ' + data2[0] + '(' + data2[\n 1] + ')' + ' <- ' +\n data3[0] + '(' + data3[1] + ')' + ' <- ' + data4[0] + '(' + data4[\n 1] + ')' + ' <- ' +\n data5[0] + '(' + data5[1] + ')' + ' <- ' + data6[0] + '(' + data6[\n 1] + ')' + ' <- ' +\n data7[0] + '(' + data7[1] + ')' + ' <- ' + data8[0] + '(' + data8[\n 1] + ')' + ' <- ' +\n data9[0] + '(' + data9[1] + ')' + ' root process is ' + ' ' +\n data9[2])\n print('\\n')\n print(\n Fore.YELLOW + 'Involved Commands if exist - read from top to '\n 'bottom:\\n')\n print(Fore.WHITE)\n p = f_ind[['Services', 'CommandLine']]\n print(f_ind[['Services', 'CommandLine']].to_string(index=False,\n header=True))\n forRunningProcesses.process_ml(p)\n print(Fore.WHITE)\n print('-----------------------------------')\n print(f_ind1[['Services', 'CommandLine']].to_string(index=False,\n header=False))\n print('-----------------------------------')\n print(f_ind2[['Services', 'CommandLine']].to_string(index=False,\n header=False))\n print('-----------------------------------')\n print(f_ind3[['Services', 'CommandLine']].to_string(index=False,\n header=False))\n print('-----------------------------------')\n print(f_ind4[['Services', 'CommandLine']].to_string(index=False,\n header=False))\n print('-----------------------------------')\n print(f_ind5[['Services', 'CommandLine']].to_string(index=False,\n header=False))\n print('-----------------------------------')\n print(f_ind6[['Services', 'CommandLine']].to_string(index=False,\n header=False))\n print('-----------------------------------')\n print(f_ind7[['Services', 'CommandLine']].to_string(index=False,\n header=False))\n print('-----------------------------------')\n print(f_ind8[['Services', 'CommandLine']].to_string(index=False,\n header=False))\n print('-----------------------------------')\n print(f_ind9[['Services', 'CommandLine']].to_string(index=False,\n header=False))\n forRunningProcesses.forward_process(process, df)\n\n print('\\n')\n print(Fore.GREEN)\n forRunningProcesses.more_processes()\n\n else:\n data10 = data9[2]\n # print(data10)\n s10 = forRunningProcesses.loop_through(data10, df)\n data10 = s10[['Services', 'ProcessId', 'ParentProcessId',\n 'CommandLine']].to_string(index=False, header=False)\n data10 = list(data10.split())\n s10 = forRunningProcesses.loop_through(data10[2], df)\n f_ind10 = df.loc[df['ProcessId'] == data10[1]]\n # print(data10)\n ist.append(data10[1])\n if s10.empty or data10[2] == '4' or data10[2] in ist:\n print('\\n')\n print(Fore.YELLOW + 'Process traceability \\n')\n print(Fore.WHITE)\n print('process ' + data[\n 0] + '(' + process + ')' + ' exEcuted by ' + '\\n' + ' ' +\n data1[0] + '(' + data1[1] + ')' + ' <- ' + data2[0] + '(' +\n data2[1] + ')' + ' <- ' +\n data3[0] + '(' + data3[1] + ')' + ' <- ' + data4[0] + '(' +\n data4[1] + ')' + ' <- ' +\n data5[0] + '(' + data5[1] + ')' + ' <- ' + data6[0] + '(' +\n data6[1] + ')' + ' <- ' + data7[0] + '(' +\n data7[1] + ')' ' <- ' + data8[0] + '(' + data8[\n 1] + ')' + ' <- ' + data9[0] + '(' + data9[1] + ')'\n + ' <- ' + data10[0] + '(' + data10[1]\n + ')' + ' root process is ' + ' ' + data10[2])\n print('\\n')\n print(\n Fore.YELLOW + 'Involved Commands if exist - read from top to '\n 'bottom:\\n')\n print(Fore.WHITE)\n p = f_ind[['Services', 'CommandLine']]\n print(f_ind[['Services', 'CommandLine']].to_string(index=False,\n header=True))\n forRunningProcesses.process_ml(p)\n print(Fore.WHITE)\n print('-----------------------------------')\n print(f_ind1[['Services', 'CommandLine']].to_string(index=False,\n header=False))\n print('-----------------------------------')\n print(f_ind2[['Services', 'CommandLine']].to_string(index=False,\n header=False))\n print('-----------------------------------')\n print(f_ind3[['Services', 'CommandLine']].to_string(index=False,\n header=False))\n print('-----------------------------------')\n print(f_ind4[['Services', 'CommandLine']].to_string(index=False,\n header=False))\n print('-----------------------------------')\n print(f_ind5[['Services', 'CommandLine']].to_string(index=False,\n header=False))\n print('-----------------------------------')\n print(f_ind6[['Services', 'CommandLine']].to_string(index=False,\n header=False))\n print('-----------------------------------')\n print(f_ind7[['Services', 'CommandLine']].to_string(index=False,\n header=False))\n print('-----------------------------------')\n print(f_ind8[['Services', 'CommandLine']].to_string(index=False,\n header=False))\n print('-----------------------------------')\n print(f_ind9[['Services', 'CommandLine']].to_string(index=False,\n header=False))\n print('-----------------------------------')\n print(f_ind10[['Services', 'CommandLine']].to_string(index=False,\n header=False))\n print('\\n')\n forRunningProcesses.forward_process(process, df)\n\n print(Fore.GREEN)\n forRunningProcesses.more_processes()\n\n else:\n data11 = data10[2]\n # print(data11)\n s11 = forRunningProcesses.loop_through(data11, df)\n data11 = s11[['Services', 'ProcessId', 'ParentProcessId',\n 'CommandLine']].to_string(index=False, header=False)\n data11 = list(data11.split())\n s11 = forRunningProcesses.loop_through(data11[2], df)\n f_ind11 = df.loc[df['ProcessId'] == data11[1]]\n # print(data11)\n ist.append(data11[1])\n if s11.empty or data11[2] == '4' or data11[2] in ist:\n print(Fore.YELLOW + 'Process traceability \\n')\n print(Fore.WHITE)\n print('process ' + data[\n 0] + '(' + process + ')' + ' executed by ' + '\\n' + ' ' +\n data1[0] + '(' + data1[1] + ')' + ' <- ' + data2[\n 0] + '(' + data2[1] + ')' + ' <- ' +\n data3[0] + '(' + data3[1] + ')' + ' <- ' + data4[\n 0] + '(' + data4[1] + ')' + ' <- ' +\n data5[0] + '(' + data5[1] + ')' + ' <- ' + data6[\n 0] + '(' + data6[1] + ')' + ' <- ' + data7[0] + '(' +\n data7[1] + ')' ' <- ' + data8[0] + '(' + data8[\n 1] + ')' + ' <- ' + data9[0] + '(' + data9[1] + ')'\n + ' <- ' + data10[0] + '(' + data10[1]\n + ')' + ' <- ' + data11[0] + '(' + data11[1]\n + ' root process is ' + ' ' + data11[2])\n print('\\n')\n print(\n Fore.YELLOW + 'Involved Commands if exist - read from top '\n 'to bottom:\\n')\n print(Fore.WHITE)\n p = f_ind[['Services', 'CommandLine']]\n print(f_ind[['Services', 'CommandLine']].to_string(index=False,\n header=True))\n forRunningProcesses.process_ml(p)\n print(Fore.WHITE)\n print('-----------------------------------')\n print(f_ind1[['Services', 'CommandLine']].to_string(index=False,\n header=False))\n print('-----------------------------------')\n print(f_ind2[['Services', 'CommandLine']].to_string(index=False,\n header=False))\n print('-----------------------------------')\n print(f_ind3[['Services', 'CommandLine']].to_string(index=False,\n header=False))\n print('-----------------------------------')\n print(f_ind4[['Services', 'CommandLine']].to_string(index=False,\n header=False))\n print('-----------------------------------')\n print(f_ind5[['Services', 'CommandLine']].to_string(index=False,\n header=False))\n print('-----------------------------------')\n print(f_ind6[['Services', 'CommandLine']].to_string(index=False,\n header=False))\n print('-----------------------------------')\n print(f_ind7[['Services', 'CommandLine']].to_string(index=False,\n header=False))\n print('-----------------------------------')\n print(f_ind8[['Services', 'CommandLine']].to_string(index=False,\n header=False)\n )\n print('-----------------------------------')\n print(f_ind9[['Services', 'CommandLine']].to_string(index=False,\n header=False)\n )\n print('-----------------------------------')\n print(\n f_ind10[['Services', 'CommandLine']].to_string(index=False,\n header=False)\n )\n print('-----------------------------------')\n print(\n f_ind11[['Services', 'CommandLine']].to_string(index=False,\n header=False)\n )\n print('\\n')\n forRunningProcesses.forward_process(process, df)\n print(Fore.GREEN)\n forRunningProcesses.more_processes()\n\n else:\n print(Fore.YELLOW)\n print('\\n')\n print('\\nTraceability: Maximum of 11 processes')\n live_process()\n else:\n print(Fore.YELLOW + 'Wrong process ID, trying again')\n live_process()\n\n return run.user_input()\n" ]
[ [ "pandas.DataFrame", "pandas.read_csv" ] ]
vgainullin/iclr19-graph2graph
[ "effafc08d90466977aed0c77712a39d142f0c3e6" ]
[ "fast_jtnn/mpn.py" ]
[ "import torch\nimport torch.nn as nn\nimport rdkit.Chem as Chem\nimport torch.nn.functional as F\nfrom fast_jtnn.nnutils import *\nfrom fast_jtnn.chemutils import get_mol\n\nELEM_LIST = ['C', 'N', 'O', 'S', 'F', 'Si', 'P', 'Cl', 'Br', 'Mg', 'Na', 'Ca', 'Fe', 'Al', 'I', 'B', 'K', 'Se', 'Zn', 'H', 'Cu', 'Mn', 'unknown']\n\nATOM_FDIM = len(ELEM_LIST) + 6 + 5 + 4 + 1\nBOND_FDIM = 5 + 6\nMAX_NB = 6\n\ndef onek_encoding_unk(x, allowable_set):\n if x not in allowable_set:\n x = allowable_set[-1]\n return list(map(lambda s: x == s, allowable_set))\n\ndef atom_features(atom):\n return torch.Tensor(onek_encoding_unk(atom.GetSymbol(), ELEM_LIST) \n + onek_encoding_unk(atom.GetDegree(), [0,1,2,3,4,5]) \n + onek_encoding_unk(atom.GetFormalCharge(), [-1,-2,1,2,0])\n + onek_encoding_unk(int(atom.GetChiralTag()), [0,1,2,3])\n + [atom.GetIsAromatic()])\n\ndef bond_features(bond):\n bt = bond.GetBondType()\n stereo = int(bond.GetStereo())\n fbond = [bt == Chem.rdchem.BondType.SINGLE, bt == Chem.rdchem.BondType.DOUBLE, bt == Chem.rdchem.BondType.TRIPLE, bt == Chem.rdchem.BondType.AROMATIC, bond.IsInRing()]\n fstereo = onek_encoding_unk(stereo, [0,1,2,3,4,5])\n return torch.Tensor(fbond + fstereo)\n\nclass MPN(nn.Module):\n\n def __init__(self, hidden_size, depth):\n super(MPN, self).__init__()\n self.hidden_size = hidden_size\n self.depth = depth\n\n self.W_i = nn.Linear(ATOM_FDIM + BOND_FDIM, hidden_size, bias=False)\n self.W_h = nn.Linear(hidden_size, hidden_size, bias=False)\n self.W_o = nn.Linear(ATOM_FDIM + hidden_size, hidden_size)\n\n def forward(self, fatoms, fbonds, agraph, bgraph, scope):\n fatoms = create_var(fatoms)\n fbonds = create_var(fbonds)\n agraph = create_var(agraph)\n bgraph = create_var(bgraph)\n\n binput = self.W_i(fbonds)\n message = F.relu(binput)\n\n for i in range(self.depth - 1):\n nei_message = index_select_ND(message, 0, bgraph)\n nei_message = nei_message.sum(dim=1)\n nei_message = self.W_h(nei_message)\n message = F.relu(binput + nei_message)\n\n nei_message = index_select_ND(message, 0, agraph)\n nei_message = nei_message.sum(dim=1)\n ainput = torch.cat([fatoms, nei_message], dim=1)\n atom_hiddens = F.relu(self.W_o(ainput))\n\n max_len = max([x for _,x in scope])\n batch_vecs = []\n for st,le in scope:\n cur_vecs = atom_hiddens[st : st + le]\n cur_vecs = F.pad( cur_vecs, (0,0,0,max_len-le) )\n batch_vecs.append( cur_vecs )\n\n mol_vecs = torch.stack(batch_vecs, dim=0)\n return mol_vecs \n\n @staticmethod\n def tensorize(mol_batch):\n padding = torch.zeros(ATOM_FDIM + BOND_FDIM)\n fatoms,fbonds = [],[padding] #Ensure bond is 1-indexed\n in_bonds,all_bonds = [],[(-1,-1)] #Ensure bond is 1-indexed\n scope = []\n total_atoms = 0\n\n for smiles in mol_batch:\n mol = get_mol(smiles)\n #mol = Chem.MolFromSmiles(smiles)\n n_atoms = mol.GetNumAtoms()\n for atom in mol.GetAtoms():\n fatoms.append( atom_features(atom) )\n in_bonds.append([])\n\n for bond in mol.GetBonds():\n a1 = bond.GetBeginAtom()\n a2 = bond.GetEndAtom()\n x = a1.GetIdx() + total_atoms\n y = a2.GetIdx() + total_atoms\n\n b = len(all_bonds) \n all_bonds.append((x,y))\n fbonds.append( torch.cat([fatoms[x], bond_features(bond)], 0) )\n in_bonds[y].append(b)\n\n b = len(all_bonds)\n all_bonds.append((y,x))\n fbonds.append( torch.cat([fatoms[y], bond_features(bond)], 0) )\n in_bonds[x].append(b)\n \n scope.append((total_atoms,n_atoms))\n total_atoms += n_atoms\n\n total_bonds = len(all_bonds)\n fatoms = torch.stack(fatoms, 0)\n fbonds = torch.stack(fbonds, 0)\n agraph = torch.zeros(total_atoms,MAX_NB).long()\n bgraph = torch.zeros(total_bonds,MAX_NB).long()\n\n for a in range(total_atoms):\n for i,b in enumerate(in_bonds[a]):\n agraph[a,i] = b\n\n for b1 in range(1, total_bonds):\n x,y = all_bonds[b1]\n for i,b2 in enumerate(in_bonds[x]):\n if all_bonds[b2][0] != y:\n bgraph[b1,i] = b2\n\n return (fatoms, fbonds, agraph, bgraph, scope)\n\n" ]
[ [ "torch.nn.Linear", "torch.zeros", "torch.cat", "torch.stack", "torch.nn.functional.relu", "torch.nn.functional.pad", "torch.Tensor" ] ]
dganguly1120/tf-pose-estimation
[ "622d3c96f2cb9951dffe857ddc67978299d5ced6" ]
[ "tf_pose/network_cmu.py" ]
[ "from __future__ import absolute_import\n\nfrom tf_pose import network_base\nimport tensorflow as tf\n\n\nclass CmuNetwork(network_base.BaseNetwork):\n def setup(self):\n (self.feed('image')\n .normalize_vgg(name='preprocess')\n .conv(3, 3, 64, 1, 1, name='conv1_1')\n .conv(3, 3, 64, 1, 1, name='conv1_2')\n .max_pool(2, 2, 2, 2, name='pool1_stage1', padding='VALID')\n .conv(3, 3, 128, 1, 1, name='conv2_1')\n .conv(3, 3, 128, 1, 1, name='conv2_2')\n .max_pool(2, 2, 2, 2, name='pool2_stage1', padding='VALID')\n .conv(3, 3, 256, 1, 1, name='conv3_1')\n .conv(3, 3, 256, 1, 1, name='conv3_2')\n .conv(3, 3, 256, 1, 1, name='conv3_3')\n .conv(3, 3, 256, 1, 1, name='conv3_4')\n .max_pool(2, 2, 2, 2, name='pool3_stage1', padding='VALID')\n .conv(3, 3, 512, 1, 1, name='conv4_1')\n .conv(3, 3, 512, 1, 1, name='conv4_2')\n .conv(3, 3, 256, 1, 1, name='conv4_3_CPM')\n .conv(3, 3, 128, 1, 1, name='conv4_4_CPM') # *****\n\n .conv(3, 3, 128, 1, 1, name='conv5_1_CPM_L1')\n .conv(3, 3, 128, 1, 1, name='conv5_2_CPM_L1')\n .conv(3, 3, 128, 1, 1, name='conv5_3_CPM_L1')\n .conv(1, 1, 512, 1, 1, name='conv5_4_CPM_L1')\n .conv(1, 1, 38, 1, 1, relu=False, name='conv5_5_CPM_L1'))\n\n (self.feed('conv4_4_CPM')\n .conv(3, 3, 128, 1, 1, name='conv5_1_CPM_L2')\n .conv(3, 3, 128, 1, 1, name='conv5_2_CPM_L2')\n .conv(3, 3, 128, 1, 1, name='conv5_3_CPM_L2')\n .conv(1, 1, 512, 1, 1, name='conv5_4_CPM_L2')\n .conv(1, 1, 19, 1, 1, relu=False, name='conv5_5_CPM_L2'))\n\n (self.feed('conv5_5_CPM_L1',\n 'conv5_5_CPM_L2',\n 'conv4_4_CPM')\n .concat(3, name='concat_stage2')\n .conv(7, 7, 128, 1, 1, name='Mconv1_stage2_L1')\n .conv(7, 7, 128, 1, 1, name='Mconv2_stage2_L1')\n .conv(7, 7, 128, 1, 1, name='Mconv3_stage2_L1')\n .conv(7, 7, 128, 1, 1, name='Mconv4_stage2_L1')\n .conv(7, 7, 128, 1, 1, name='Mconv5_stage2_L1')\n .conv(1, 1, 128, 1, 1, name='Mconv6_stage2_L1')\n .conv(1, 1, 38, 1, 1, relu=False, name='Mconv7_stage2_L1'))\n\n (self.feed('concat_stage2')\n .conv(7, 7, 128, 1, 1, name='Mconv1_stage2_L2')\n .conv(7, 7, 128, 1, 1, name='Mconv2_stage2_L2')\n .conv(7, 7, 128, 1, 1, name='Mconv3_stage2_L2')\n .conv(7, 7, 128, 1, 1, name='Mconv4_stage2_L2')\n .conv(7, 7, 128, 1, 1, name='Mconv5_stage2_L2')\n .conv(1, 1, 128, 1, 1, name='Mconv6_stage2_L2')\n .conv(1, 1, 19, 1, 1, relu=False, name='Mconv7_stage2_L2'))\n\n (self.feed('Mconv7_stage2_L1',\n 'Mconv7_stage2_L2',\n 'conv4_4_CPM')\n .concat(3, name='concat_stage3')\n .conv(7, 7, 128, 1, 1, name='Mconv1_stage3_L1')\n .conv(7, 7, 128, 1, 1, name='Mconv2_stage3_L1')\n .conv(7, 7, 128, 1, 1, name='Mconv3_stage3_L1')\n .conv(7, 7, 128, 1, 1, name='Mconv4_stage3_L1')\n .conv(7, 7, 128, 1, 1, name='Mconv5_stage3_L1')\n .conv(1, 1, 128, 1, 1, name='Mconv6_stage3_L1')\n .conv(1, 1, 38, 1, 1, relu=False, name='Mconv7_stage3_L1'))\n\n (self.feed('concat_stage3')\n .conv(7, 7, 128, 1, 1, name='Mconv1_stage3_L2')\n .conv(7, 7, 128, 1, 1, name='Mconv2_stage3_L2')\n .conv(7, 7, 128, 1, 1, name='Mconv3_stage3_L2')\n .conv(7, 7, 128, 1, 1, name='Mconv4_stage3_L2')\n .conv(7, 7, 128, 1, 1, name='Mconv5_stage3_L2')\n .conv(1, 1, 128, 1, 1, name='Mconv6_stage3_L2')\n .conv(1, 1, 19, 1, 1, relu=False, name='Mconv7_stage3_L2'))\n\n (self.feed('Mconv7_stage3_L1',\n 'Mconv7_stage3_L2',\n 'conv4_4_CPM')\n .concat(3, name='concat_stage4')\n .conv(7, 7, 128, 1, 1, name='Mconv1_stage4_L1')\n .conv(7, 7, 128, 1, 1, name='Mconv2_stage4_L1')\n .conv(7, 7, 128, 1, 1, name='Mconv3_stage4_L1')\n .conv(7, 7, 128, 1, 1, name='Mconv4_stage4_L1')\n .conv(7, 7, 128, 1, 1, name='Mconv5_stage4_L1')\n .conv(1, 1, 128, 1, 1, name='Mconv6_stage4_L1')\n .conv(1, 1, 38, 1, 1, relu=False, name='Mconv7_stage4_L1'))\n\n (self.feed('concat_stage4')\n .conv(7, 7, 128, 1, 1, name='Mconv1_stage4_L2')\n .conv(7, 7, 128, 1, 1, name='Mconv2_stage4_L2')\n .conv(7, 7, 128, 1, 1, name='Mconv3_stage4_L2')\n .conv(7, 7, 128, 1, 1, name='Mconv4_stage4_L2')\n .conv(7, 7, 128, 1, 1, name='Mconv5_stage4_L2')\n .conv(1, 1, 128, 1, 1, name='Mconv6_stage4_L2')\n .conv(1, 1, 19, 1, 1, relu=False, name='Mconv7_stage4_L2'))\n\n (self.feed('Mconv7_stage4_L1',\n 'Mconv7_stage4_L2',\n 'conv4_4_CPM')\n .concat(3, name='concat_stage5')\n .conv(7, 7, 128, 1, 1, name='Mconv1_stage5_L1')\n .conv(7, 7, 128, 1, 1, name='Mconv2_stage5_L1')\n .conv(7, 7, 128, 1, 1, name='Mconv3_stage5_L1')\n .conv(7, 7, 128, 1, 1, name='Mconv4_stage5_L1')\n .conv(7, 7, 128, 1, 1, name='Mconv5_stage5_L1')\n .conv(1, 1, 128, 1, 1, name='Mconv6_stage5_L1')\n .conv(1, 1, 38, 1, 1, relu=False, name='Mconv7_stage5_L1'))\n\n (self.feed('concat_stage5')\n .conv(7, 7, 128, 1, 1, name='Mconv1_stage5_L2')\n .conv(7, 7, 128, 1, 1, name='Mconv2_stage5_L2')\n .conv(7, 7, 128, 1, 1, name='Mconv3_stage5_L2')\n .conv(7, 7, 128, 1, 1, name='Mconv4_stage5_L2')\n .conv(7, 7, 128, 1, 1, name='Mconv5_stage5_L2')\n .conv(1, 1, 128, 1, 1, name='Mconv6_stage5_L2')\n .conv(1, 1, 19, 1, 1, relu=False, name='Mconv7_stage5_L2'))\n\n (self.feed('Mconv7_stage5_L1',\n 'Mconv7_stage5_L2',\n 'conv4_4_CPM')\n .concat(3, name='concat_stage6')\n .conv(7, 7, 128, 1, 1, name='Mconv1_stage6_L1')\n .conv(7, 7, 128, 1, 1, name='Mconv2_stage6_L1')\n .conv(7, 7, 128, 1, 1, name='Mconv3_stage6_L1')\n .conv(7, 7, 128, 1, 1, name='Mconv4_stage6_L1')\n .conv(7, 7, 128, 1, 1, name='Mconv5_stage6_L1')\n .conv(1, 1, 128, 1, 1, name='Mconv6_stage6_L1')\n .conv(1, 1, 38, 1, 1, relu=False, name='Mconv7_stage6_L1'))\n\n (self.feed('concat_stage6')\n .conv(7, 7, 128, 1, 1, name='Mconv1_stage6_L2')\n .conv(7, 7, 128, 1, 1, name='Mconv2_stage6_L2')\n .conv(7, 7, 128, 1, 1, name='Mconv3_stage6_L2')\n .conv(7, 7, 128, 1, 1, name='Mconv4_stage6_L2')\n .conv(7, 7, 128, 1, 1, name='Mconv5_stage6_L2')\n .conv(1, 1, 128, 1, 1, name='Mconv6_stage6_L2')\n .conv(1, 1, 19, 1, 1, relu=False, name='Mconv7_stage6_L2'))\n\n with tf.compat.v1.variable_scope('Openpose'):\n (self.feed('Mconv7_stage6_L2',\n 'Mconv7_stage6_L1')\n .concat(3, name='concat_stage7'))\n\n def loss_l1_l2(self):\n l1s = []\n l2s = []\n for layer_name in self.layers.keys():\n if 'Mconv7' in layer_name and '_L1' in layer_name:\n l1s.append(self.layers[layer_name])\n if 'Mconv7' in layer_name and '_L2' in layer_name:\n l2s.append(self.layers[layer_name])\n\n return l1s, l2s\n\n def loss_last(self):\n return self.get_output('Mconv7_stage6_L1'), self.get_output('Mconv7_stage6_L2')\n\n def restorable_variables(self):\n return None\n" ]
[ [ "tensorflow.compat.v1.variable_scope" ] ]
pzjzeason/BrainCancer
[ "682a5635b4c3106a6d6df20cbff917e423e0c269" ]
[ "predict_associated_tumors/score_test.py" ]
[ "import json\nfrom openpyxl import load_workbook\nfrom pandas import DataFrame\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n\ndata = {}\nwith open(\"/Users/燚/study/大三下/信息系统开发与设计/系统开发/score/score_with_associatedTumours2.json\", \"r\", encoding='utf-8') as json_file:\n for each in json_file.readlines():\n values = {}\n line = json.loads(each)\n\n for value in line:\n if value != 'id':\n values[value]=line[value]\n\n data[line['id']] = values\n\n# 训练集\nwb = load_workbook('/Users/燚/study/大三下/信息系统开发与设计/系统开发/training_set.xlsx')\nsheet = wb.active\n\n# 训练集id保存在列表training_set\ntraining_set = []\nfor row in range(2, sheet.max_row+1):\n id_cell = sheet.cell(row=row, column=1) # 读取训练集中肿瘤id\n id_text = id_cell.value\n training_set.append(int(id_text))\n\n# 创建数据结构 DataFrame矩阵score_dataFrame\nscore_dataFrame = DataFrame(columns=training_set, index=training_set)\nfor id in data:\n if int(id) in training_set:\n for each in data[id]: # 确保两两计算的肿瘤均属于训练集\n if int(each) in training_set:\n score_dataFrame.loc[int(id),int(each)]=[]\n score_dataFrame.loc[int(id),int(each)].append(data[id][each]['brainStructure_score'])\n score_dataFrame.loc[int(id),int(each)].append(data[id][each]['symptoms_score'])\n score_dataFrame.loc[int(id), int(each)].append(data[id][each]['image_score'])\n score_dataFrame.loc[int(id), int(each)].append(data[id][each]['isAssociated'])\n\n\"\"\"\nax = plt.subplot(111, projection='3d') # 创建一个三维的绘图工程\n\nx_data0 = []\nx_data1 = []\ny_data0 = []\ny_data1 = []\nz_data0 = []\nz_data1 = []\n\nfor row in training_set:\n for col in training_set:\n if col > row:\n if score_dataFrame.loc[row,col][3] == 1:\n x_data1.append(score_dataFrame.loc[row,col][0])\n y_data1.append(score_dataFrame.loc[row,col][1])\n z_data1.append(score_dataFrame.loc[row,col][2])\n else:\n x_data0.append(score_dataFrame.loc[row,col][0])\n y_data0.append(score_dataFrame.loc[row,col][1])\n z_data0.append(score_dataFrame.loc[row,col][2])\n\nax.scatter(x_data0, y_data0, z_data0, c='y') # 绘制数据点\nax.scatter(x_data1, y_data1, z_data1, c='r')\n\nax.set_zlabel('Z') # 坐标轴\nax.set_ylabel('Y')\nax.set_xlabel('X')\nplt.show()\n\"\"\"\n\n# 创建权重训练字典\nscore_dic = {}\nfor x in range(0,101): # x:weight for brainStructure_score,保存为字典一级key\n score_dic[x] = {}\n for y in range(0,101-x): # x:weight for symptoms_score,保存为字典二级key\n score_dic[x][y] = {}\n z = 100 - x - y # x:weight for image_score,保存为字典三级key\n\n score = 0\n score_all = 0\n score_isAssociated = 0\n score_percent = 0\n\n # 根据训练集索引遍矩阵右上角历两两记录(不包括自身)\n for row in training_set:\n for col in training_set:\n if col > row:\n score = x * score_dataFrame.loc[row, col][0] \\\n + y * score_dataFrame.loc[row, col][1] \\\n + z * score_dataFrame.loc[row, col][2] # 单次得分记录\n score_all += score # 加入总得分记录\n if score_dataFrame.loc[row, col][3] == 1:\n score_isAssociated += score # 为相似肿瘤,加入相似肿瘤总得分记录\n if score_all != 0:\n score_percent = score_isAssociated / score_all\n score_dic[x][y][z] = score_percent # 字典保存相似肿瘤得分占比记录\n\nscore_max = {'x': 0, 'y': 0, 'z': 0, 'score_max': 0}\nfor x in score_dic:\n for y in score_dic[x]:\n for z in score_dic[x][y]:\n if score_dic[x][y][z] > score_max['score_max']:\n score_max['x'] = x/100\n score_max['y'] = y/100\n score_max['z'] = z/100\n score_max['score_max'] = score_dic[x][y][z]\nprint(score_max)\n\n''''''\n# 创建脑区与症状权重变化的三维的绘图工程\nax = plt.subplot(111, projection='3d')\n\nx_data = []\ny_data = []\nz_data = []\nfor x in score_dic:\n for y in score_dic[x]:\n for z in score_dic[x][y]:\n x_data.append(x/100)\n y_data.append(y/100)\n z_data.append(score_dic[x][y][z])\n\nax.scatter(x_data, y_data, z_data, c='y') # 绘制数据点\n\nax.set_zlabel('Score_percent') # 坐标轴\nax.set_ylabel('Y:Weight for symptoms_score')\nax.set_xlabel('X:Weight for brainStructure_score')\n# plt.show()\n\n# 创建脑区与影像学表现权重变化的三维的绘图工程\nax = plt.subplot(111, projection='3d')\n\nx_data = []\ny_data = []\nz_data = []\nfor x in score_dic:\n for y in score_dic[x]:\n for z in score_dic[x][y]:\n x_data.append(x/100)\n y_data.append(z/100)\n z_data.append(score_dic[x][y][z])\n\nax.scatter(x_data, y_data, z_data, c='y') # 绘制数据点\n\nax.set_zlabel('Score_percent') # 坐标轴\nax.set_ylabel('Z:Weight for image_score')\nax.set_xlabel('X:Weight for brainStructure_score')\n# plt.show()\n\n# 创建症状与影像学表现权重变化的三维的绘图工程\nax = plt.subplot(111, projection='3d')\n\nx_data = []\ny_data = []\nz_data = []\nfor x in score_dic:\n for y in score_dic[x]:\n for z in score_dic[x][y]:\n x_data.append(y/100)\n y_data.append(z/100)\n z_data.append(score_dic[x][y][z])\n\nax.scatter(x_data, y_data, z_data, c='y') # 绘制数据点\n\nax.set_zlabel('Score_percent') # 坐标轴\nax.set_ylabel('Z:Weight for image_score')\nax.set_xlabel('Y:Weight for symptoms_score')\n# plt.show()\n''''''" ]
[ [ "pandas.DataFrame", "matplotlib.pyplot.subplot" ] ]
jkoloda/deivos
[ "d41bc4d0cc62896fe0bf5e7a73a8e1ae7315795f" ]
[ "test/test_squeezenet.py" ]
[ "\"\"\"Tester for squeezenet module.\"\"\"\r\n\r\nimport unittest\r\nimport numpy as np\r\nimport tensorflow as tf\r\nfrom deivos.architectures.squeezenet import (\r\n default_preprocessor,\r\n expand,\r\n fire_module,\r\n get_model_v10,\r\n get_model_v11,\r\n squeeze,\r\n)\r\n\r\n\r\nclass TestLayers(unittest.TestCase):\r\n \"\"\"Tester for SqueezeNet architecture.\"\"\"\r\n\r\n # pylint: disable=too-many-instance-attributes\r\n\r\n def setUp(self):\r\n self.batch_size = 16\r\n self.rows = 24\r\n self.cols = 32\r\n self.channels = 20\r\n self.input_shape = (self.batch_size, self.rows,\r\n self.cols, self.channels)\r\n self.default_input_shape = (self.batch_size, 227, 227, 3)\r\n self.inputs = tf.random.normal(shape=self.input_shape)\r\n self.default_inputs = tf.random.normal(shape=self.default_input_shape)\r\n\r\n def test_squeeze(self):\r\n \"\"\"Test squeeze module.\"\"\"\r\n for _ in range(0, 100):\r\n filters = np.random.randint(low=1, high=2*self.channels)\r\n output_shape = (self.batch_size, self.rows, self.cols, filters)\r\n # Check shape after squeezing\r\n if filters < self.channels:\r\n outputs = squeeze(self.inputs, name='', filters=filters)\r\n self.assertTrue(outputs.shape == tf.TensorShape(output_shape))\r\n else:\r\n # Squeeze module cannot expand input\r\n with self.assertRaises(AssertionError):\r\n outputs = squeeze(self.inputs, name='', filters=filters)\r\n\r\n def test_expand(self):\r\n \"\"\"Test expand module.\"\"\"\r\n for _ in range(0, 100):\r\n filters = np.random.randint(low=1, high=2*self.channels)\r\n output_shape = (self.batch_size, self.rows, self.cols, 2*filters)\r\n # Check shape after expanding\r\n if filters > self.channels:\r\n outputs = expand(self.inputs, name='', filters=filters)\r\n self.assertTrue(outputs.shape == tf.TensorShape(output_shape))\r\n else:\r\n # Expand module cannot squeeze input\r\n with self.assertRaises(AssertionError):\r\n outputs = expand(self.inputs, name='', filters=filters)\r\n\r\n def test_fire_module(self):\r\n \"\"\"Test fire module.\"\"\"\r\n # Only test for one number of filters\r\n # Filter variety is tested by expand and squeeze tests\r\n filters_in = 10\r\n for squeeze_expand_ratio in [2, 3, 4]:\r\n # Expand squeezed dimension for both 1x1 and 3x3 filters\r\n filters_out = squeeze_expand_ratio * 2 * filters_in\r\n # No bypass\r\n output_shape = (self.batch_size, self.rows, self.cols, filters_out)\r\n outputs = fire_module(self.inputs, name='',\r\n squeeze_filters=filters_in, bypass=False,\r\n squeeze_expand_ratio=squeeze_expand_ratio)\r\n self.assertTrue(outputs.shape == tf.TensorShape(output_shape))\r\n # Complex bypass\r\n outputs = fire_module(self.inputs, name='',\r\n squeeze_filters=filters_in, bypass=True,\r\n squeeze_expand_ratio=squeeze_expand_ratio)\r\n self.assertTrue(outputs.shape == tf.TensorShape(output_shape))\r\n\r\n # Simple bypass\r\n for squeeze_expand_ratio in [2, 4, 5]:\r\n filters_in = self.channels//squeeze_expand_ratio\r\n # Expand squeezed dimension for both 1x1 and 3x3 filters\r\n filters_out = squeeze_expand_ratio * 2 * filters_in\r\n output_shape = (self.batch_size, self.rows, self.cols, filters_out)\r\n outputs = fire_module(self.inputs, name='',\r\n squeeze_filters=filters_in, bypass=True,\r\n squeeze_expand_ratio=squeeze_expand_ratio)\r\n self.assertTrue(outputs.shape == tf.TensorShape(output_shape))\r\n\r\n def test_default_preprocessor(self):\r\n \"\"\"Test deafult preprocessor.\"\"\"\r\n # Version 1.0, default input\r\n outputs = default_preprocessor(self.default_inputs, version='1.0')\r\n self.assertTrue(outputs.shape == (self.batch_size, 55, 55, 96))\r\n # Not default input\r\n with self.assertRaises(AssertionError):\r\n outputs = default_preprocessor(self.inputs, '1.0')\r\n\r\n # Version 1.1, default input\r\n outputs = default_preprocessor(self.default_inputs, version='1.1')\r\n self.assertTrue(outputs.shape == (self.batch_size, 56, 56, 64))\r\n # Not default input\r\n with self.assertRaises(AssertionError):\r\n outputs = default_preprocessor(self.inputs, version='1.1')\r\n\r\n def test_get_model_v10(self):\r\n \"\"\"Test SqueezeNet v1.0.\"\"\"\r\n layers = {'fire2_concat': (None, 55, 55, 128),\r\n 'fire3_concat': (None, 55, 55, 128),\r\n 'fire4_concat': (None, 55, 55, 256),\r\n 'fire5_concat': (None, 27, 27, 256),\r\n 'fire6_concat': (None, 27, 27, 384),\r\n 'fire7_concat': (None, 27, 27, 384),\r\n 'fire8_concat': (None, 27, 27, 512),\r\n 'fire9_concat': (None, 13, 13, 512)}\r\n\r\n for num_classes in [10, 100, 100]:\r\n for bypass_type in [None, 'simple', 'complex']:\r\n model = get_model_v10(num_classes=num_classes,\r\n bypass_type=bypass_type)\r\n for name, shape in layers.items():\r\n layer = model.get_layer(name)\r\n self.assertTrue(layer.output_shape == shape)\r\n self.assertTrue(model.output_shape == (None, num_classes))\r\n del model\r\n\r\n def test_get_model_v11(self):\r\n \"\"\"Test SqueezeNet v1.1.\"\"\"\r\n layers = {'fire2_concat': (None, 56, 56, 128),\r\n 'fire3_concat': (None, 56, 56, 128),\r\n 'fire4_concat': (None, 28, 28, 256),\r\n 'fire5_concat': (None, 28, 28, 256),\r\n 'fire6_concat': (None, 14, 14, 384),\r\n 'fire7_concat': (None, 14, 14, 384),\r\n 'fire8_concat': (None, 14, 14, 512),\r\n 'fire9_concat': (None, 14, 14, 512)}\r\n\r\n for num_classes in [10, 100, 100]:\r\n for bypass_type in [None, 'simple', 'complex']:\r\n model = get_model_v11(num_classes=num_classes,\r\n bypass_type=bypass_type)\r\n for name, shape in layers.items():\r\n layer = model.get_layer(name)\r\n self.assertTrue(layer.output_shape == shape)\r\n self.assertTrue(model.output_shape == (None, num_classes))\r\n del model\r\n\r\n def test_squeezenet(self):\r\n # TODO: Check that corresponding get models have been called\r\n pass\r\n\r\n\r\nif __name__ == '__main__':\r\n unittest.main()\r\n" ]
[ [ "tensorflow.random.normal", "tensorflow.TensorShape", "numpy.random.randint" ] ]
tridivb/Soccer_Ball_Detector_with_FCNN_and_ConvLSTM
[ "41758736a4f7fd29981f4954578e520a2f592099" ]
[ "utils/processing.py" ]
[ "import torch\r\nimport numpy as np\r\nimport cv2\r\n\r\n\r\nclass BoundingBox(object):\r\n \"\"\" Class to process the data as necessary\r\n \"\"\"\r\n def __init__(self, device):\r\n self.device = device\r\n\r\n def pre_process(self, bbox, input_size, output_size):\r\n \"\"\" Pre-process the data and create ground truth by fitting a gaussian at\r\n the location of the ball\r\n Args:\r\n bbox (Tensor): Input bounding box\r\n input_size (tuple): Size of input image\r\n output_size (tuple): Size of output image (ground truth)\r\n\r\n Returns:\r\n img_heatmap (Tensor): Ground truth heatmap\r\n bbox (Tensor): Scaled bounding box coordinates as per output_size\r\n \"\"\"\r\n # Check if ball is present or not from the bounding box coordinates\r\n # Center of bounding box must be greater than 0 for a ball to be present\r\n if not torch.equal(bbox[2], torch.DoubleTensor([0.0, 0.0]).to(self.device)):\r\n img_heatmap = torch.zeros(\r\n (output_size[0], output_size[1], output_size[2])).to(self.device)\r\n # Check if bounding box needs to be scaled or not\r\n if input_size != output_size:\r\n scale = torch.DoubleTensor([output_size[1]/input_size[1],\r\n output_size[2]/input_size[2]]).to(self.device)\r\n bbox[0] = torch.round(bbox[0] * scale)\r\n bbox[1] = torch.round(bbox[1] * scale)\r\n bbox[3][0] = torch.abs(bbox[0, 0]-bbox[1, 0])\r\n bbox[3][1] = torch.abs(bbox[0, 1]-bbox[1, 1])\r\n bbox[2][0], bbox[2][1] = bbox[0, 0]+bbox[3, 0] / \\\r\n 2, bbox[0, 1]+bbox[3, 1]/2\r\n\r\n pt1, pt2 = bbox[0], bbox[1]\r\n dist = torch.abs(pt1-pt2)\r\n width, length = dist[0].item(), dist[1].item()\r\n\r\n # Choose kernel size for gaussian\r\n if length > width:\r\n ksize = int(max(length, 15))\r\n else:\r\n ksize = int(max(width, 15))\r\n\r\n kernel = cv2.getGaussianKernel(ksize, 4)\r\n kernel = np.dot(kernel, kernel.T)\r\n kernel *= 100\r\n\r\n if pt1[1].item()+ksize > img_heatmap.shape[1]-1:\r\n kY_start = img_heatmap.shape[1]-1-ksize\r\n else:\r\n kY_start = int(pt1[1].item())\r\n\r\n if pt1[0].item()+ksize > img_heatmap.shape[2]-1:\r\n kX_start = img_heatmap.shape[2]-1-ksize\r\n else:\r\n kX_start = int(pt1[0].item())\r\n\r\n # Fit gaussian on the heatmap at bounding box location\r\n img_heatmap[0, kY_start:kY_start+ksize, kX_start:kX_start +\r\n ksize] = torch.from_numpy(kernel).to(self.device)\r\n\r\n else:\r\n # When no ball is present\r\n img_heatmap = torch.zeros(\r\n (output_size[0], output_size[1], output_size[2])).to(self.device)\r\n\r\n return img_heatmap, bbox\r\n\r\n def post_process(self, input, bbox=None):\r\n \"\"\" Post-process the output data from model and detect contours in it\r\n Extract bound box coordinates using the detected contours\r\n Args:\r\n input (Tensor): Input for post processing\r\n bbox (Tensor): Input bounding box to compare against(optional) [Default: None]\r\n\r\n Returns:\r\n confusion_matrix (2D Numpy array): Confusion matrix over input image\r\n detected_bbox_list (List): List of all detected bounding boxes in image\r\n \"\"\"\r\n # Convert to numpy and blur the image\r\n image = input.cpu().numpy()\r\n if input.shape[0] == 1:\r\n image = image.reshape(image.shape[1], image.shape[2])\r\n else:\r\n image = np.stack((image[2], image[1], image[0]), axis=2)\r\n image = (image*255).astype('uint8')\r\n image = cv2.medianBlur(image, 5)\r\n\r\n detected_bbox_list = []\r\n confusion_matrix = np.zeros((2, 2))\r\n # Set area threshold to filter out too small or too large blobs\r\n area_threshold_min = 20.0\r\n area_threshold_max = 5000.0\r\n # If annotation data is available calculate metrics\r\n if bbox is not None:\r\n ball_present = False\r\n ball_detected = False\r\n\r\n if bbox[3][0].item() > bbox[3][1].item():\r\n dist_threshold = bbox[3][0].item()\r\n else:\r\n dist_threshold = bbox[3][1].item()\r\n\r\n gt_cX, gt_cY = int(bbox[2][0].item()), int(bbox[2][1].item())\r\n\r\n if gt_cX > 0 or gt_cY > 0:\r\n ball_present = True\r\n\r\n # Erode and Dilute the image\r\n erosion_size = 4\r\n element = cv2.getStructuringElement(\r\n cv2.MORPH_ELLIPSE, (2*erosion_size + 1, 2*erosion_size+1), (erosion_size, erosion_size))\r\n image = cv2.erode(image, element)\r\n dilation_size = 4\r\n element = cv2.getStructuringElement(\r\n cv2.MORPH_ELLIPSE, (2*dilation_size + 1, 2*dilation_size+1), (dilation_size, dilation_size))\r\n image = cv2.dilate(image, element)\r\n\r\n _, img_thresh = cv2.threshold(image, 15, 255, cv2.THRESH_BINARY)\r\n _, contours, _ = cv2.findContours(\r\n img_thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\r\n\r\n # For each contour filter out invalid contours and get bounding boxes for the rest\r\n for c in contours:\r\n epsilon = 0.1*cv2.arcLength(c, True)\r\n c = cv2.approxPolyDP(c, epsilon, True)\r\n area = cv2.contourArea(c)\r\n if area >= area_threshold_min and area <= area_threshold_max:\r\n x, y, width, height = cv2.boundingRect(c)\r\n detected_bbox_list.append(np.array([[x, y], [width, height]]))\r\n if bbox is not None:\r\n ball_detected = True \r\n if ball_present:\r\n M = cv2.moments(c)\r\n cX = int(M[\"m10\"] / M[\"m00\"])\r\n cY = int(M[\"m01\"] / M[\"m00\"])\r\n dist = np.sqrt((cX - gt_cX)**2 + (cY - gt_cY)**2)\r\n if dist <= dist_threshold:\r\n # True Positive\r\n confusion_matrix[1, 1] += 1\r\n else:\r\n # False Positive\r\n confusion_matrix[0, 1] += 1\r\n else:\r\n # False Positive\r\n confusion_matrix[0, 1] += 1\r\n\r\n if bbox is not None:\r\n if ball_present and not ball_detected:\r\n # False Negative\r\n confusion_matrix[1, 0] += 1\r\n if not ball_present and not ball_detected:\r\n # True Negative\r\n confusion_matrix[0, 0] += 1\r\n\r\n return confusion_matrix, detected_bbox_list\r\n" ]
[ [ "torch.zeros", "torch.round", "numpy.array", "numpy.dot", "numpy.zeros", "torch.from_numpy", "torch.abs", "torch.DoubleTensor", "numpy.stack", "numpy.sqrt" ] ]
lakshaykc/lfm_quant
[ "ac6f47c9a36f681920314423e2502f3654c5b592" ]
[ "scripts/data_processing.py" ]
[ "from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport sys\nimport copy\nfrom datetime import datetime\nimport time\nimport pickle\nimport random\nimport pandas as pd\nimport numpy as np\nimport tensorflow as tf\nimport pathlib\nfrom sklearn import preprocessing as sk_pre\n\nfrom base_config import get_configs\n\n_MIN_SEQ_NORM = 10\n\n\nclass Dataset(object):\n \"\"\"\n Builds training, validation and test datasets based on ```tf.data.Dataset``` type\n\n Attributes:\n\n Methods:\n \"\"\"\n\n def __init__(self, config):\n self.config = config\n self._data_path = os.path.join(self.config.data_dir, self.config.datafile)\n\n self.is_train = self.config.train\n self.seq_len = self.config.max_unrollings\n\n # read and filter data_values based on start and end date\n self.data = pd.read_csv(self._data_path, sep=' ', dtype={'gvkey': str})\n try:\n self.data['date'] = pd.to_datetime(self.data['date'], format=\"%Y%m%d\")\n self.start_date = pd.to_datetime(self.config.start_date, format=\"%Y%m%d\")\n self.end_date = pd.to_datetime(self.config.end_date, format=\"%Y%m%d\")\n except ValueError:\n # time data does not match the format \"%Y%m%d\". For example non-cdrs data is in the format \"%Y%m\"\n self.data['date'] = pd.to_datetime(self.data['date'], format=\"%Y%m\")\n self.start_date = pd.to_datetime(self.config.start_date, format=\"%Y%m\")\n self.end_date = pd.to_datetime(self.config.end_date, format=\"%Y%m\")\n\n # date_offset_from_end is added end date to ensure tha target date is not Nan if data_values is available\n self._date_offset_from_end = pd.DateOffset(months=self.config.stride)\n # date_offset_from_start is subtracted to start_date to ensure enough history is present to build the dataset\n # from the start_date\n self._date_offset_from_start = pd.DateOffset(years=self.config.max_unrollings)\n self.data = self.data[(self.data['date'] >= self.start_date - self._date_offset_from_start) & \\\n (self.data['date'] <= self.end_date + self._date_offset_from_end)]\n\n # split gvkeys into train, validation\n self.gvkeys = self._get_gvkeys()\n self._train_gvkeys, self._valid_gvkeys, self._test_gvkeys = self.train_test_split(self.gvkeys,\n self.config.validation_size,\n self.config.seed,\n self.is_train)\n\n print(\"Start Date: %s\" % self.start_date.strftime('%Y-%m-%d'))\n print(\"End Date: %s\" % self.end_date.strftime('%Y-%m-%d'))\n print(\"Loading dataset %s complete\" % self.config.datafile)\n print(\"Total number of records: %i\" % self.data.shape[0])\n if self.config.train:\n print(\"Run type: Training\")\n print(\"Number of training entities: %i\" % len(self._train_gvkeys))\n print(\"Number of validation entities: %i\" % len(self._valid_gvkeys))\n else:\n print(\"Run type: Prediction\")\n print(\"Number of test entities: %i\" % len(self._test_gvkeys))\n\n _, self.fin_col_names = self.get_cols_from_colnames(self.config.financial_fields)\n _, self.aux_col_names = self.get_cols_from_colnames(self.config.aux_fields)\n _, self.dont_scale_col_names = self.get_cols_from_colnames(self.config.dont_scale_fields)\n\n self.n_inputs = len(self.fin_col_names) + len(self.aux_col_names)\n self.n_outputs = len(self.fin_col_names)\n\n # target_index refers to the column index of the target variable in the target data_values. Target\n # data_values is essentially the input data_values for fin_col_names shifted by stride. This mean the row for\n # next time step is the target for current time step.\n self.target_index = self.fin_col_names.index(self.config.target_field)\n\n self._cols = ['date', 'gvkey', 'active'] + self.fin_col_names + self.aux_col_names\n self._cols_offset = 3 # ['date', 'gvkey', ''active]\n\n # Append scale field if not in fin_cols + aux_cols\n if self.config.scale_field in self.data.columns and self.config.scale_field not in self._cols:\n self._cols.append(self.config.scale_field)\n\n # self.data = self.data[['date', 'gvkey', 'active'] + self.fin_col_names + self.aux_col_names]\n self.data = self.data[self._cols]\n\n # self._cols = self.data.columns.tolist()\n self._gvkey_idx = self._cols.index(self.config.key_field)\n self._date_idx = self._cols.index(self.config.date_field)\n self._active_idx = self._cols.index(self.config.active_field)\n self.fin_col_ids = [self._cols.index(x) for x in self.fin_col_names]\n self.aux_col_ids = [self._cols.index(x) for x in self.aux_col_names]\n self.dont_scale_col_ids = [self._cols.index(x) for x in self.dont_scale_col_names]\n self.inp_col_ids = self.fin_col_ids + self.aux_col_ids\n\n # scale_inp_col_ids are indexes of input tensor and not the _data matrix. _data matrix contains additional\n # columns such as date, gvkey. input tensors only contains fin + aux fields.\n self.scale_inp_col_ids = [x - self._cols_offset for x in self.inp_col_ids if x not in self.dont_scale_col_ids]\n\n self._aux_col_ids_seq = [x - self._cols_offset for x in self.aux_col_ids]\n\n # sequence normalizer\n if self.config.scale_field in self._cols:\n self._seq_norm_idx = self._cols.index(self.config.scale_field)\n else:\n self._seq_norm_idx = None\n\n # convert data_values from dataframe to numpy array for faster ops\n self.data_values = self.data.values\n self._dataset = {'train_X': [],\n 'train_Y': [],\n 'valid_X': [],\n 'valid_Y': [],\n 'test_X': [],\n 'test_Y': [],\n 'pre_metadata': []\n }\n # self._dataset values are converted from a list of sequences to np array of shape=(samples, seq_len, features)\n\n self.model_dir = None\n self.scaling_params = None\n\n def generate_dataset(self):\n \"\"\"\n Generates the dataset by adding dataset properties such as train_set, test_set to the instantiated class\n Also ensures scaling params are loaded and/or saved\n :return:\n \"\"\"\n # build tf.data_values.dataset\n self._create_tf_dataset()\n\n # scaling params\n self.model_dir = os.path.join(self.config.experiments_dir, self.config.model_dir)\n if not os.path.isdir(self.model_dir):\n pathlib.Path(self.model_dir).mkdir(parents=True, exist_ok=True)\n\n if not self.config.scalesfile:\n scales_path = os.path.join(self.model_dir, 'scales.dat')\n else:\n scales_path = self.config.scalesfile\n\n if self.config.train:\n try:\n self.scaling_params = pickle.load(open(scales_path, 'rb'))\n except FileNotFoundError:\n self.scaling_params = self.get_scaling_params()\n pickle.dump(self.scaling_params, open(scales_path, 'wb'))\n\n else: # prediction\n assert os.path.isfile(scales_path), \"scalesfile not provided. Ensure to use the same scalesfile as used \" \\\n \"during training \"\n self.scaling_params = pickle.load(open(scales_path, 'rb'))\n\n # print dataset stats\n # self._print_dataset_stats()\n\n def _create_tf_dataset(self):\n \"\"\"\n Builds training set, validation set as tf.data.dataset objects if config.train=True.\n Otherwise builds testing set as tf.data.dataset object.\n\n For each gvkey, sequences of len `max_unrollings` are built where the last element of the sequence is active.\n Sequences are padded with zeros if enough historical data is not present to meet `max_unrollings`. For example,\n if start_date=1980, max_unrollings=8 and company x only has data beginning 1975, sequences from 1971 to 1975\n will be padded with zeros.\n\n If targets are not present for inputs, Nans are returned. For example, if training end date is today's date,\n target data for 1 year into the future is will not be available, hence Nans are returned.\n\n\n shuffling and batching should be performed during training/ prediction\n\n\n Pseudo Code\n dataset = []\n for i in len(data):\n\n if active and\n start_date < date < end_date and\n has enough history (seq_len):\n\n create the sequence as np.array\n pad with zeros if seq_len < max_unrollings\n append to corresponding dataset (train, valid or test)\n\n concat sequences (np.arrays) to create np.array of shape=(num_sequences, seq_len, num_inputs/ num_outputs)\n convert to tf.data.dataset object\n \"\"\"\n\n min_steps = self.config.stride * (self.config.min_unrollings - 1) + 1\n max_steps = self.config.stride * (self.config.max_unrollings - 1) + 1\n\n last_key = ''\n cur_len = 1\n\n for i in range(self.data_values.shape[0]):\n key = self.data_values[i, self._gvkey_idx]\n active = True if int(self.data_values[i, self._active_idx]) else False\n date = self.data_values[i, self._date_idx]\n if i + self.config.forecast_n <= self.data_values.shape[0] - 1:\n tar_key = self.data_values[i + self.config.forecast_n, self._gvkey_idx]\n else:\n tar_key = ''\n\n if key != last_key:\n cur_len = 1\n if self.config.train: # Training\n if cur_len >= min_steps \\\n and active is True \\\n and self.start_date <= date <= self.end_date - pd.DateOffset(months=self.config.stride) \\\n and tar_key == key:\n self._append_sequence_data(cur_len, min_steps, max_steps, i, key, tar_key, date)\n\n cur_len += 1\n last_key = key\n\n else: # Prediction\n if cur_len >= min_steps \\\n and active is True \\\n and self.start_date <= date <= self.end_date:\n self._append_sequence_data(cur_len, min_steps, max_steps, i, key, tar_key, date)\n\n cur_len += 1\n last_key = key\n\n for k, v in self._dataset.items():\n if len(v) > 0:\n self._dataset[k] = np.concatenate(v, axis=0)\n else:\n self._dataset[k] = None\n\n return\n\n def _append_sequence_data(self, cur_len, min_steps, max_steps, idx, key, tar_key, date):\n \"\"\"\n Appends two forms of data to their respective dataset attributes\n 1. append [start_idc, end_idx, pad_size] for inputs, targets to self._dataset['*_X'], self._dataset['*_Y'], etc\n 2. append pre_metadata [date, inp_key, tar_key] to self._dataset['pre_metadata']\n :param cur_len: len of current key's elements from it's start date\n :param min_steps: number of min steps to form a sequence\n :param max_steps: number of max steps to form a sequence\n :param idx: index of the last element in the sequence\n :param key: input gvkey\n :param tar_key: gvkey of target\n :param date: date of input gvkey\n :return:\n \"\"\"\n assert cur_len >= min_steps\n\n seq_len = min(cur_len - (cur_len - 1) % self.config.stride, max_steps)\n pad_size = (max_steps - seq_len) // self.config.stride\n\n # train/valid/test sets define indices and are of the form [start_idx, end_idx, pad_size]\n inp_indices = np.expand_dims(np.array([idx - seq_len + 1, idx, pad_size]),\n axis=0)\n\n if key == tar_key:\n tar_indices = np.expand_dims(np.array([idx - seq_len + 1 + self.config.forecast_n,\n idx + self.config.forecast_n,\n pad_size]),\n axis=0)\n else: # tar_key could be another gvkey or '' i.e end of datafile\n tar_indices = np.expand_dims(np.array([idx - seq_len + 1 + self.config.forecast_n,\n idx,\n pad_size]),\n axis=0)\n\n pre_metadata = np.expand_dims(np.array([date.strftime(\"%Y%m%d\"), key, tar_key]),\n axis=0)\n\n self._append_idxs_to_dataset(key, inp_indices, tar_indices)\n self._append_pre_metadata_to_dataset(pre_metadata)\n\n def _append_idxs_to_dataset(self, key, inp_indices, tar_indices):\n if key in self._train_gvkeys and self.config.train:\n self._dataset['train_X'].append(inp_indices)\n self._dataset['train_Y'].append(tar_indices)\n elif key in self._valid_gvkeys and self.config.train:\n self._dataset['valid_X'].append(inp_indices)\n self._dataset['valid_Y'].append(tar_indices)\n elif key in self._test_gvkeys and not self.config.train:\n self._dataset['test_X'].append(inp_indices)\n self._dataset['test_Y'].append(tar_indices)\n else:\n raise ValueError(\"Mismatch between gvkey category (train/valid/test set) and run type (train/ pred)\")\n\n def _append_pre_metadata_to_dataset(self, pre_metadata):\n \"\"\"\n appends pre_metadata of the form np.array([[date, key]]) to the dataset\n :return:\n \"\"\"\n self._dataset['pre_metadata'].append(pre_metadata)\n\n def get_batch(self, inp_indices, tar_indices, pre_metadata):\n \"\"\"\n creates a batch of inps, tar given the corresponding start indices, end indices and padding size.\n :param inp_indices: batch of [start_idxs, end_idxs, pad_size] for inputs. shape=(batch_size, 3)\n :param tar_indices: batch of [start_idxs, end_idxs, pad_size] for targets. shape=(batch_size, 3)\n :param pre_metadata: batch of metadata [date, gvkey, seq_norm]. shape=(batch_size, 3).\n :return: inp_batch, target_batch, metadata_batch.\n\n metadata_batch is None during training and is only stored during prediction\n\n batch shape: (batch_size, seq_len, features)\n \"\"\"\n inp_indices, tar_indices, pre_metadata = inp_indices.numpy(), tar_indices.numpy(), pre_metadata.numpy()\n\n inp_batch = np.empty(shape=(inp_indices.shape[0], self.seq_len, len(self.inp_col_ids)))\n tar_batch = np.empty(shape=(tar_indices.shape[0], self.seq_len, self.n_outputs))\n metadata_batch = pre_metadata\n\n for i in range(inp_indices.shape[0]):\n inp_key, tar_key = pre_metadata[i, 1], pre_metadata[i, 2]\n if self.config.train:\n inp_batch[i, :, :], seq_norm = self._get_train_seq(inp_indices[i][0], inp_indices[i][1],\n inp_indices[i][2],\n self.inp_col_ids)\n tar_batch[i, :, :], _ = self._get_train_seq(tar_indices[i][0], tar_indices[i][1], tar_indices[i][2],\n self.fin_col_ids)\n else:\n inp_batch[i, :, :], seq_norm = self._get_pred_seq(inp_indices[i][0], inp_indices[i][1],\n inp_indices[i][2],\n inp_key, tar_key, self.inp_col_ids)\n tar_batch[i, :, :], _ = self._get_pred_seq(tar_indices[i][0], tar_indices[i][1], tar_indices[i][2],\n inp_key, tar_key, self.fin_col_ids)\n\n # Sequence Normalization\n inp_batch[i, :, 0:len(self.fin_col_ids)] /= seq_norm\n tar_batch[i, :, 0:len(self.fin_col_ids)] /= seq_norm\n # Log squasher\n if self.config.log_squasher:\n inp_batch[i, :, 0:len(self.fin_col_ids)] = self.log_squasher(inp_batch[i, :, 0:len(self.fin_col_ids)])\n tar_batch[i, :, 0:len(self.fin_col_ids)] = self.log_squasher(tar_batch[i, :, 0:len(self.fin_col_ids)])\n\n # overwrite tar_key column with seq_norm in pre_metadata to form metadata_batch\n metadata_batch[i, 2] = seq_norm\n\n # scaling params\n inp_batch[:, :, self.scale_inp_col_ids] = np.divide(\n inp_batch[:, :, self.scale_inp_col_ids] - \\\n self.scaling_params['center'][self.scale_inp_col_ids],\n self.scaling_params['scale'][self.scale_inp_col_ids])\n tar_batch = np.divide(tar_batch - self.scaling_params['center'][:len(self.fin_col_ids)],\n self.scaling_params['scale'][:len(self.fin_col_ids)])\n\n if self.config.aux_masking:\n # make aux fields to 0 for all time steps except the last one\n inp_batch[:, 0:self.seq_len - 1, self._aux_col_ids_seq] = 0.0\n\n if 'MLP' in self.config.nn_type or 'Naive' in self.config.nn_type:\n inp_batch = inp_batch.reshape(inp_indices.shape[0], self.seq_len * len(self.inp_col_ids))\n tar_batch = tar_batch[:, -1, :]\n\n return tf.convert_to_tensor(inp_batch, dtype=tf.float32), tf.convert_to_tensor(tar_batch, dtype=tf.float32), \\\n metadata_batch\n\n def _get_train_seq(self, start_idx, end_idx, pad_size, col_ids):\n \"\"\"\n returns sequence for training of dtype np.ndarray and shape=(seq_len, len(col_ids). The first pad_size elements\n in the sequence are zero is start_idx and end_idx do not form a sequence of seq_len.\n\n end_idx should exist in the data as targets cannot be nan during training\n\n :param start_idx: starting index of the sequence\n :param end_idx: end index of the sequence\n :param pad_size: number of elements in the sequence to be padded to match seq_len\n :param col_ids: column ids to create the sequences. Example input/ output column ids\n :return: sequence dtype: np.ndarray, shape=(seq_len, len(col_ids), seq_norm\n \"\"\"\n if pad_size > 0:\n seq = np.concatenate([np.zeros(shape=(pad_size, self.data_values.shape[1])),\n self.data_values[\n start_idx: end_idx + self.config.stride: self.config.stride,\n :]],\n axis=0)\n else:\n seq = self.data_values[start_idx: end_idx + self.config.stride: self.config.stride, :]\n\n # Sequence Normalization\n if self._seq_norm_idx:\n seq_norm = max(seq[-1, self._seq_norm_idx], _MIN_SEQ_NORM)\n else:\n seq_norm = 1.\n\n return seq[:, col_ids], seq_norm\n\n def _get_pred_seq(self, start_idx, end_idx, pad_size, inp_key, tar_key, col_ids):\n \"\"\"\n returns sequence for prediction of dtype np.ndarray and shape=(seq_len, len(col_ds))\n If start_idx and end_idx do not form a sequence of seq_len, zero padding is used.\n\n if end_idx > len(data) or gvkey of end_idx is not the same as current gvkey:\n Nans are returned\n\n :param start_idx: starting index of the sequence\n :param end_idx: end index of the sequence\n :param pad_size: umber of elements in the sequence to be padded to match seq_le\n :param inp_key: gvkey of input sequence\n :param tar_key: gvkey of target sequence\n :param col_ids: column ids to create the sequences. Example input/ output column ids\n :return: sequence dtype: np.ndarray, shape=(seq_len, len(col_ids), seq_norm\n \"\"\"\n\n if tar_key == inp_key:\n if pad_size > 0:\n seq = np.concatenate([np.zeros(shape=(pad_size, self.data_values.shape[1])),\n self.data_values[\n start_idx: end_idx + self.config.stride: self.config.stride,\n :]],\n axis=0)\n else:\n seq = self.data_values[start_idx: end_idx + self.config.stride: self.config.stride, :]\n\n else: # target values don't exist for the given time period. Return Nan filled np array\n seq = np.empty((self.seq_len - pad_size, self.data_values.shape[1]))\n seq[:] = np.nan\n for i, j in enumerate(range(start_idx, end_idx + self.config.stride, self.config.stride)):\n try:\n self.data_values[j, self._date_idx] = self.data_values[j, self._date_idx].strftime(\"%Y%m%d\")\n except AttributeError:\n pass\n seq[i, :] = self.data_values[j, :]\n\n if pad_size > 0:\n seq = np.concatenate([np.zeros(shape=(pad_size, seq.shape[1])), seq],\n axis=0)\n else:\n seq = seq\n\n # Sequence Normalization\n if self._seq_norm_idx:\n seq_norm = max(seq[-1, self._seq_norm_idx], _MIN_SEQ_NORM)\n else:\n seq_norm = 1.\n\n return seq[:, col_ids], seq_norm\n\n @property\n def train_set(self):\n assert self.config.train, 'config.train is not True. train_set is only available during training'\n X = tf.data.Dataset.from_tensor_slices(self._dataset['train_X'].astype('int32'))\n Y = tf.data.Dataset.from_tensor_slices(self._dataset['train_Y'].astype('int32'))\n return tf.data.Dataset.zip((X, Y, self.pre_metadata))\n\n @property\n def valid_set(self):\n assert self.config.train, \"config.train is not True. valid_set is only available during training\"\n X = tf.data.Dataset.from_tensor_slices(self._dataset['valid_X'].astype('int32'))\n Y = tf.data.Dataset.from_tensor_slices(self._dataset['valid_Y'].astype('int32'))\n return tf.data.Dataset.zip((X, Y, self.pre_metadata))\n\n @property\n def test_set(self):\n assert not self.config.train, \"config.train is not False. test_set is only available during prediction\"\n X = tf.data.Dataset.from_tensor_slices(self._dataset['test_X'].astype('int32'))\n Y = tf.data.Dataset.from_tensor_slices(self._dataset['test_Y'].astype('int32'))\n return tf.data.Dataset.zip((X, Y, self.pre_metadata))\n\n @property\n def pre_metadata(self):\n return tf.data.Dataset.from_tensor_slices(self._dataset['pre_metadata'])\n\n def get_cols_from_colnames(self, columns):\n \"\"\"\n Returns indexes and names of columns of data that are included in columns.\n columns are separated by commas and can include ranges. For example,\n f1-f5,f7,f9 would be feature one through 5, and feature 7 and 9.\n\n :param columns: columns or column ranges from the config file. eg. f1-f5,f7,f8\n :return: column indices, column names\n \"\"\"\n colidxs = []\n col_names = []\n\n if columns:\n data_cols = self.data.columns.tolist()\n col_list = columns.split(',')\n for col in col_list:\n col_range = col.split('-')\n if len(col_range) == 1:\n colidxs.append(list(data_cols).index(col_range[0]))\n col_names.append(col_range[0])\n elif len(col_range) == 2:\n start_idx = list(data_cols).index(col_range[0])\n end_idx = list(data_cols).index(col_range[1])\n assert (start_idx >= 0)\n assert (start_idx <= end_idx)\n colidxs.extend(list(range(start_idx, end_idx + 1)))\n col_names += [data_cols[i] for i in range(start_idx, end_idx + 1)]\n return colidxs, col_names\n\n def _get_gvkeys(self):\n \"\"\"\n :return: all gvkeys between start and end date\n \"\"\"\n assert isinstance(self.data, pd.DataFrame)\n gvkey_data = self.data[['date', 'gvkey']]\n gvkey_data = gvkey_data[gvkey_data['date'] <= self.end_date]\n\n return gvkey_data['gvkey'].unique()\n\n @staticmethod\n def train_test_split(keys, validation_size, seed, is_train):\n \"\"\"\n Splits a list (eg gvkeys) into training, validation and test lists based on validation size as a fraction\n of list size.\n If `is_train=False` i.e prediction, training and validation set are empty. Tests set contains all the keys\n if `is_train=True`, test set is empty\n :param keys: list of gvkeys\n :param validation_size: fraction of total size of list to be used for validation\n :param seed: random seed for split\n :param is_train: split only for training. If is_train is False, training set is None\n :return: train_keys, valid_keys\n \"\"\"\n np.random.seed(seed)\n if is_train:\n valid_keys = np.random.choice(keys, size=int(len(keys) * validation_size), replace=False)\n train_keys = list(set(keys) - set(valid_keys))\n test_keys = []\n else:\n train_keys = []\n valid_keys = []\n test_keys = keys\n return sorted(train_keys), sorted(valid_keys), sorted(test_keys)\n\n def get_scaling_params(self):\n \"\"\"\n Returns scaling parameters of the sklearn scaler specified in the config file.\n :return: sklearn scaler\n \"\"\"\n assert self.config.train, \"scaling params are only calculated during training\"\n\n indices_data = self._dataset['train_X'].tolist()\n\n data_sample = list()\n\n indices_sample = random.sample(indices_data, int(0.3 * len(indices_data)))\n\n for start_idx, end_idx, _ in indices_sample:\n step = random.randrange(self.config.min_unrollings)\n cur_idx = start_idx + step * self.config.stride\n assert cur_idx <= self.data_values.shape[0]\n x1 = self.get_feature_vector(cur_idx, end_idx)\n x2 = self.get_aux_vector(cur_idx)\n data_sample.append(np.append(x1, x2))\n\n scaler_class = self.config.data_scaler\n if hasattr(sk_pre, scaler_class):\n scaler = getattr(sk_pre, scaler_class)()\n else:\n raise RuntimeError(\"Unknown scaler = %s\" % scaler_class)\n\n scaler.fit(data_sample)\n\n params = dict()\n params['center'] = scaler.center_ if hasattr(scaler, 'center_') else scaler.mean_\n params['scale'] = scaler.scale_\n\n return params\n\n def get_feature_vector(self, cur_idx, end_idx):\n \"\"\"\n returns cur_idx feature vector normalized and log squashed by scale_field of last time step (i.e end_idx)\n :param cur_idx: idx of current time step\n :param end_idx: idx of last time step\n :return: np.array\n \"\"\"\n x = self.data_values[cur_idx, self.fin_col_ids]\n if self._seq_norm_idx:\n normalizer = max(self.data_values[end_idx, self._seq_norm_idx], _MIN_SEQ_NORM)\n else:\n normalizer = 1.\n x = np.divide(x, normalizer)\n if self.config.log_squasher:\n x_abs = np.absolute(x).astype(float)\n x = np.multiply(np.sign(x), np.log1p(x_abs))\n return x\n\n def get_aux_vector(self, cur_idx):\n \"\"\"\n return aux vector for cur_idx\n :param cur_idx:\n :return: np.array of shape=(len(aux_fields)\n \"\"\"\n return self.data_values[cur_idx, self.aux_col_ids]\n\n def log_squasher(self, x):\n \"\"\"\n Applies log squashing function i.e log(1 + x) if log_squasher is True in config\n :param x:\n :return:\n \"\"\"\n if self.config.log_squasher:\n x_abs = np.absolute(x).astype(float)\n x = np.multiply(np.sign(x), np.log1p(x_abs))\n return x\n\n def reverse_log_squasher(self, x):\n \"\"\"\n Reverses the log squashing function i. exp(x) - 1\n :param x:\n :return:\n \"\"\"\n if self.config.log_squasher:\n x = np.multiply(np.sign(x), np.expm1(np.fabs(x)))\n return x\n\n def print_dataset_stats(self):\n print(\"[samples, sequence_length, features]\")\n for k, v in self._dataset.items():\n if v is not None:\n print(\"%s : %s\" % (k, v.shape,))\n else:\n print(\"%s: None\" % k)\n\n\nclass CDRSInferenceData(Dataset):\n \"\"\"\n Dataset class object to generate data_values from the CDRS dataset for inference\n \"\"\"\n\n def __init__(self, config):\n super().__init__(config)\n\n assert self.end_date >= datetime.now(), \"\"\"Ensure the end_date in the config is set to a value greater than\n today's date, preferably 220012\"\"\"\n\n assert self.start_date <= datetime.now() - pd.offsets.DateOffset(years=self.seq_len), \"\"\"\n Ensure the start date goes back at least the seq_len, preferably 197501\"\"\"\n\n self.gvkeys = sorted(self.data['gvkey'].unique().tolist())\n self._train_gvkeys, self._valid_gvkeys, self._test_gvkeys = [], [], self.gvkeys\n\n assert not self.config.train, \"\"\"CDRS data_values can only be used during inference. \n Ensure the train=False in the config\"\"\"\n\n def generate_dataset(self):\n \"\"\"\n Generates dataset using CDRS Inference data_values as the source. Only builds the test_set as this is only applicable\n for inference. train, valid sets are empty lists.\n :return:\n \"\"\"\n # build tf.data_values.dataset\n self._create_tf_dataset()\n\n # scaling params\n self.model_dir = os.path.join(self.config.experiments_dir, self.config.model_dir)\n if not self.config.scalesfile:\n scales_path = os.path.join(self.model_dir, 'scales.dat')\n else:\n scales_path = self.config.scalesfile\n assert os.path.isfile(scales_path), \"scalesfile not provided. Make sure to use the same scalesfile as used \" \\\n \"during training \"\n self.scaling_params = pickle.load(open(scales_path, 'rb'))\n\n for k, v in self._dataset.items():\n if len(v) > 0:\n self._dataset[k] = np.concatenate(v, axis=0)\n else:\n self._dataset[k] = None\n\n def _create_tf_dataset(self):\n\n for i, gvkey in enumerate(self.gvkeys):\n gvkey_df = self.data[self.data.gvkey == gvkey]\n idxs = gvkey_df.index\n start_idx = idxs[0]\n end_idx = idxs[-1]\n pad_size = self.config.max_unrollings - len(idxs)\n date = self.data.loc[end_idx, 'date'].strftime(\"%Y%m%d\")\n seq_norm = np.nan # seq_norm is updated when batch is created using get_batch method\n\n self._dataset['test_X'].append(np.expand_dims(np.array([start_idx, end_idx, pad_size]),\n axis=0))\n self._dataset['test_Y'].append(np.expand_dims(np.array([start_idx, end_idx, pad_size]),\n axis=0)) # not used for predictions\n self._dataset['pre_metadata'].append(np.expand_dims(np.array([date, gvkey, seq_norm]),\n axis=0))\n\n def get_batch(self, inp_indices, tar_indices, pre_metadata):\n \"\"\"\n creates a batch of inps, tar given the corresponding start indices, end indices and padding size.\n :param inp_indices: batch of [start_idxs, end_idxs, pad_size] for inputs. shape=(batch_size, 3)\n :param tar_indices: batch of [start_idxs, end_idxs, pad_size] for targets. shape=(batch_size, 3)\n :param pre_metadata: batch of metadata [date, gvkey, seq_norm]. shape=(batch_size, 3).\n :return: inp_batch, target_batch, metadata_batch.\n\n metadata_batch is None during training and is only stored during prediction\n\n batch shape: (batch_size, seq_len, features)\n \"\"\"\n inp_indices, tar_indices, pre_metadata = inp_indices.numpy(), tar_indices.numpy(), pre_metadata.numpy()\n\n inp_batch = np.empty(shape=(inp_indices.shape[0], self.seq_len, len(self.inp_col_ids)))\n tar_batch = np.empty(shape=(tar_indices.shape[0], self.seq_len, self.n_outputs))\n metadata_batch = pre_metadata\n\n # Note: Each gvkey has only one sequence\n for i in range(inp_indices.shape[0]):\n inp_batch[i, :, :], seq_norm = self.get_pred_seq(inp_indices[i][0],\n inp_indices[i][1],\n inp_indices[i][2],\n self.inp_col_ids)\n # targets are not used when making predictions for the current date\n tar_batch[i, :, :] = np.nan\n\n # # Sequence normalization\n inp_batch[i, :, 0:len(self.fin_col_ids)] /= seq_norm\n # Log squasher\n if self.config.log_squasher:\n inp_batch[i, :, 0:len(self.fin_col_ids)] = self.log_squasher(inp_batch[i, :, 0:len(self.fin_col_ids)])\n\n # update seq_norm in metadata to form metadata_batch\n metadata_batch[i, 2] = seq_norm\n\n # scaling params\n inp_batch[:, :, self.scale_inp_col_ids] = np.divide(\n inp_batch[:, :, self.scale_inp_col_ids] - \\\n self.scaling_params['center'][self.scale_inp_col_ids],\n self.scaling_params['scale'][self.scale_inp_col_ids])\n\n if self.config.aux_masking:\n # make aux fields to 0 for all time steps except the last one\n inp_batch[:, 0:self.seq_len - 1, self._aux_col_ids_seq] = 0.0\n\n if 'MLP' in self.config.nn_type or 'Naive' in self.config.nn_type:\n inp_batch = inp_batch.reshape(inp_indices.shape[0], self.seq_len * len(self.inp_col_ids))\n tar_batch = tar_batch[:, -1, :]\n\n return tf.convert_to_tensor(inp_batch, dtype=tf.float32), tf.convert_to_tensor(tar_batch, dtype=tf.float32), \\\n metadata_batch\n\n def get_pred_seq(self, start_idx, end_idx, pad_size, col_ids):\n seq = self.data_values[start_idx: end_idx + 1, :]\n if pad_size > 0:\n seq = np.concatenate([np.zeros(shape=(pad_size, seq.shape[1])), seq],\n axis=0)\n else:\n seq = seq\n\n # Sequence normalization\n if self._seq_norm_idx:\n seq_norm = max(seq[-1, self._seq_norm_idx], _MIN_SEQ_NORM)\n else:\n seq_norm = 1.\n return seq[:, col_ids], seq_norm\n\n\nif __name__ == '__main__':\n pd.set_option('display.max_columns', 100)\n pd.set_option('display.max_rows', 100)\n # GCP Run\n t1 = time.time()\n config = get_configs()\n config.train = False\n # config.datafile = 'source-ml-data_values-v8-100M.dat'\n # config.datafile = 'sample_data_testing_4.dat'\n config.datafile = 'cdrs-ml-data.dat'\n config.data_dir = '../datasets'\n # config.model_dir = '../experiments/model'\n config.start_date = 20040101\n config.end_date = 22000101\n config.min_unrollings = 5\n config.max_unrollings = 5\n config.batch_size = 1\n config.scale_field = 'mrkcap'\n config.nn_type = 'RNNUqRangeEstimate'\n config.aux_masking = False\n config.model_dir = \"../experiments/test-model\"\n\n # D = Dataset(config)\n # D.generate_dataset()\n # print(D.scaling_params)\n # print(D._train_gvkeys, D._valid_gvkeys, D._test_gvkeys)\n \n # training_set = D.train_set.batch(batch_size=config.batch_size)\n # valid_set = D.valid_set.batch(batch_size=4)\n # pre_m_set = D.pre_metadata.batch(batch_size=4)\n\n # print(training_set)\n\n # for i, train_items in enumerate(training_set):\n # pass\n # print(i)\n # inp_idxs = train_items[0]\n # tar_idxs = train_items[1]\n # pre_m = train_items[2]\n # inp, tar, metadata = D.get_batch(inp_idxs, tar_idxs, pre_m)\n # if i == 0:\n # print(\"INP\")\n # print(inp)\n # print(\"TAR\")\n # print(tar)\n # print(\"M\")\n # print(metadata)\n # break\n\n # ------------------------------------------------------------------------\n # Test CDRSInferenceData\n cdrs_d = CDRSInferenceData(config)\n cdrs_d.generate_dataset()\n # # Load data_values\n # test_set = cdrs_d.test_set\n # test_set = test_set.batch(batch_size=config.batch_size)\n # # t = time.time()\n # for (batch_n, test_set_items) in enumerate(test_set):\n # inp_idxs = test_set_items[0]\n # tar_idxs = test_set_items[1]\n # pre_metadata = test_set_items[-1]\n # inp, targets, metadata = cdrs_d.get_batch(inp_idxs, tar_idxs, pre_metadata)\n # # if batch_n % 100 == 0:\n # # print(batch_n, time.time() - t)\n # # t = time.time()\n" ]
[ [ "tensorflow.data.Dataset.from_tensor_slices", "numpy.sign", "pandas.read_csv", "pandas.offsets.DateOffset", "numpy.divide", "numpy.concatenate", "numpy.empty", "pandas.set_option", "numpy.log1p", "pandas.DateOffset", "numpy.fabs", "numpy.append", "pandas.to_datetime", "numpy.array", "numpy.zeros", "numpy.absolute", "tensorflow.convert_to_tensor", "numpy.random.seed", "tensorflow.data.Dataset.zip" ] ]
Abhimanyu8/Utkranti4.0_Team_Runtime_Matrix
[ "a69978d1397e90e7e13eb77c614e47ee8dd9085c" ]
[ "Video FPS benchmark.py" ]
[ "# import the necessary packages\nfrom imutils.video import FPS\nimport numpy as np\nimport argparse\nimport imutils\nimport cv2\n# construct the argument parse and parse the arguments\nap = argparse.ArgumentParser()\nap.add_argument(\"-v\", \"--video\", required=True,\n\thelp=\"path to input video file\")\nargs = vars(ap.parse_args())\n# open a pointer to the video stream and start the FPS timer\nstream = cv2.VideoCapture(args[\"video\"])\nfps = FPS().start()\n\n# loop over frames from the video file stream\nwhile True:\n # grab the frame from the threaded video file stream\n (grabbed, frame) = stream.read()\n # if the frame was not grabbed, then we have reached the end of the stream\n if not grabbed:\n break\n # resize the frame and convert it to grayscale (while still retaining 3 channels)\n frame = imutils.resize(frame, width=450)\n frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n frame = np.dstack([frame, frame, frame])\n # display a piece of text to the frame (so we can benchmark fairly against the fast method)\n cv2.putText(frame, \"Slow Method\", (10, 30),\n cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 2)\t\n # show the frame and update the FPS counter\n cv2.imshow(\"Frame\", frame)\n cv2.waitKey(1)\n fps.update()\n \n\n\n# stop the timer and display FPS information\nfps.stop()\nprint(\"[INFO] elasped time: {:.2f}\".format(fps.elapsed()))\nprint(\"[INFO] approx. FPS: {:.2f}\".format(fps.fps()))\n# do a bit of cleanup\nstream.release()\ncv2.destroyAllWindows()\n" ]
[ [ "numpy.dstack" ] ]
devskroy1/ForkedBrainSurfaceTK
[ "774035ab5eae6c0a40eb96eab43d489d3f722eaa" ]
[ "models/pointnet/src/models/pointnet2_regression_v2.py" ]
[ "import torch\nimport torch.nn.functional as F\nfrom torch.nn import Sequential as Seq, Linear as Lin, ReLU, BatchNorm1d as BN\nfrom torch_geometric.nn import PointConv, fps, radius, global_max_pool\n\n\nclass SAModule(torch.nn.Module):\n def __init__(self, ratio, r, nn):\n super(SAModule, self).__init__()\n self.ratio = ratio\n self.r = r\n self.conv = PointConv(nn)\n\n def forward(self, x, pos, batch):\n idx = fps(pos, batch, ratio=self.ratio)\n row, col = radius(pos, pos[idx], self.r, batch, batch[idx],\n max_num_neighbors=64)\n edge_index = torch.stack([col, row], dim=0)\n x = self.conv(x, (pos, pos[idx]), edge_index)\n pos, batch = pos[idx], batch[idx]\n return x, pos, batch\n\n\nclass GlobalSAModule(torch.nn.Module):\n def __init__(self, nn):\n super(GlobalSAModule, self).__init__()\n self.nn = nn\n\n def forward(self, x, pos, batch):\n x = self.nn(torch.cat([x, pos], dim=1))\n x = global_max_pool(x, batch)\n pos = pos.new_zeros((x.size(0), 3))\n batch = torch.arange(x.size(0), device=batch.device)\n return x, pos, batch\n\n\ndef MLP(channels, batch_norm=True):\n return Seq(*[\n Seq(Lin(channels[i - 1], channels[i]), ReLU(), BN(channels[i]))\n for i in range(1, len(channels))\n ])\n\n\nclass Net(torch.nn.Module):\n def __init__(self, num_local_features, num_global_features):\n super(Net, self).__init__()\n\n self.num_global_features = num_global_features\n\n # 3+num_local_features IS 3 FOR COORDINATES, num_local_features FOR FEATURES PER POINT.\n self.sa1_module = SAModule(0.5, 0.2, MLP([3 + num_local_features, 32, 32, 64]))\n self.sa2_module = SAModule(0.25, 0.4, MLP([64 + 3, 64, 64, 128]))\n self.sa3_module = GlobalSAModule(MLP([128 + 3, 128, 256, 512]))\n\n self.lin1 = Lin(512 + num_global_features, 256)\n self.lin2 = Lin(256, 128)\n self.lin3 = Lin(128, 1)\n\n def forward(self, data):\n sa0_out = (data.x, data.pos, data.batch)\n sa1_out = self.sa1_module(*sa0_out)\n sa2_out = self.sa2_module(*sa1_out)\n sa3_out = self.sa3_module(*sa2_out)\n x, pos, batch = sa3_out\n\n if self.num_global_features > 0:\n x = torch.cat((x, data.y[:, 1:self.num_global_features+1].view(-1, self.num_global_features)), 1)\n\n x = F.relu(self.lin1(x))\n x = F.relu(self.lin2(x))\n x = self.lin3(x)\n\n return x.view(-1)\n" ]
[ [ "torch.nn.Linear", "torch.cat", "torch.stack", "torch.nn.ReLU", "torch.nn.BatchNorm1d" ] ]
mhamedLmarbouh/bonnetal
[ "f8ab00cf0d2aa4bfa5d6c3fe1512e1c6a4d60d32" ]
[ "train/tasks/classification/modules/traceSaver.py" ]
[ "#!/usr/bin/env python3\n# This file is covered by the LICENSE file in the root of this project.\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.backends.cudnn as cudnn\nimport torchvision.transforms as transforms\nimport imp\nimport yaml\nimport time\nfrom PIL import Image\nimport numpy as np\nimport __init__ as booger\nimport collections\nimport copy\nimport os\n\nfrom backbones.config import *\nfrom tasks.classification.modules.head import *\nfrom tasks.classification.modules.classifier import *\nimport onnx\n\n\nclass TraceSaver():\n def __init__(self, path, new_path, force_img_prop=(None, None)):\n # parameters\n self.path = path\n self.new_path = new_path\n\n # config from path\n try:\n yaml_path = self.path + \"/cfg.yaml\"\n print(\"Opening config file %s\" % yaml_path)\n self.CFG = yaml.load(open(yaml_path, 'r'))\n except Exception as e:\n print(e)\n print(\"Error opening cfg.yaml file from trained model.\")\n quit()\n\n # if force img prop is a tuple with 2 elements, force image props\n if force_img_prop[0] is not None or force_img_prop[1] is not None:\n if force_img_prop[0] is not None:\n self.CFG[\"dataset\"][\"img_prop\"][\"height\"] = force_img_prop[0]\n if force_img_prop[1] is not None:\n self.CFG[\"dataset\"][\"img_prop\"][\"width\"] = force_img_prop[1]\n print(\"WARNING: FORCING IMAGE PROPERTIES TO\")\n print(self.CFG[\"dataset\"][\"img_prop\"])\n\n # get the data\n parserModule = imp.load_source(\"parserModule\",\n booger.TRAIN_PATH + '/tasks/classification/dataset/' +\n self.CFG[\"dataset\"][\"name\"] + '/parser.py')\n self.parser = parserModule.Parser(img_prop=self.CFG[\"dataset\"][\"img_prop\"],\n img_means=self.CFG[\"dataset\"][\"img_means\"],\n img_stds=self.CFG[\"dataset\"][\"img_stds\"],\n classes=self.CFG[\"dataset\"][\"labels\"],\n train=False)\n self.data_h, self.data_w, self.data_d = self.parser.get_img_size()\n\n # get architecture and build backbone (with pretrained weights)\n self.bbone_cfg = BackboneConfig(name=self.CFG[\"backbone\"][\"name\"],\n os=self.CFG[\"backbone\"][\"OS\"],\n h=self.data_h,\n w=self.data_w,\n d=self.data_d,\n dropout=self.CFG[\"backbone\"][\"dropout\"],\n bn_d=self.CFG[\"backbone\"][\"bn_d\"],\n extra=self.CFG[\"backbone\"][\"extra\"])\n\n self.head_cfg = HeadConfig(n_class=self.parser.get_n_classes(),\n dropout=self.CFG[\"head\"][\"dropout\"])\n\n # concatenate the encoder and the head\n self.model = Classifier(self.bbone_cfg,\n self.head_cfg,\n self.path,\n strict=True)\n\n # CUDA speedup?\n if torch.cuda.is_available():\n cudnn.fastest = True\n cudnn.benchmark = True\n self.model = self.model.cuda()\n\n # don't train\n self.model.eval()\n for w in self.model.backbone.parameters():\n w.requires_grad = False\n for w in self.model.head.parameters():\n w.requires_grad = False\n\n # print number of parameters and the ones requiring gradients\n weights_total = sum(p.numel()\n for p in self.model.parameters())\n weights_grad = sum(p.numel()\n for p in self.model.parameters() if p.requires_grad)\n print(\"Total number of parameters: \", weights_total)\n print(\"Total number of parameters requires_grad: \", weights_grad)\n\n # profiler based saver, so create a dummy input to infer\n print(\"Creating dummy input to profile\")\n self.dummy_input = torch.randn(1, self.CFG[\"dataset\"][\"img_prop\"][\"depth\"],\n self.CFG[\"dataset\"][\"img_prop\"][\"height\"],\n self.CFG[\"dataset\"][\"img_prop\"][\"width\"])\n # gpu?\n if torch.cuda.is_available():\n self.dummy_input = self.dummy_input.cuda()\n\n def export_config(self):\n # save the config file in the log folder\n try:\n new_yaml_path = self.new_path + \"/cfg.yaml\"\n print(\"Saving config file %s\" % new_yaml_path)\n with open(new_yaml_path, 'w') as outfile:\n yaml.dump(self.CFG, outfile, default_flow_style=False)\n except Exception as e:\n print(e)\n print(\"Error saving cfg.yaml in new model dir \", new_yaml_path)\n quit()\n\n def export_ONNX(self):\n # convert to ONNX traced model\n\n # create profile\n onnx_path = os.path.join(self.new_path, \"model.onnx\")\n with torch.no_grad():\n print(\"Profiling model\")\n print(\"saving model in \", onnx_path)\n torch.onnx.export(self.model, self.dummy_input, onnx_path)\n\n # check that it worked\n print(\"Checking that it all worked out\")\n model_onnx = onnx.load(onnx_path)\n onnx.checker.check_model(model_onnx)\n\n # Print a human readable representation of the graph\n # print(onnx.helper.printable_graph(model_onnx.graph))\n\n def export_pytorch(self):\n # convert to Pytorch traced model\n\n # create profile\n pytorch_path = os.path.join(self.new_path, \"model.pytorch\")\n with torch.no_grad():\n print(\"Profiling model\")\n pytorch_model = torch.jit.trace(self.model, self.dummy_input)\n print(\"saving model in \", pytorch_path)\n pytorch_model.save(pytorch_path)\n\n def export(self):\n \"\"\"Export config file, ONNX model, and Pytorch traced model to log directory\n \"\"\"\n self.export_config()\n self.export_ONNX()\n self.export_pytorch()\n" ]
[ [ "torch.no_grad", "torch.cuda.is_available", "torch.onnx.export", "torch.jit.trace", "torch.randn" ] ]
bracket/handsome
[ "c93d34f94d0eea24f5514efc9bc423eb28b44a6b" ]
[ "tests/test_micropolygon.py" ]
[ "from handsome.Micropolygon import Micropolygon\nfrom handsome.util import point\nimport numpy as np\n\ndef test_micropolygon():\n m = Micropolygon(\n point(0, 0),\n point(1, 0),\n point(1, 1),\n point(2, 1),\n )\n\n tests = [\n [ (.5 , .5) , np.array([ 1, .5 , 1, 1 ]), ],\n [ (.25, .75), np.array([ 1, .75, 1, 1 ]), ],\n [ (0. , 0.) , np.array([ 0, 0 , 1, 1 ]), ],\n [ (1. , 0.) , np.array([ 1, 0 , 1, 1 ]), ],\n [ (0. , 1.) , np.array([ 1, 1 , 1, 1 ]), ],\n [ (1. , 1.) , np.array([ 2, 1 , 1, 1 ]), ],\n ]\n\n for input, expected in tests:\n actual = m(*input)\n np.testing.assert_array_equal(actual, expected)\n" ]
[ [ "numpy.array", "numpy.testing.assert_array_equal" ] ]
Biles430/Python_Modules
[ "6434e587699f745f244b99cef57f75dcd99b749f" ]
[ "hotwire.py" ]
[ "#!/usr/bin/python\n# Filename: HotWire.py\n\n################### IMPORTS #######################\nimport pandas as pd\nfrom pandas import DataFrame\nimport numpy as np\nimport h5py\n#######################################################\n #LAST UPDATED : 8-16-16\n#######################################################\n\n#############################################################################\n#################### Read in Hot Wire text files #####################\n# FUNCTION\n#This function will take a series of text files and arrange them into a\n#dataframe for further analysis\n#changed to put first value as zero\n# UPDATED: 4-22-2016\n# INPUTS\n#name = name of file\n#num_files = number of files\n#delim = deliminter between values\n#file_format is the format of the data file (.csv, .txt ...)\n# OUTPUTS,\n#returndata = np.array containing all imported data sets\n# [j] = individual data sets\n# NOTES\n#Updated to put ouput as np.array for easier vector manipulation\n\ndef readin(name, numfiles, delim, file_format):\n\n #determine length\n N = len(np.loadtxt((name+str(0)+file_format), dtype=float, delimiter=delim, skiprows=1))\n #initalize size of return data set\n returndata = np.zeros([numfiles, N])\n #step through name of file\n for j in range(0,numfiles):\n file_name = name + str(j) + file_format\n #open data file (could use data path)\n #with open(file_name,'r') as datafile:\n #skip first row and load all data as float\n data = np.loadtxt(file_name, dtype=float, delimiter=delim, skiprows=1)\n #place data in overall array\n returndata[j] = data[0:N]\n return(returndata)\n\n#############################################################################\n#################### Determine Wall Norm Position #####################\n# FUNCTION\n#This function creates a set of log spaced points to be used as the wall\n#normal positions from a profiling experiment\n#Changed to put first position as zero\n# UPDATED: 4-22-2016\n# INPUTS\n#L = Lowest Position\n#H = Highest Position\n#N = Number of steps\n# OUTPUTS,\n#x = np.array containing N number of heights\n\ndef probe_height(L, H, N):\n #initalize variables\n x = np.zeros(N)\n position = (np.log10(H)-np.log10(L))/(N-1)\n for i in range(0,N):\n x[i] = L*10**((i)*position)\n return(x)\n\n#############################################################################\n#################### Calculate BL thickness #####################\n# FUNCTION\n#This function will compute the boundary layer thickness using the 99% method\n#Note it is for Twall > Tair\n# UPDATED: 4-06-2017\n# INPUTS\n#data = set of mean data values at each position x\n#x = wall normal positions\n# OUTPUTS,\n#delta = boundary layer thickness\n# UPDATES\n#Need to change such that it can caluculate Twall>Tair or for Twall<Tair\n\ndef delta(data, x, U_inf, threshold, profile):\n #create place holder\n temp_delta = 0\n N = len(data)\n temp = data/U_inf\n ##0 -> 1\n if profile == 0:\n for j in range(1,N):\n if temp[j] >= threshold:\n if temp[j-1] <= threshold:\n #interpolate to find true value\n temp_delta = (threshold-temp[j-1])/(temp[j]-temp[j-1])*(x[j]-x[j-1])+x[j-1]\n break\n delta_pos = j+1\n ##1 -> 0\n threshold = 1+(1-threshold)\n if profile == 1:\n for j in range(1,N):\n if temp[j] <= threshold:\n if temp[j-1] >= threshold:\n #interpolate to find true value\n temp_delta = (threshold-temp[j-1])/(temp[j]-temp[j-1])*(x[j]-x[j-1])+x[j-1]\n break\n delta_pos = j+1\n return(temp_delta, delta_pos)\n\n#############################################################################\n#################### Normalize Temp Profile #####################\n# FUNCTION\n#This function normalizes the thermal BL profile and computes\n#the analytical profile\n# UPDATED: 2-24-2016\n# INPUTS\n#data = set of mean data values at each position x\n#x = wall normal positions\n# OUTPUTS,\n#delta = boundary layer thickness\n# UPDATES\n\ndef T_norm(data, y, delta):\n #theta = pd.DataFrame()\n N = len(data)\n #normalize data\n temp1 = (data-data[N-1])/(data[0]-data[N-1])\n #calculate eta\n temp2 = y/delta\n #calc analytical profile\n temp3 = 1-1.5*temp2+.5*temp2**3\n d = {'Eta': temp2, 'Theta_T': temp1, 'Theta_A': temp3}\n theta = pd.DataFrame(d)\n return(theta)\n\n#############################################################################\n#################### DETERMINE AIR PROP #####################\n# FUNCTION\n#This function determines the thermal propeties of air from a ref table\n# UPDATED: 4-19-2016\n# INPUTS\n#T_given = input temperature\n#x = wall normal positions\n# OUTPUTS,\n#k\n#rho#nu\n#c\n\n# UPDATES\ndef air_prop(T_given):\n air_prop_data = pd.read_hdf('data/airprop1.h5', 'air_prop')\n for j in range(0, len(air_prop_data['T'])):\n if T_given < air_prop_data['T'][j]:\n #if air_prop_data['T'][j+1] > T_given:\n delta_T= air_prop_data['T'][j] - air_prop_data['T'][j-1]\n delta_given = T_given - air_prop_data['T'][j]\n rho = (air_prop_data['rho'][j] - air_prop_data['rho'][j-1])/delta_T * delta_given + air_prop_data['rho'][j]\n k = (air_prop_data['k'][j] - air_prop_data['k'][j-1])/delta_T * delta_given + air_prop_data['k'][j]\n cp = (air_prop_data['cp'][j] - air_prop_data['cp'][j-1])/delta_T * delta_given + air_prop_data['cp'][j]\n nu = ((air_prop_data['nu'][j] - air_prop_data['nu'][j-1])/delta_T * delta_given + air_prop_data['nu'][j])*(10**(-6))\n Pr = (air_prop_data['Pr'][j] - air_prop_data['Pr'][j-1])/delta_T * delta_given + air_prop_data['Pr'][j]\n air_prop = {'k':k, 'nu':nu, 'rho':rho, 'cp':cp, 'Pr':Pr}\n return(air_prop)\n\n#############################################################################\n#################### Read in Hot Wire text files #####################\n# FUNCTION\n#This function performs a spatial average on a dataset. It was written for\n# thermocouple profiles so account for the diam of the TC bulb\n# UPDATED: 8-16-16\n# INPUTS\n#data = name of file\n#y_pos = number of files\n#probe_diam = deliminter between values\n#file_format is the format of the data file (.csv, .txt ...)\n# OUTPUTS,\n#returndata = np.array containing all imported data sets\n# [j] = individual data sets\n# NOTES\n#Updated to put ouput as np.array for easier vector manipulation\ndef spatial_avg(data, y_pos, probe_diam, walloffset):\n #probe_diam = .00106 #m\n probe_pos = np.zeros(1) + probe_diam/2 + walloffset\n pos = int(y_pos[0])\n data_avg = np.array(data[0])\n while (probe_pos[-1] + probe_diam/2) < y_pos[-1]:\n count = 0\n sum_data = 0\n for j in range(pos, len(y_pos)):\n if y_pos[j] < (probe_pos[-1] + probe_diam/2):\n count+=1\n sum_data = sum_data + data[j]\n else:\n #if y_pos > then average above summed data and set new y probe pos\n #avg sum datasets\n sum_data = sum_data/count\n #append avg onto new dataset\n data_avg = np.append(data_avg, sum_data)\n #append y pos onto new dataset\n probe_pos = np.append(probe_pos, y_pos[j]+probe_diam/2)\n #save last position so for loop can begin there\n pos = j\n break\n return(probe_pos, data_avg)\n\n#############################################################################\n#################### Perform differentiation on dataset #####################\n# FUNCTION\n#This function performs a differentiation based on the provided inputs. It utilizes a\n# richardson nonunifrom approach as recommended by Dr. Ebadi\n# UPDATED: 05-02-17\n# INPUTS\n#x= x of dataset\n#y = y of dataset\n# OUTPUTS,\n#dydx = differentiated dataset\n# NOTES\n\ndef richardson(x,y):\n y = np.array(y)\n x = np.array(x)\n m = np.size(y)\n dydx = np.zeros(m)\n dydx[0] = (y[1] - y[0]) / (x[1] - x[0])\n if m == 1:\n dydx[-1] = dydx[0];\n elif m < 5:\n for i in range(1, len(y) - 2):\n dydx[i] = (y[i + 1] - y[i - 1]) / (x[i + 1] - x[i - 1])\n dydx[-1] = (y[-1] - y[-2]) / (x[-1] - x[-2])\n else:\n for i in range(1,3):\n dydx[i] = (y[i + 1] - y[i - 1]) / (x[i + 1] - x[i - 1])\n for i in range(3, m - 2):\n dydx[i] = (-y[i + 2] + 8*y[i + 1] - 8*y[i - 1] + y[i - 2]) / (6*(x[i + 1] - x[i - 1]));\n i = m - 2\n dydx[i] = (y[i + 1] - y[i - 1]) / (x[i + 1] - x[i - 1]);\n dydx[-1] = (y[-1] - y[-2]) / (x[-1] - x[-2]);\n\n return dydx\n\n#############################################################################\n#################### Perform shear based PST correction #####################\n# FUNCTION\n#This function takes a correction factor from S.C.C. Bailey et al and applies it\n# to experimental PST datasets\n# UPDATED: 05-18-17\n# INPUTS\n#u= u of dataset\n#y = y of dataset\n#uinf = free stream velocity\n#Dp = diameter of PST\n# OUTPUTS,\n#ynew = new y positions based on delta_y correction\n# NOTES\n\ndef pst_shear_correction(u, y, uinf, Dp):\n\t#define richardson #\n def richardson(x,y):\n y = np.array(y)\n x = np.array(x)\n m = np.size(y)\n dydx = np.zeros(m)\n dydx[0] = (y[1] - y[0]) / (x[1] - x[0])\n if m == 1:\n dydx[-1] = dydx[0];\n elif m < 5:\n for i in range(1, len(y) - 2):\n dydx[i] = (y[i + 1] - y[i - 1]) / (x[i + 1] - x[i - 1])\n dydx[-1] = (y[-1] - y[-2]) / (x[-1] - x[-2])\n else:\n for i in range(1,3):\n dydx[i] = (y[i + 1] - y[i - 1]) / (x[i + 1] - x[i - 1])\n for i in range(3, m - 2):\n dydx[i] = (-y[i + 2] + 8*y[i + 1] - 8*y[i - 1] + y[i - 2]) / (6*(x[i + 1] - x[i - 1]));\n i = m - 2\n dydx[i] = (y[i + 1] - y[i - 1]) / (x[i + 1] - x[i - 1]);\n dydx[-1] = (y[-1] - y[-2]) / (x[-1] - x[-2]);\n\n return dydx\n\n ynew = np.zeros(len(y))\n dudy = ((richardson(y, u)**2)**(1/2))\n alpha = (Dp/ (2*uinf) ) * dudy\n delta_y = (.15 * np.tanh(4 * (alpha)**(1/2) ) ) * Dp\n ynew = y + delta_y\n ynew[0] = 0\n return(ynew)\n\n#############################################################################\n#################### Perform new wall based PST correction #################\n# FUNCTION\n#This function takes a correction factor from S.C.C. Bailey et al and applies it\n# to experimental PST datasets\n# UPDATED: 05-18-17\n# INPUTS\n#u= u of dataset\n#y = y of dataset\n#utau = friction velocity determined from dataset\n#Dp = diameter of PST\n# OUTPUTS,\n#unew = shifted velocities \n# NOTES\n\ndef pst_wall_correction(u, y, utau, Dp, nu):\n unew = np.zeros(len(u))\n dplus = (Dp*utau) / nu\n udelta = (20*np.exp(-.1*dplus) + 1)*.015 * np.exp(-2.5* (y/Dp - .5))\n unew = (1/ (1-udelta))*u\n return(unew)\n\n\n" ]
[ [ "numpy.array", "numpy.zeros", "pandas.DataFrame", "numpy.exp", "numpy.tanh", "numpy.loadtxt", "pandas.read_hdf", "numpy.size", "numpy.append", "numpy.log10" ] ]
graziegrazie/SC-CAM
[ "0c3b40e15ba5c4164287f07931a076001249d706" ]
[ "tool/infer_utils.py" ]
[ "import os\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom PIL import Image\nimport shutil\nimport scipy.misc\nimport imageio\nimport math\n\n\n\ndef create_class_key_in_dict(dict, cls_nb):\n for i in range(cls_nb):\n dict[i] = []\n return dict\n\n\ndef calculate_class_avg_iou(class_iou_dict):\n class_mean_iou_dict = {}\n for i in range(20):\n class_iou_list = class_iou_dict[i]\n if len(class_iou_list) != 0:\n class_iou_list_mean = round(sum(class_iou_list)/len(class_iou_list), 4)\n else:\n class_iou_list_mean = 0.\n class_mean_iou_dict[i] = class_iou_list_mean\n return class_mean_iou_dict\n\n\ndef draw_heatmap(img, hm):\n hm = plt.cm.hot(hm)[:, :, :3]\n hm = np.array(Image.fromarray((hm*255).astype(np.uint8), 'RGB').resize((img.shape[1], img.shape[0]), Image.BICUBIC)).astype(np.float)*2\n if hm.shape == np.array(img).astype(np.float).shape:\n out = (hm + np.array(img).astype(np.float)) / 3\n out = Image.fromarray((out / np.max(out) * 255).astype(np.uint8), 'RGB')\n return hm, out\n\n\ndef draw_heatmap_array(img, hm):\n hm = plt.cm.hot(hm)[:, :, :3]\n hm = np.array(Image.fromarray((hm*255).astype(np.uint8), 'RGB').resize((img.shape[1], img.shape[0]), Image.BICUBIC)).astype(np.float)*2\n if hm.shape == np.array(img).astype(np.float).shape:\n out = (hm + np.array(img).astype(np.float)) / 3\n out = (out / np.max(out) * 255).astype(np.uint8)\n return hm, out\n\n\ndef cls200_vote(y_200, k_cluster):\n topk_subcls = np.argsort(y_200[0].detach().cpu().numpy())[-10:][::-1]\n topk_cls = np.array(topk_subcls/k_cluster, dtype=np.uint8)\n topk_vote = np.unique(topk_cls, return_counts=True)\n\n p_cls_sum = []\n for p_cls in topk_vote[0]:\n subcls_sum = []\n for prob in np.where(topk_cls == p_cls)[0]:\n subcls_sum.append(y_200[0][topk_subcls[prob]].item())\n p_cls_sum.append(sum(subcls_sum))\n\n cls200_pred_vote = topk_vote[0][np.where(np.array(p_cls_sum) >= 0.5)[0]]\n return cls200_pred_vote\n\n\ndef cls200_sum(y_200, k_cluster):\n cls20_prob_sum_list = []\n for rou in range(20):\n subclass_prob_sum = sum(y_200[0][rou*k_cluster:rou*k_cluster+k_cluster].detach().cpu().numpy())\n cls20_prob_sum_list.append(subclass_prob_sum/10)\n\n cls200_pred_max = np.where(np.array(cls20_prob_sum_list)>0.05)[0]\n return cls200_pred_max\n\n\ndef cam_subcls_norm(cam, cls20_gt, k_cluster):\n for gt in cls20_gt:\n subcls_cam = cam[gt*k_cluster:gt*k_cluster+k_cluster]\n\n norm_cam = subcls_cam / (np.max(subcls_cam, keepdims=True) + 1e-5)\n\n subcls_norm_cam = np.asarray(norm_cam)\n cam[gt*k_cluster:gt*k_cluster+k_cluster] = subcls_norm_cam\n return cam\n\n\ndef compute_acc(pred_labels, gt_labels):\n pred_correct_count = 0\n pred_correct_list = []\n for pred_label in pred_labels:\n if pred_label in gt_labels:\n pred_correct_count += 1\n union = len(gt_labels) + len(pred_labels) - pred_correct_count\n acc = round(pred_correct_count/union, 4)\n return(acc)\n\n\ndef compute_iou(gt_labels, cam_np, gt_np, th, class_iou_dict):\n iou_list = []\n for label in gt_labels:\n cam = cam_np[label]\n gt = gt_np[label]\n\n gt_target_class = label + 1\n\n gt_y, gt_x = np.where(gt == gt_target_class)\n gt_pixel_nb = gt_y.shape[0] # object\n\n correct_pixel_nb = 0\n\n cam_y, cam_x = np.where(cam >= th)\n high_response_pixel_nb = cam_y.shape[0] # detected\n\n for pixel in range(gt_y.shape[0]):\n if cam[gt_y[pixel]][gt_x[pixel]] >= th:\n correct_pixel_nb += 1 # intersection\n else:\n continue\n\n union = gt_pixel_nb + high_response_pixel_nb - correct_pixel_nb\n\n if high_response_pixel_nb != 0:\n iou = round(correct_pixel_nb/union, 4)\n else:\n iou = 0.\n iou_list.append(iou)\n if high_response_pixel_nb != 0:\n precision = round(correct_pixel_nb/high_response_pixel_nb, 4)\n else:\n precision = 0.\n recall = round(correct_pixel_nb/gt_pixel_nb, 4)\n class_iou_dict[label].append(iou)\n print(label, iou)\n return class_iou_dict, iou_list\n\n\n\n\ndef compute_merge_iou(gt_labels, cam_nor, cam_b4_nor, gt_np, th, k, class_iou_dict):\n merged_cam_list = []\n for label in gt_labels:\n\n cam_b4_nor_ = cam_b4_nor[label*k:label*k+k] # (10, 366, 500)\n cam_b4_sum = np.sum(cam_b4_nor_, axis=0) # (366, 500)\n merge_cam = cam_b4_sum / np.amax(cam_b4_sum) # (366, 500) np.max(merge_cam)=1.0\n\n\n merged_cam_list.append(merge_cam)\n\n\n gt = gt_np[label]\n gt_target_class = label + 1\n\n gt_y, gt_x = np.where(gt == gt_target_class)\n gt_pixel_nb = gt_y.shape[0] # object\n\n correct_pixel_nb = 0\n\n cam_y, cam_x = np.where(merge_cam >= th)\n high_response_pixel_nb = cam_y.shape[0] # detected\n\n for pixel in range(gt_y.shape[0]):\n if merge_cam[gt_y[pixel]][gt_x[pixel]] >= th:\n correct_pixel_nb += 1 # intersection\n else:\n continue\n\n union = gt_pixel_nb + high_response_pixel_nb - correct_pixel_nb\n\n if high_response_pixel_nb != 0:\n iou = round(correct_pixel_nb/union, 4)\n else:\n iou = 0.\n if high_response_pixel_nb != 0:\n precision = round(correct_pixel_nb/high_response_pixel_nb, 4)\n else:\n precision = 0.\n recall = round(correct_pixel_nb/gt_pixel_nb, 4)\n class_iou_dict[label].append(iou)\n return class_iou_dict, merged_cam_list\n\n\n\ndef compute_merge_11_iou(gt_labels, cam_20, cam_200, gt_np, th, k, class_all_iou_dict):\n merged_cam_list = []\n for label in gt_labels:\n parcls_cam = np.expand_dims(cam_20[label], axis=0)\n subcls_cam = cam_200[label*k:label*k+k]\n\n merge_11_cam = np.concatenate((subcls_cam, parcls_cam), axis=0)\n merge_11_cam = np.amax(merge_11_cam, axis=0)\n merge_cam = merge_11_cam / np.amax(merge_11_cam)\n\n merged_cam_list.append(merge_cam)\n\n gt = gt_np[label]\n gt_target_class = label + 1\n\n gt_y, gt_x = np.where(gt == gt_target_class)\n gt_pixel_nb = gt_y.shape[0]\n\n correct_pixel_nb = 0\n\n cam_y, cam_x = np.where(merge_cam >= th)\n high_response_pixel_nb = cam_y.shape[0]\n\n for pixel in range(gt_y.shape[0]):\n if merge_cam[gt_y[pixel]][gt_x[pixel]] >= th:\n correct_pixel_nb += 1\n else:\n continue\n\n union = gt_pixel_nb + high_response_pixel_nb - correct_pixel_nb\n\n if high_response_pixel_nb != 0:\n iou = round(correct_pixel_nb/union, 4)\n else:\n iou = 0.\n if high_response_pixel_nb != 0:\n precision = round(correct_pixel_nb/high_response_pixel_nb, 4)\n else:\n precision = 0.\n recall = round(correct_pixel_nb/gt_pixel_nb, 4)\n class_all_iou_dict[label].append(iou)\n\n return class_all_iou_dict, merged_cam_list\n\n\n\ndef compute_ub_iou(gt_labels, cam_np, gt_np, th, k, class_iou_dict):\n iou_list = []\n all_subclass_iou_list = []\n for l_num, label in enumerate(gt_labels):\n subclass_iou_list = []\n cam = cam_np[label*k:label*k+k]\n for num, one in enumerate(cam):\n merge_cam = one\n gt = gt_np[label]\n\n gt_target_class = label + 1\n\n gt_y, gt_x = np.where(gt == gt_target_class)\n gt_pixel_nb = gt_y.shape[0]\n\n correct_pixel_nb = 0\n\n cam_y, cam_x = np.where(merge_cam >= th)\n high_response_pixel_nb = cam_y.shape[0]\n\n for pixel in range(gt_y.shape[0]):\n if merge_cam[gt_y[pixel]][gt_x[pixel]] >= th:\n correct_pixel_nb += 1\n else:\n continue\n\n union = gt_pixel_nb + high_response_pixel_nb - correct_pixel_nb\n\n\n if high_response_pixel_nb != 0:\n iou = round(correct_pixel_nb/union, 4)\n else:\n iou = 0.\n subclass_iou_list.append(iou)\n\n if high_response_pixel_nb != 0:\n precision = round(correct_pixel_nb/high_response_pixel_nb, 4)\n else:\n precision = 0.\n recall = round(correct_pixel_nb/gt_pixel_nb, 4)\n\n print(label, 'subcls_iou_list: {}'.format(subclass_iou_list))\n max_iou = max(subclass_iou_list)\n print(max_iou, subclass_iou_list.index(max(subclass_iou_list)))\n class_iou_dict[label].append(max_iou)\n iou_list.append(max_iou)\n\n all_subclass_iou_list.append(subclass_iou_list)\n return class_iou_dict, iou_list, all_subclass_iou_list\n\n\n\n\ndef count_maxiou_prob(y_200, cls20_gt, all_subclass_iou_list, class_20_iou_list, k_cluster, subclass_top_iou_list, class_200_ub_iou_list, class_ub_iou_dict, img_name):\n for i, gt in enumerate(cls20_gt):\n subclass_prob = y_200[0][gt*k_cluster:gt*k_cluster+k_cluster].detach().cpu().numpy()\n print('pred_score: {}'.format(subclass_prob))\n\n ten_subclass_iou_list = all_subclass_iou_list[i]\n ten_subclass_iou_list.append(class_20_iou_list[i])\n\n subclass_max_idx = ten_subclass_iou_list.index(max(ten_subclass_iou_list))\n pred_subclass = gt*k_cluster+subclass_max_idx\n\n if subclass_max_idx != 10:\n sort_subclass_prob_idx = np.argsort(subclass_prob)[::-1]\n top_k_best_iou = np.where(sort_subclass_prob_idx == subclass_max_idx)[0][0]\n subclass_top_iou_list[top_k_best_iou] += 1\n else:\n top_k_best_iou = 10\n subclass_top_iou_list[top_k_best_iou] += 1\n\n\n ub_iou = max(class_20_iou_list[i], class_200_ub_iou_list[i])\n class_ub_iou_dict[cls20_gt[i]].append(ub_iou)\n print(subclass_top_iou_list)\n\n line = '{},{},{},{},{}\\n'.format(img_name, pred_subclass, top_k_best_iou, ub_iou, class_20_iou_list)\n\n return class_ub_iou_dict\n\n\n\ndef merge_topk_iou(y_200, gt_labels, all_subclass_iou_list, cam_np, gt_np, th, k, class_iou_dict):\n merged_cam_list = []\n for num, label in enumerate(gt_labels):\n subclass_prob = y_200[0][label*k:label*k+k].detach().cpu().numpy()\n subclass_iou_list = all_subclass_iou_list[num][:-1]\n\n cam = cam_np[label*k:label*k+k]\n sort_subcls_prob_idx = np.argsort(subclass_prob)[::-1]\n\n # print(subclass_prob)\n # print(subclass_iou_list)\n # print(sort_subcls_prob_idx)\n\n top_k_list = [0, 1, 2, 4, 9]\n top_k_iou_list = []\n for top in top_k_list:\n merge_k = np.zeros((top+1, cam.shape[1], cam.shape[2]))\n target_subcls_cam_idx = sort_subcls_prob_idx[:top+1]\n print(top, merge_k.shape, target_subcls_cam_idx)\n\n for i, idx in enumerate(target_subcls_cam_idx):\n merge_k[i] = cam[idx]\n\n ## norm -> max per pixel\n merge_cam = np.amax(merge_k, axis=0)\n\n # ## sum -> norm\n # merge_cam = np.sum(cam, axis=0) / np.amax(cam)\n\n merged_cam_list.append(merge_cam)\n\n\n gt = gt_np[label]\n gt_target_class = label + 1\n\n gt_y, gt_x = np.where(gt == gt_target_class)\n gt_pixel_nb = gt_y.shape[0] # object\n\n correct_pixel_nb = 0\n\n cam_y, cam_x = np.where(merge_cam >= th)\n high_response_pixel_nb = cam_y.shape[0] # detected\n\n for pixel in range(gt_y.shape[0]):\n if merge_cam[gt_y[pixel]][gt_x[pixel]] >= th:\n correct_pixel_nb += 1 # intersection\n else:\n continue\n\n union = gt_pixel_nb + high_response_pixel_nb - correct_pixel_nb\n\n if high_response_pixel_nb != 0:\n iou = round(correct_pixel_nb/union, 4)\n else:\n iou = 0.\n if high_response_pixel_nb != 0:\n precision = round(correct_pixel_nb/high_response_pixel_nb, 4)\n else:\n precision = 0.\n recall = round(correct_pixel_nb/gt_pixel_nb, 4)\n\n top_k_iou_list.append(iou)\n\n return class_iou_dict, merged_cam_list\n\n\n\ndef vrf_iou_w_distance(cls20_gt):\n cls20_w = np.load('./kmeans_subclass/c20_k10/3rd_round/weight_np/R3_cls20_w.npy', allow_pickle=True) # (20, 4096)\n cls200_w = np.load('./kmeans_subclass/c20_k10/3rd_round/weight_np/R3_cls200_w.npy', allow_pickle=True) # (200, 4096)\n\n bike_w = cls20_w[cls20_gt[0]]\n sub_human_w = cls200_w[cls20_gt[1]*10:cls20_gt[1]*10+10]\n\n sub_w_dis_list = []\n for num, sub in enumerate(sub_human_w):\n dist = np.linalg.norm(bike_w-sub)\n sub_w_dis_list.append(dist)\n print('dist_list: {}'.format(sub_w_dis_list))\n print(sub_w_dis_list.index(min(sub_w_dis_list)))\n\n\ndef find_200_pseudo_label(image_name, round_nb):\n filename_list_path = './kmeans_subclass/c20_k10/{}_round/train/{}_train_filename_list.txt'.format(round_nb, round_nb)\n label_20_npy = np.load( './kmeans_subclass/c20_k10/{}_round/train/{}_train_label_20.npy'.format(round_nb, round_nb), allow_pickle=True)\n label_200_npy = np.load('./kmeans_subclass/c20_k10/{}_round/train/{}_train_label_200.npy'.format(round_nb, round_nb), allow_pickle=True)\n\n with open(filename_list_path, 'r') as f:\n filename_list = f.read().split('\\n')\n f.close()\n\n image_idx = filename_list.index(image_name)\n label_20 = label_20_npy[image_idx]\n label_200 = label_200_npy[image_idx]\n\n\n return label_20, label_200\n\n\ndef cam_npy_to_cam_dict(cam_np, label):\n cam_dict = {}\n idxs = np.where(label==1)[0]\n\n for idx in idxs:\n cam_dict[idx] = cam_np[idx]\n\n return cam_dict\n\n\ndef response_to_label(cam_npy):\n seg_map = cam_npy.transpose(1,2,0)\n seg_map = np.asarray(np.argmax(seg_map, axis=2), dtype=np.int)\n\n return seg_map\n\n\ndef get_accum_from_dict(par_cls, clust_dict):\n accum = 0\n for m in range(par_cls):\n accum += clust_dict[m]\n return accum\n\n\ndef cls200_cam_norm(cam_list_200, k_cluster):\n cam_200 = np.sum(cam_list_200, axis=0)\n norm_cam_200 = np.zeros((cam_200.shape[0], cam_200.shape[1], cam_200.shape[2]))\n\n for i in range(20):\n subcls_cam = cam_200[i*k_cluster:i*k_cluster+k_cluster]\n\n norm_cam = subcls_cam / (np.max(subcls_cam, keepdims=True) + 1e-5)\n\n subcls_norm_cam = np.asarray(norm_cam)\n norm_cam_200[i*k_cluster:i*k_cluster+k_cluster] = subcls_norm_cam\n return norm_cam_200\n\n\n\ndef cls200_cam_norm_dynamicK(cam_list_200, clust_dict):\n\n cam_200 = np.sum(cam_list_200, axis=0)\n norm_cam_200 = np.zeros((cam_200.shape[0], cam_200.shape[1], cam_200.shape[2]))\n for i in range(20):\n accum = get_accum_from_dict(i, clust_dict)\n\n subcls_cam = cam_200[accum:accum+clust_dict[i]]\n\n norm_cam = subcls_cam / (np.max(subcls_cam, keepdims=True) + 1e-5)\n\n subcls_norm_cam = np.asarray(norm_cam)\n norm_cam_200[accum:accum+clust_dict[i]] = subcls_norm_cam\n return norm_cam_200\n\n\n\ndef dict2npy(cam_dict, gt_label, th):\n gt_cat = np.where(gt_label==1)[0]\n\n orig_img_size = cam_dict[gt_cat[0]].shape\n\n bg_score = [np.ones_like(cam_dict[gt_cat[0]])*th]\n cam_npy = np.zeros((20, orig_img_size[0], orig_img_size[1]))\n\n for gt in gt_cat:\n cam_npy[gt] = cam_dict[gt]\n\n cam_npy = np.concatenate((bg_score, cam_npy), axis=0)\n return cam_npy\n\n\n\ndef merge_200_cam_dict(cam_dict_200, gt_label, th, k):\n gt_cat = np.where(gt_label==1)[0]\n\n orig_img_size = cam_dict_200[gt_cat[0]*k].shape\n\n cam_npy = np.zeros((20, orig_img_size[0], orig_img_size[1]))\n sub_cam_npy = np.zeros((k, orig_img_size[0], orig_img_size[1]))\n\n for gt in gt_cat:\n for i in range(k):\n sub_cam_npy[i] = cam_dict_200[gt*k+i]\n sub_cam_max_npy = np.amax(sub_cam_npy, axis=0)\n cam_npy[gt] = sub_cam_max_npy\n return cam_npy\n\n\n\ndef cam_npy_to_label_map(cam_npy):\n seg_map = cam_npy.transpose(1,2,0)\n seg_map = np.asarray(np.argmax(seg_map, axis=2), dtype=np.int)\n return seg_map\n\n\n\ndef cam_npy_to_cam_dict(cam_npy, label):\n cam_dict = {}\n for i in range(len(label)):\n if label[i] > 1e-5:\n cam_dict[i] = cam_npy[i]\n return cam_dict\n\n\ndef cls200_cam_to_cls20_entropy(no_norm_cam_200, k_cluster, norm_cam, save_path, img_name, orig_img, gt_label, save_entropy_heatmap):\n gt_cat = np.where(gt_label==1)[0]\n\n cam_200_entropy_path = '{}/entropy/cls_200/{}'.format(save_path, img_name)\n if save_entropy_heatmap == 1:\n if os.path.isdir(cam_200_entropy_path):\n shutil.rmtree(cam_200_entropy_path)\n os.mkdir(cam_200_entropy_path)\n\n entropy_npy = np.zeros((norm_cam.shape[0], norm_cam.shape[1], norm_cam.shape[2]))\n\n\n for i in range(20):\n sub_cams = no_norm_cam_200[i*k_cluster:i*k_cluster+k_cluster]\n\n sub_cams_sum = np.sum(sub_cams, axis=0)\n\n sub_cams_sum_10 = sub_cams_sum[np.newaxis, :]\n sub_cams_sum_10 = np.repeat(sub_cams_sum_10, k_cluster, axis=0)\n prob = sub_cams/(sub_cams_sum_10 + 1e-5)\n\n prob_log = np.log(prob + 1e-5) / np.log(k_cluster)\n\n entropy_norm = -(np.sum(prob*prob_log, axis=0)) # entropy normalization\n\n entropy_norm[entropy_norm<0]=0\n entropy_npy[i] = entropy_norm\n\n if save_entropy_heatmap == 1:\n if i in gt_cat:\n hm, heatmap = draw_heatmap(orig_img, entropy_norm)\n imageio.imsave('{}/entropy/cls_200/{}/{}_{}.png'.format(save_path, img_name, img_name, i), heatmap)\n\n return entropy_npy\n\n\ndef create_folder(inference_dir_path):\n\n if os.path.exists(inference_dir_path) == True:\n shutil.rmtree(inference_dir_path)\n\n os.mkdir(inference_dir_path)\n os.mkdir(os.path.join(inference_dir_path + '/heatmap'))\n os.mkdir(os.path.join(inference_dir_path + '/heatmap/cls_20'))\n os.mkdir(os.path.join(inference_dir_path + '/heatmap/cls_200'))\n os.mkdir(os.path.join(inference_dir_path + '/output_CAM_npy'))\n os.mkdir(os.path.join(inference_dir_path + '/output_CAM_npy/cls_20'))\n os.mkdir(os.path.join(inference_dir_path + '/output_CAM_npy/cls_200'))\n os.mkdir(os.path.join(inference_dir_path + '/IOU'))\n os.mkdir(os.path.join(inference_dir_path + '/crf'))\n os.mkdir(os.path.join(inference_dir_path + '/crf/out_la_crf'))\n os.mkdir(os.path.join(inference_dir_path + '/crf/out_ha_crf'))\n\n\n\n\ndef draw_single_heatmap(norm_cam, gt_label, orig_img, save_path, img_name):\n gt_cat = np.where(gt_label==1)[0]\n heatmap_list = []\n mask_list = []\n for i, gt in enumerate(gt_cat):\n hm, heatmap = draw_heatmap_array(orig_img, norm_cam[gt])\n cam_viz_path = os.path.join(save_path,'heatmap/cls_20', img_name + '_{}.png'.format(gt))\n imageio.imsave(cam_viz_path, heatmap)\n\n norm_cam_gt = norm_cam[gt]\n norm_cam_gt[norm_cam_gt<=0.15]=0\n norm_cam_gt[norm_cam_gt>0.15]=255\n\n heatmap = np.transpose(heatmap, (2, 1, 0))\n heatmap_list.append(heatmap)\n mask_list.append(norm_cam_gt)\n\n return heatmap_list, mask_list\n\n\n\n\ndef draw_heatmap_cls200(norm_cam, gt_label, orig_img):\n gt_cat = np.where(gt_label==1)[0]\n heatmap_list = []\n for i, gt in enumerate(gt_cat):\n heatmap_cat_list = []\n for x in range(10):\n hm, heatmap = draw_heatmap_array(orig_img, norm_cam[gt*10+x])\n heatmap = np.transpose(heatmap, (2, 1, 0))\n heatmap_cat_list.append(heatmap)\n heatmap_list.append(heatmap_cat_list)\n\n return heatmap_list\n\n\ndef draw_heatmap_cls200_merge(norm_cam, gt_label, orig_img, img_name):\n gt_cat = np.where(gt_label==1)[0]\n heatmap_list = []\n for i, gt in enumerate(gt_cat):\n hm, heatmap = draw_heatmap_array(orig_img, norm_cam[gt])\n imageio.imsave('/home/julia/julia_data/wsss/best/heatmap/cls_200/merge_{}.png'.format(img_name), heatmap)\n heatmap = np.transpose(heatmap, (2, 1, 0))\n heatmap_list.append(heatmap)\n\n return heatmap_list\n\n\ndef draw_heatmap_cls200_entropy(norm_cam, gt_label, orig_img):\n gt_cat = np.where(gt_label==1)[0]\n heatmap_list = []\n mask_list = []\n for i, gt in enumerate(gt_cat):\n hm, heatmap = draw_heatmap_array(orig_img, norm_cam[gt])\n\n norm_cam_gt = norm_cam[gt]\n norm_cam_gt[norm_cam_gt<=0.6]=0\n norm_cam_gt[norm_cam_gt>0.6]=255\n\n heatmap = np.transpose(heatmap, (2, 1, 0))\n heatmap_list.append(heatmap)\n mask_list.append(norm_cam_gt)\n\n return heatmap_list, mask_list\n\n\ndef combine_four_images(files, img_name, gt, save_path):\n result = Image.new(\"RGB\", (1200, 800))\n\n for index, file in enumerate(files):\n img = file\n img.thumbnail((400, 400), Image.ANTIALIAS)\n x = index // 2 * 400\n y = index % 2 * 400\n w , h = img.size\n result.paste(img, (x, y, x + w, y + h))\n result.save(os.path.expanduser('./{}/combine_maps/{}_{}.jpg'.format(save_path, img_name, gt)))\n\n\ndef save_combine_response_maps(cam_20_heatmap, cam_200_merge_heatmap, cam_200_entropy_heatmap, cam_20_map, cam_200_entropy_map, orig_img, gt_label, img_name, save_path):\n gt_cat = np.where(gt_label==1)[0]\n orig_img_out = Image.fromarray(orig_img.astype(np.uint8), 'RGB')\n print(len(cam_20_heatmap), len(cam_200_merge_heatmap), len(cam_200_entropy_heatmap))\n\n for num, gt in enumerate(gt_cat):\n cls20_out = Image.fromarray(np.transpose(cam_20_heatmap[num], (2, 1, 0)).astype(np.uint8), 'RGB')\n cls200_merge_out = Image.fromarray(np.transpose(cam_200_merge_heatmap[num], (2, 1, 0)).astype(np.uint8), 'RGB')\n cls200_entropy_out = Image.fromarray(np.transpose(cam_200_entropy_heatmap[num], (2, 1, 0)).astype(np.uint8), 'RGB')\n cam_20_map_out = Image.fromarray(cam_20_map[num].astype(np.uint8))\n cam_200_entropy_map_out = Image.fromarray(cam_200_entropy_map[num].astype(np.uint8))\n\n image_list = [orig_img_out, cls200_merge_out, cls20_out, cls200_entropy_out, cam_20_map_out, cam_200_entropy_map_out]\n combine_four_images(image_list, img_name, gt, save_path)\n" ]
[ [ "numpy.ones_like", "numpy.load", "numpy.where", "numpy.concatenate", "numpy.max", "numpy.linalg.norm", "numpy.log", "numpy.argmax", "numpy.transpose", "numpy.expand_dims", "matplotlib.pyplot.cm.hot", "numpy.array", "numpy.zeros", "numpy.amax", "numpy.argsort", "numpy.asarray", "numpy.sum", "numpy.repeat", "numpy.unique" ] ]
akjayant/coding_reinforcement_learning
[ "5882b4e55907a517915e3df698eebb80252c732d" ]
[ "Policy Gradients/Reinforce_continous_action.py" ]
[ "#------------------THIS IS VANILLA REINFORCE ALGORITHM WITH NO BASELINE-----------------------------------------------\n\nimport gym\nimport torch\nimport torch as T\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\n#from gym import wrappers\nfrom torch.distributions import Normal\nfrom torch.utils.tensorboard import SummaryWriter\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.lines import Line2D\nimport pandas as pd\nimport safety_gym\n\nfrom torch.distributions import MultivariateNormal\n\n\nclass PolicyNetwork(nn.Module):\n def __init__(self,num_states, num_actions, hidden_size):\n super(PolicyNetwork,self).__init__()\n self.num_states = num_states\n self.num_actions = num_actions\n\n #Policy Network\n self.actor = nn.Sequential(\n nn.Linear(num_states,hidden_size),\n nn.ReLU(),\n nn.Linear(hidden_size,hidden_size),\n nn.ReLU(),\n nn.Linear(hidden_size,2*num_actions)\n )\n\n\n def forward(self,state):\n nn_out = self.actor(state).view(-1,4)\n\n\n mu_1 = T.tanh(nn_out[0][0]).view(-1,1)\n var_1 = F.softplus(nn_out[0][1]).view(-1,1)\n\n\n mu_2 = T.tanh(nn_out[0][2]).view(-1,1)\n var_2 = F.softplus(nn_out[0][3]).view(-1,1)\n #print(mu_1,mu_2)\n #print(var_1,var_2)\n mu = T.cat([mu_1,mu_2]).to(device)\n var = T.cat([var_1,var_2]).to(device)\n\n mu = mu.view(-1,1,2)\n var = var.view(-1,1,2)\n #var = T.ones_like(var)\n #var = var*0.1\n dist = MultivariateNormal(mu,T.diag_embed(var))\n\n return dist\n\n\n\n\ndef update_gradients(gamma,ep_rewards,ep_logits,ep_entropies):\n mc_return = []\n p_loss = []\n loss=0\n G = 0\n for r in reversed(range(len(ep_rewards))):\n G = ep_rewards[r] + gamma*G\n mc_return.insert(0,G)\n mc_return = torch.tensor(mc_return)\n advantage_returns = (mc_return - mc_return.mean())/mc_return.std()\n #print((mc_return))\n for lp, re in zip(ep_logits, advantage_returns):\n p_loss.append( - lp * re)\n\n optim_policy.zero_grad()\n #trying entropy regularization\n #print(ep_entropies)\n loss = torch.stack(p_loss).sum() #+ 0.0001*ep_entropies\n loss.backward()\n #plot_grad_flow_v2(p_net.named_parameters())\n optim_policy.step()\n\n\n\ndef train(env):\n gamma = 0.99\n max_episodes = 1400\n max_steps = 1000\n running_reward = 0\n running_cost = 0\n plot_rewards = []\n plot_costs = []\n for ep in range(max_episodes):\n ep_rewards =[]\n ep_logits = []\n ep_entropies = []\n ep_costs = []\n current_reward = 0\n current_cost = 0\n state = env.reset()\n\n for step in range(max_steps):\n #print(type(state))\n state = torch.from_numpy(state).float().unsqueeze(0).to(device)\n\n dist_obj = p_net.forward(state)\n #print(mu_out,var_out)\n #Sample next action according normal distribution we trying to fit\n\n sampled_action_tensor = dist_obj.sample()\n sampled_action = np.clip(sampled_action_tensor.cpu().detach().numpy(),-1,1)\n #print(sampled_action,\"/n\")\n next_state,reward,done,info= env.step(sampled_action)\n log_prob = dist_obj.log_prob(sampled_action_tensor)\n #print(log_prob)\n entropy = dist_obj.entropy()\n ep_rewards.append(reward)\n ep_logits.append(log_prob)\n ep_entropies.append(entropy)\n current_reward += reward\n current_cost += info['cost']\n state = next_state\n running_reward = 0.05 * current_reward + (1 - 0.05) * running_reward\n running_cost = 0.05 * current_cost + (1 - 0.05) * running_cost\n\n if done:\n plot_rewards.append(current_reward)\n plot_costs.append(current_cost)\n break\n if ep%10==0:\n print(ep)\n print(\"Current reward = \",current_reward,\"Running reward = \",running_reward,\"Current cost = \",current_cost,\"Running cost = \",running_cost)\n #Update the parameters\n ep_entropies = torch.cat(ep_entropies)\n update_gradients(gamma,ep_rewards,ep_logits,ep_entropies.sum())\n writer.add_scalar(\"Reward \",current_reward)\n writer.add_scalar(\"Cost \",current_cost)\n #if running_reward >env.spec.reward_threshold:\n # print(\"Solved in \",ep)\n return plot_rewards, dist_obj, plot_costs\n\n\n\n #device = set_device()\nenv = gym.make('Safexp-PointGoal1-v0')\ndevice = T.device('cuda:0' if T.cuda.is_available() else 'cpu')\nprint(device)\np_net = PolicyNetwork(60,2,256)\np_net.to(device)\noptim_policy= optim.Adam(p_net.parameters(), lr=3e-4)\nwriter = SummaryWriter()\np_net.train()\n\n\nplot_rewards, dist_obj, plot_costs = train(env)\nwriter.flush()\nenv.close()\n\ncost_limit = np.array([25 for i in range(1400)])\n\n\nfig, axs = plt.subplots(2)\n# axs[0].plot(x, running_avg_return)\n# axs[1].plot(x, running_avg_cost)\n# axs[1].plot(x,limit_cost)\n# axs[0].set_yticks(np.arange(0,26,5))\n# axs[1].set_yticks(np.arange(0,161,20))\n# plt.savefig(figure_file)\n\n#axs[0].plot(np.arange(0,1400),plot_rewards)\n#axs[1].plot(np.arange(0,1400),plot_costs)\naxs[0].plot(np.arange(0,1400),pd.Series(plot_rewards).rolling(100).mean())\naxs[1].plot(np.arange(0,1400),pd.Series(plot_costs).rolling(100).mean())\naxs[1].plot(np.arange(0,1400),cost_limit)\naxs[0].set_yticks(np.arange(0,26,5))\naxs[1].set_yticks(np.arange(0,161,20))\nplt.savefig('vpg_pointgoal1.png')\n" ]
[ [ "torch.nn.Linear", "torch.diag_embed", "torch.cat", "torch.stack", "torch.nn.functional.softplus", "matplotlib.pyplot.savefig", "matplotlib.pyplot.subplots", "torch.from_numpy", "torch.nn.ReLU", "torch.cuda.is_available", "numpy.arange", "torch.tensor", "pandas.Series", "torch.tanh", "torch.utils.tensorboard.SummaryWriter" ] ]
awb-carleton/pattern-analysis
[ "532066398f2d102031aaa86b9a7c739ee16ceb9c" ]
[ "foldit/variation_analysis.py" ]
[ "from pattern_extraction import *\nimport argparse\nimport numpy as np\nimport pandas as pd\nimport logging\nimport json\nimport sys\nimport os\nimport string\nimport re\nfrom typing import Dict, Tuple, List\nfrom itertools import combinations, groupby, chain\nfrom util import category_lookup\nfrom plot_util import make_boxplot\nfrom scipy import stats\nimport matplotlib\nmatplotlib.use(\"Agg\")\nimport matplotlib.pyplot as plt\n\nwith open(\"data/user_ubiq_v1.csv\") as fp:\n ubiqs = [{k: float(v) if not k.endswith(\"id\") else v for k, v in r.items()}\n for r in csv.DictReader(fp)]\nubiq_lookup = {uid: sorted(us, key=lambda x: x['pid']) for uid, us in groupby(sorted(ubiqs, key=lambda u: u['uid']), lambda u: u['uid'])}\n\nwith open(\"data/user_metadata_v4.csv\") as fp:\n user_metas = {(r['uid'], r['pid']): r for r in csv.DictReader(fp)}\n for v in user_metas.values():\n v['time'] = int(v['time'])\n v['relevant_time'] = int(float(v['relevant_time']))\n v['best_energy_time'] = int(v['best_energy_time'])\n v['action_count_all'] = int(v['action_count_all'])\n v['action_count_relevant'] = int(v['action_count_relevant'])\n v['action_count_best'] = int(v['action_count_best'])\n v['best_energy'] = float(v['best_energy'])\n v['perf'] = float(v['perf'])\n v['solo_perf'] = float(v['solo_perf']) if v['solo_perf'] != \"\" else np.nan\nuser_meta_lookup = {uid: sorted(metas, key=lambda x: x['pid']) for uid, metas in groupby(sorted(user_metas.values(), key=lambda m: m['uid']),\n lambda m: m['uid'])}\n\nwith open(\"data/puz_metadata_v4.csv\") as fp:\n puz_infos = {r['pid']: {'start': int(r['start']),\n 'end': int(r['end']),\n 'baseline': float(r['baseline']),\n 'best': float(r['best']),\n 'best_solo': float(r['best_solo'])\n } for r in csv.DictReader(fp)}\n\nwith open(\"data/user_patterns_v1.csv\") as fp:\n reader = csv.DictReader(fp)\n pattern_count_lookup = {}\n for r in reader:\n pattern_count_lookup[(r['uid'], r['pid'])] = {pt: float(c) for pt, c in r.items() if pt != 'uid' and pt != 'pid'}\nuid_to_pattern_fracs = {uid: {pid: {pt: c / sum(pattern_count_lookup[(uid, pid)].values()) for pt, c in pattern_count_lookup[(uid, pid)].items()}\n for uid, pid in tags if sum(pattern_count_lookup[(uid, pid)].values()) > 0}\n for uid, tags in groupby(sorted(pattern_count_lookup.keys()), lambda x: x[0]) if 'evol' not in uid}\n\nwith open(\"data/puzzle_categories_v4.csv\") as fp:\n puz_cat = {r['nid']: r['categories'].split(',') for r in csv.DictReader(fp)}\n\nwith open(\"data/puzzle_labels_v1.json\") as fp:\n puz_labels = {x['pid']: x for x in json.load(fp)}\n\n\n# def make_markers(uid):\n# markers = {\"r.\": [re.match(r\"\\d\\d\\d\\d: Revisiting\", puz_labels[ubiq['pid']][\"title\"]) != None for ubiq in ubiq_lookup[uid]],\n# \"b.\": [re.match(r\"\\d\\d\\d\\d: Unsolved\", puz_labels[ubiq['pid']][\"title\"]) != None and puz_labels[ubiq['pid']][\"title\"].count(\":\") == 1 for ubiq in ubiq_lookup[uid]]}\n# markers[\"g.\"] = [not a and not b for a, b in zip(markers[\"r.\"], markers[\"b.\"])]\n# return markers\n\n\n# target_uids = ['716281', '236506', '476462', '447652', '306768', '513977', '492685', '482875', '455069', '126983', '71954', '398373']\n# for uid in target_uids:\n# make_boxplot([[ubiq[a + \"_ubiq_relevant\"] for ubiq in ubiq_lookup[uid]] for a in get_action_labels()],\n# [a for a in get_action_labels()], \"ubiq\", \"variation_viz/uid_{}.png\".format(uid), markers=make_markers(uid))\n\ndenovo_pids = [pid for pid in puz_labels if re.match(r\"\\d\\d\\d\\d: Unsolved\", puz_labels[pid][\"title\"]) != None and puz_labels[pid][\"title\"].count(\":\") == 1]\nrevisit_pids = [pid for pid in puz_labels if re.match(r\"\\d\\d\\d\\d: Revisiting\", puz_labels[pid][\"title\"]) != None]\ntarget_pids = denovo_pids + revisit_pids\n\ntarget_pts = [\"1A\", \"1D\", \"1E\", \"1F\", \"1G\", \"1H\", \"1I\", \"1J\", \"2A\", \"2C\", \"2D\", \"2E\", \"2F\", \"2G\",\n \"2H\", \"2I\", \"2J\", \"3A\", \"3C\", \"3D\", \"3E\", \"3F\", \"3G\", \"3H\", \"3I\", \"3J\", \"4\"]\n\nexperience_cohorts = {\"exp{}\".format(thresh): [uid for uid, pfs in uid_to_pattern_fracs.items() if len([pid for pid in pfs if pid in target_pids]) > thresh] for thresh in [5, 10, 25, 50]}\n# perf_cohorts = {\"perf{}\".format(thresh): [uid for uid, pfs in uid_to_pattern_fracs.items() if\n# len([pid for pid in pfs if pid in target_pids]) > 5\n# and np.median([x['perf'] for x in user_meta_lookup[uid] if x['pid'] in target_pids]) > thresh]\n# for thresh in [0.8, 0.9, 0.95]}\n\nfor label, uids in experience_cohorts.items(): #chain(experience_cohorts.items(), perf_cohorts.items()):\n print(\"{} (n = {})\".format(label, len(uids)))\n print(\"correlations of IQR with perf\")\n for a in get_action_labels():\n print(a, stats.spearmanr([stats.iqr([u[a + \"_ubiq_relevant\"] for u in us if u['pid'] in target_pids]) for uid, us in ubiq_lookup.items() if uid in uids],\n [np.median([x['perf'] for x in user_meta_lookup[uid] if x['pid'] in target_pids]) for uid, us in ubiq_lookup.items() if uid in uids],\n nan_policy=\"omit\"))\n print()\n for pt in target_pts:\n pt_uids = [uid for uid in uids if any(pf[pt] > 0 for pid, pf in uid_to_pattern_fracs[uid].items())]\n print(pt, stats.spearmanr([stats.iqr([pf[pt] for pid, pf in pfs.items() if pid in target_pids]) for uid, pfs in uid_to_pattern_fracs.items() if uid in pt_uids],\n [np.median([x['perf'] for x in user_meta_lookup[uid] if x['pid'] in target_pids]) for uid, pfs in uid_to_pattern_fracs.items() if uid in pt_uids],\n nan_policy=\"omit\"))\n\n # coefs = {uid: np.corrcoef([[u[a + \"_ubiq_all\"] for u in us if u['pid'] in target_pids] for a in get_action_labels()]) for uid, us in ubiq_lookup.items() if uid in uids}\n coefs = np.corrcoef([[u[a + \"_ubiq_all\"] for uid in uids for u in ubiq_lookup[uid] if u['pid'] in target_pids] for a in get_action_labels()])\n fig, ax = plt.subplots(figsize=(10,10))\n # im = ax.matshow(np.nanmean(list(coefs.values()), axis=0))\n im = ax.matshow(coefs)\n ax.figure.colorbar(im, ax=ax)\n ax.set_xticks(np.arange(len(get_action_labels())))\n ax.set_yticks(np.arange(len(get_action_labels())))\n ax.set_xticklabels(get_action_labels())\n ax.set_yticklabels(get_action_labels())\n plt.setp(ax.get_xticklabels(), rotation=-30, ha=\"right\", rotation_mode=\"anchor\")\n fig.savefig(\"variation_viz/all_coef_mat_ubiq_{}cohort.png\".format(label))\n plt.close()\n\n # coefs = {uid: np.corrcoef([[pf[pt] for pid, pf in pfs.items() if pid in target_pids] for pt in target_pts]) for uid, pfs in uid_to_pattern_fracs.items() if uid in uids}\n coefs = np.corrcoef([[pf[pt] for uid in uids for pid, pf in uid_to_pattern_fracs[uid].items() if pid in target_pids] for pt in target_pts])\n fig, ax = plt.subplots(figsize=(10,10))\n # im = ax.matshow(np.nanmean(list(coefs.values()), axis=0), vmax=0.5)\n im = ax.matshow(coefs)\n ax.figure.colorbar(im, ax=ax)\n ax.set_xticks(np.arange(len(target_pts)))\n ax.set_yticks(np.arange(len(target_pts)))\n ax.set_xticklabels(target_pts)\n ax.set_yticklabels(target_pts)\n plt.setp(ax.get_xticklabels(), rotation=-30, ha=\"right\", rotation_mode=\"anchor\")\n fig.savefig(\"variation_viz/all_coef_mat_patterns_{}cohort.png\".format(label))\n plt.close()\n print(\"\\n\\n\")\n\n # shown = []\n # print()\n # print(\"correlations of two-action correlation with perf (only those with p < 0.05 shown\")\n # for a in get_action_labels():\n # series = []\n # for b in get_action_labels():\n # s = [stats.spearmanr([u[a + \"_ubiq_all\"] for u in us if u['pid'] in target_pids],\n # [u[b + \"_ubiq_all\"] for u in us if u['pid'] in target_pids]) for uid, us in ubiq_lookup.items() if uid in uids]\n # series.append([r.correlation for r in s if not np.isnan(r.correlation)])\n # if {a, b} not in shown:\n # shown.append({a, b})\n # cor = stats.spearmanr([x.correlation for x in s], [np.median([x['perf'] for x in user_meta_lookup[uid]]) for uid, us in ubiq_lookup.items() if uid in uids], nan_policy=\"omit\")\n # if cor.pvalue < 0.05:\n # print(\"cor({}, {}) {}\".format(a, b, cor))\n # make_boxplot(series, get_action_labels(), \"spearman r\", \"variation_viz/{}_correlations_{}cohort.png\".format(a, min_exp))\n # print()\n # print()\n\n # shown = []\n print()\n print(\"correlations of two-pattern correlation with perf (only those with p < 0.01 shown)\")\n for a, b in combinations(target_pts, 2):\n # series = []\n # for b in target_pts:\n s = [stats.spearmanr([pf[a] for pid, pf in pfs.items() if pid in target_pids],\n [pf[b] for pid, pf in pfs.items() if pid in target_pids]) for uid, pfs in uid_to_pattern_fracs.items() if uid in uids]\n # series.append([r.correlation for r in s if not np.isnan(r.correlation)])\n # if {a, b} not in shown:\n # shown.append({a, b})\n cor = stats.spearmanr([x.correlation for x in s], [np.median([x['perf'] for x in user_meta_lookup[uid]]) for uid, pfs in uid_to_pattern_fracs.items() if uid in uids], nan_policy=\"omit\")\n if cor.pvalue < 0.01:\n print(\"cor({}, {}) {}\".format(a, b, cor))\n # make_boxplot(series, get_action_labels(), \"spearman r\", \"variation_viz/{}_correlations_{}cohort.png\".format(a, min_exp))\n print()\n print()\n\n# devs = {}\n# for uid, us in ubiq_lookup.items():\n# target_us = [u for u in us if u['pid'] in target_pids]\n# devs[uid] = {}\n# for i, u in enumerate(target_us[5:], 5):\n# pid = u['pid']\n# devs[uid][pid] = {}\n# for a in get_action_labels():\n# mean = np.mean([u[a + \"_ubiq_all\"] for u in target_us[:i] if a != \"build\" or u['pid'] >= '2002327'])\n# std = np.std([u[a + \"_ubiq_all\"] for u in target_us[:i] if a != \"build\" or u['pid'] >= '2002327'])\n# devs[uid][pid][a] = (u[a + \"_ubiq_all\"] - mean) / std\n" ]
[ [ "matplotlib.use", "scipy.stats.iqr", "numpy.median", "matplotlib.pyplot.close", "matplotlib.pyplot.subplots" ] ]
chto/redmapper
[ "1dc66b601889ef9913f0f9b2e05980b982834485" ]
[ "tests/test_cluster.py" ]
[ "from __future__ import division, absolute_import, print_function\nfrom past.builtins import xrange\n\nimport unittest\nimport numpy.testing as testing\nimport numpy as np\nimport fitsio\nfrom numpy import random\n\nfrom redmapper import Entry\nfrom redmapper import Cluster\nfrom redmapper import Configuration\nfrom redmapper import GalaxyCatalog\nfrom redmapper import Background\nfrom redmapper import RedSequenceColorPar\nfrom redmapper import HPMask\nfrom redmapper import DepthMap\nfrom redmapper.utilities import calc_theta_i\n\nclass ClusterTestCase(unittest.TestCase):\n \"\"\"\n This file tests multiple features of the redmapper.Cluster class, including\n background and richness computation.\n \"\"\"\n def runTest(self):\n \"\"\"\n Run the ClusterTest\n \"\"\"\n\n # all new...\n\n random.seed(seed=12345)\n\n file_path = 'data_for_tests'\n\n cluster = Cluster()\n\n conf_filename = 'testconfig.yaml'\n cluster.config = Configuration(file_path + '/' + conf_filename)\n\n filename = 'test_cluster_members.fit'\n\n neighbors = GalaxyCatalog.from_fits_file(file_path + '/' + filename)\n\n cluster.set_neighbors(neighbors)\n\n zred_filename = 'test_dr8_pars.fit'\n cluster.zredstr = RedSequenceColorPar(file_path + '/' + zred_filename, fine=True)\n\n bkg_filename = 'test_bkg.fit'\n cluster.bkg = Background('%s/%s' % (file_path, bkg_filename))\n\n hdr=fitsio.read_header(file_path+'/'+filename,ext=1)\n cluster.redshift = hdr['Z']\n richness_compare = hdr['LAMBDA']\n richness_compare_err = hdr['LAMBDA_E']\n scaleval_compare = hdr['SCALEVAL']\n cpars_compare = np.array([hdr['CPARS0'], hdr['CPARS1'], hdr['CPARS2'], hdr['CPARS3']])\n cval_compare = hdr['CVAL']\n mstar_compare = hdr['MSTAR']\n cluster.ra = hdr['RA']\n cluster.dec = hdr['DEC']\n\n mask = HPMask(cluster.config)\n maskgal_index = mask.select_maskgals_sample(maskgal_index=0)\n mask.set_radmask(cluster)\n\n depthstr = DepthMap(cluster.config)\n depthstr.calc_maskdepth(mask.maskgals, cluster.ra, cluster.dec, cluster.mpc_scale)\n\n # Test the NFW profile on its own\n # (this works to 5 decimal places because of the 2*pi*r scaling)\n nfw_python = cluster._calc_radial_profile()\n testing.assert_almost_equal(nfw_python, neighbors.nfw/(2.*np.pi*neighbors.r),5)\n\n # Test the background\n # Note that this uses the input chisq values\n bkg_python = cluster.calc_bkg_density(cluster.neighbors.r,\n cluster.neighbors.chisq,\n cluster.neighbors.refmag)\n # this is cheating here...\n to_test, = np.where((cluster.neighbors.refmag < cluster.bkg.refmagbins[-1]))\n\n seed = 0\n random.seed(seed = 0)\n\n richness = cluster.calc_richness(mask)\n\n # these are regression tests. Various mask issues make the matching\n # to idl for the time being\n testing.assert_almost_equal(cluster.Lambda, 24.366407, 5)\n testing.assert_almost_equal(cluster.lambda_e, 2.5137918, 5)\n\n return\n\n\nif __name__=='__main__':\n unittest.main()\n\n" ]
[ [ "numpy.random.seed", "numpy.where", "numpy.array", "numpy.testing.assert_almost_equal" ] ]
ali-mahdavi-mazdeh/pyHMT2D
[ "5351ea8a0d234d4a2b8e1e62c803d7f3cfeb0f4d" ]
[ "pyHMT2D/Misc/Terrain.py" ]
[ "\"\"\"\nA Python class for terrain data I/O, creation, and manipulation\n\"\"\"\n\nimport math\n\nimport numpy as np\nimport sys\n\nfrom osgeo import gdal\nfrom osgeo import osr\n\nfrom pyHMT2D.Hydraulic_Models_Data import HydraulicData\nimport random\n\nclass Terrain(HydraulicData):\n \"\"\"A Python class for terrain data I/O, creation, and manipulation\n\n Typical work flow is as follows:\n\n 1. create the Terrain object\n 2. create the terrain (elevation, pixel_width/height): user can either call\n some pre-defined terrains such as constant slope, or create the terrain by themsleves\n and then call set_terrain(...), and set_pixel_size(...)\n 3. set the georeferencing by calling set_georeference(...)\n 4. save the terrain to file by calling save_terrain_to_file(...)\n\n Attributes\n ----------\n name : str\n name of the terrain\n elevation : numpy.ndarray\n elevation of the terrain (2D numpy array)\n geoTopLeft_x : float\n raster's top-left corner georeferenced x-coordinate\n geoTopLeft_y : float\n raster's top-left corner georeferenced y-coordinate\n pixel_width : float\n pixel width (in x), i.e, each pixel is how many meters/feet wide?\n pixel_height : float\n pixel height (in y), i.e, each pixel is how many meters/feet high?\n EPSGCode : int\n EPSG (European Petroleum Survey Group) code that defines the coordinate reference system\n geoTransform : list\n affine transform for the raster image from image pixel to real coordinates\n supportedGDALDrivers : list\n list of supported GDAL drivers (short names only)\n\n \"\"\"\n\n def __init__(self, name):\n \"\"\"Terrain class constructor\n\n Parameters\n ----------\n name : str\n name of the terrain\n\n \"\"\"\n\n HydraulicData.__init__(self, \"Terrain\")\n\n self.name = name # name of the terrain\n self.elevation = np.array([]) # elevation of the terrain, should be 2D numpy array\n\n self.geoTopLeft_x = 0.0 # raster's top-left corner georeferenced location\n self.geoTopleft_y = 0.0\n\n self.pixel_width = -1.0 # pixel width (in x), i.e, each pixel is how many meters/feet wide?\n self.pixel_height = -1.0 # pixel height (in y)\n\n self.EPSGCode = -1 # EPSG (European Petroleum Survey Group) code that defines the coordinate reference system\n\n self.geoTransform = [] # affine transform for the raster image from image pixel to real coordinates\n\n self.supportedGDALDrivers = [] #list of supported GDAL drivers (short names only)\n self.build_supported_GDAL_drivers_list()\n\n\n def get_terrain_name(self):\n \"\"\"Get the terrain name\n\n Returns\n -------\n name : str\n name of the terrain\n\n \"\"\"\n\n return self.name\n\n def get_elevation(self):\n \"\"\"Get the elevation array\n\n Returns\n -------\n elevation : numpy.array\n elevation 2D array\n \"\"\"\n\n return self.elevation\n\n def set_elevation(self, elevation):\n \"\"\"Set the elevation array\n\n Parameters\n _______\n elevation : numpy.ndarray\n elevation 2D array\n\n Returns\n -------\n\n \"\"\"\n\n self.elevation = elevation\n\n def set_pixel_size(self, pixel_width, pixel_height):\n \"\"\"Set the pixel size in x and y directions\n\n Parameters\n ----------\n pixel_width : float\n the width of each pixel in real world\n pixel_height : float\n the height of each pixel in real world\n\n Returns\n -------\n\n \"\"\"\n\n self.pixel_width = pixel_width\n self.pixel_height = pixel_height\n\n def build_supported_GDAL_drivers_list(self):\n \"\"\"Build the list of supported GDAL drivers list\n\n Returns\n -------\n\n \"\"\"\n\n for i in range(gdal.GetDriverCount()):\n drv = gdal.GetDriver(i)\n self.supportedGDALDrivers.append(drv.ShortName)\n\n print(\"Supported GDAL drivers are: \", self.supportedGDALDrivers)\n\n def create_constant_slope_channel_elevation(self, slope, channel_lenx, channel_leny, pixel_width,\n pixel_height, elevation_origin=0, extra_len=0):\n \"\"\"Create a constant slope channel elevation\n\n The slope is in the x direction only. The slope in the y direction is zero.\n\n Parameters\n -----------\n slope : float\n slope in x\n channel_lenx : float\n channel length in x\n channel_leny : float\n channel length in y\n elevation_origin : float\n the elevation at the origin (top left; does not account for the extra fringe)\n extra_len : float\n optional extra fringe length added to the channel domain (to\n have some free room in developing 2D models in e.g., SMS or HEC-RAS.\n\n Returns\n -------\n\n \"\"\"\n\n # raster image width and height in pixels\n self.pixel_width = pixel_width\n self.pixel_height = pixel_height\n\n #raster size (without extra length)\n nx = int(channel_lenx/pixel_width)\n ny = int(channel_leny/pixel_height)\n\n #extra length (fringe)\n extra_len_nx = int(extra_len/pixel_width)\n extra_len_ny = int(extra_len/pixel_height)\n self.elevation = np.zeros((ny+extra_len_ny*2,nx+extra_len_nx*2))\n\n #set the elevation\n for iy in range(0, ny + extra_len_ny * 2):\n for ix in range(0, nx + extra_len_nx * 2):\n self.elevation[iy, ix] = elevation_origin -slope * (ix-extra_len_nx) * pixel_width\n\n def add_bedform(self, channel_lenx, channel_leny, Lb, Hb, alpha_lee, a_stoss, rotation=0,perturbation=0):\n \"\"\"Add bedform feature to the terrain\n\n Typical use scenario is firstly to create a constant slope channel and then add the bedform features.\n\n Parameters\n ----------\n channel_lenx : float\n channel length in x\n channel_leny : float\n channel length in y\n Lb : float\n bed form length\n Hb : float\n bed form height\n alpha_lee : float\n bed-form's lee side slope angle (in degrees)\n a_stoss : float\n bed-form's stoss size sine function amplitude\n rotation : float\n optional rotation angle of the domain in degrees (default is zero)\n perturbation : float\n optional perturbation added to the terrain (default is zero)\n\n Returns\n -------\n\n \"\"\"\n\n #lee side length\n Llee = Hb/np.tan(math.radians(alpha_lee))\n\n #stoss side length\n Lstoss = Lb - Llee\n\n if Lstoss <=0:\n raise Exception(\"The calculated stoss lengh is negative. Check the bedform parameters.\")\n\n print(\"Bedform lengths of stoss and lee sides are: \", Lstoss, Llee)\n\n #stoss side angle\n alpha_stoss = np.arctan(Hb/Lstoss)\n\n #raster size (without extra length)\n nx = int(channel_lenx/self.pixel_width)\n ny = int(channel_leny/self.pixel_height)\n\n # set the elevation\n for iy in range(self.elevation.shape[0]):\n for ix in range(self.elevation.shape[1]):\n\n # get current grid point's coordinate\n x = ix * self.pixel_width\n y = iy * self.pixel_height\n L = np.sqrt(x**2+y**2)\n\n x_new = x\n y_new = y\n\n # take care of optional rotation\n if np.abs(rotation) > 1e-3:\n alpha = np.arctan(y/(x+1e-6))\n alpha_prime = alpha + np.deg2rad(rotation)\n x_new = L*np.cos(alpha_prime)\n y_new = L*np.sin(alpha_prime)\n\n # get the location of current grid point within one bedform\n xprime = x_new % Lb\n\n # elevation due to the existence of bedform\n deltaZ = 0.0\n\n if xprime <= Lstoss: #if current location is in the stoss side\n deltaZ = xprime*np.tan(alpha_stoss) - a_stoss*np.sin(2*math.pi*xprime/Lstoss)\n else: #if the current location is in the lee side\n deltaZ = Hb - Hb*(xprime-Lstoss)/(Lb-Lstoss)\n\n # shift the bedform so vertically the center is at the origin\n deltaZ -= Hb/2.0\n\n # take care of optional perturbation\n if np.abs(perturbation) > 1e-3:\n deltaZ += (random.random() - 0.5)*2*perturbation\n\n self.elevation[iy, ix] += deltaZ\n\n def add_composite_channel(self, channel_lenx, channel_leny, L1, B, D, alpha):\n \"\"\"Add composite channel to the terrain\n\n Typical use scenario is firstly to create a constant slope channel and then add the composite channel.\n\n Parameters\n ----------\n channel_lenx : float\n channel length in x\n channel_leny : float\n channel length in y\n L1 : float\n flood plain's width on one side (the other side can be calculated)\n B : float\n main channel bottom width\n D : float\n main channel depth\n alpha : float\n main channel's side slope angle (in degrees)\n\n Returns\n -------\n\n \"\"\"\n\n #main channel slope's horizontal distance\n Lside = D*np.tan(math.radians(alpha))\n\n #raster size (without extra length)\n nx = int(channel_lenx/self.pixel_width)\n ny = int(channel_leny/self.pixel_height)\n\n # set the elevation\n for iy in range(self.elevation.shape[0]):\n for ix in range(self.elevation.shape[1]):\n\n # get current grid point's coordinate\n x = ix * self.pixel_width\n y = iy * self.pixel_height\n\n # elevation modification due to the existence of main channel\n deltaZ = 0.0\n\n if (y>L1 and y <= (L1+Lside)):\n deltaZ = -(y-L1)/np.tan(math.radians(alpha))\n elif (y>(L1+Lside) and y<= (L1+Lside+B)):\n deltaZ = -D\n elif (y>(L1+Lside+B) and y < (L1+Lside+B+Lside)):\n deltaZ = -(L1+Lside+B+Lside - y)/np.tan(math.radians(alpha))\n else:\n deltaZ = 0.0\n\n self.elevation[iy, ix] += deltaZ\n\n\n def set_georeference(self, geoTopLeft_x, geoTopLeft_y, EPSGCode):\n \"\"\"Set the georeferencing information\n\n Parameters\n ----------\n geoTopLeft_x : float\n raster's top-left corner georeferenced x location\n geoTopLeft_y : float\n raster's top-left corner georeferenced y location\n EPSGCode : int\n EPSG (European Petroleum Survey Group) code that defines the coordinate reference system\n\n Returns\n -------\n\n \"\"\"\n\n if self.pixel_width < 0 or self.pixel_height < 0:\n print(\"Either pixel_width or pixel_height is negative. Need to create the terrain first.\")\n print(\"Exiting...\")\n sys.exit()\n\n self.geoTopLeft_x = geoTopLeft_x\n self.geoTopleft_y = geoTopLeft_y\n\n self.geoTransform = [geoTopLeft_x, self.pixel_width, 0, self.geoTopleft_y, 0, -self.pixel_height]\n\n self.EPSGCode = EPSGCode\n\n def save_terrain_to_file(self, terrainFileName, geoDriverName = 'GTiff'):\n \"\"\"save terrain to file, such as GeoTiff\n\n Parameters\n -----------\n terrainFileName : str\n file name for the saved terrain\n geoDriverName : str\n GDAL raster driver names, such as 'GTiff'\n\n \"\"\"\n\n print(\"Save the terrain to file:\", terrainFileName)\n\n if geoDriverName not in self.supportedGDALDrivers:\n print(\"The provided geoDriverName\", geoDriverName, \"is not supported.\")\n print(\"Supported GDAL driver names are:\", self.supportedGDALDrivers)\n print(\"Exiting...\")\n sys.exit()\n\n if (not self.elevation.size) or (self.pixel_width < 0) or (self.pixel_height < 0) \\\n or (self.EPSGCode < 0) or (len(self.geoTransform) == 0):\n print(\"Terrain data is not complete. Missing elevation, pixel size, EPSG code, \"\n \"or geoTransform.\")\n print(\"Exiting...\")\n sys.exit()\n\n driver = gdal.GetDriverByName(geoDriverName)\n dst_filename = terrainFileName\n dst_ds = driver.Create(dst_filename, self.elevation.shape[1],\n self.elevation.shape[0], 1, gdal.GDT_Float32)\n\n dst_ds.SetGeoTransform(self.geoTransform)\n\n srs = osr.SpatialReference()\n srs.ImportFromEPSG(self.EPSGCode)\n\n dst_ds.SetProjection(srs.ExportToWkt())\n\n dst_ds.GetRasterBand(1).WriteArray(self.elevation)\n\n # Once we're done, close properly the dataset\n dst_ds = None\n\n\n" ]
[ [ "numpy.array", "numpy.sin", "numpy.zeros", "numpy.tan", "numpy.arctan", "numpy.sqrt", "numpy.abs", "numpy.deg2rad", "numpy.cos" ] ]
londoed/a3c
[ "10073b294cf8faeb78d7be4737513d88d93ff0d7" ]
[ "a3c.py" ]
[ "import numpy as np\nimport tensorflow as tf\nimport sonnet as snt\nimport gym\n\nimport os\nimport threading\nimport multiprocessing\nimport argparse\nfrom queue import Queue\n\ntf.enable_eager_execution()\n\nparser = argparse.ArgumentParser(description='Run A3C algorithm on gym env.')\nparser.add_argument('--algorithm', default='a3c', type=str,\n help='Choose between \\'a3c\\' and \\'random\\'.')\nparser.add_argument('--train', dest='train', action='store_true',\n help='Train our model.')\nparser.add_argument('--lr', default=0.001,\n help='Learning rate for the shared optimizer.')\nparser.add_argument('--update-freq', default=20, type=int,\n help='How often to update the global model.')\nparser.add_argument('--max-eps', default=1000, type=int,\n help='Global maximum number of episodes to run.')\nparser.add_argument('--gamma', default=0.99,\n help='Discount factor of rewards.')\nargs = parser.parse_args()\n\n\nclass A3C(snt.AbstractModule):\n def __init__(self, state_size, action_size, name='a3c'):\n super(A3C, self).__init__(name=name)\n self.state_size = state_size\n self.action_size = action_size\n\n def _build(self, inputs):\n logits = snt.Sequential([\n snt.Linear(100), tf.nn.relu,\n snt.Linear(self.action_size)\n ])\n\n values = snt.Sequential([\n snt.Linear(100), tf.nn.relu,\n snt.Linear(1)\n ])\n return logits(inputs), values(inputs)\n\nclass RandomAgent():\n def __init__(self, env_name, max_eps):\n self.env = env\n self.max_episodes = max_episodes\n self.res_queue = Queue()\n\n def run(self):\n reward_avg = 0\n for episode in range(self.max_episodes):\n is_done = False\n self.env.reset()\n reward_sum = 0.0\n steps = 0\n while not is_done:\n _, reward, is_done, _ = self.env.step(self.env.action_space.sample())\n steps += 1\n reward_sum += reward\n reward_avg += reward_sum\n final_avg = reward_avg / float(self.max_episodes)\n return final_avg\n\nclass MasterAgent():\n def __init__(self):\n self.env_name = env_name\n env = gym.make(self.game_name)\n self.state_size = env.observation_space.shape[0]\n self.action_size = env.action_space.n\n self.opt = tf.train.AdamOptimizer(args.lr, use_locking=True)\n self.global_model = A3C(self.state_size, self.action_size)\n self.global_model(tf.convert_to_tensor(np.random.random((1, self.state_size)), dtype=tf.float32))\n\n def train(self):\n if args.algorithm == 'random':\n random_agent = RandomAgent(self.game_name, args.max_episodes)\n random_agent.run()\n return\n res_queue = Queue()\n\n workers = [Worker(self.state_size,\n self.action_size,\n self.opt, res_queue,\n i, game_name=self.game_name)\n for i in range(multiprocessing.cpu_count())]\n\n for i, worker in enumerate(worker):\n worker.start()\n\n def play(self):\n env = gym.make(self.game_name).unwrapped\n state = env.reset()\n model = self.global_model\n is_done = False\n step_counter = 0\n reward_sum = 0\n\n while not is_done:\n env.render(mode='rgb_array')\n policy, value = model(tf.convert_to_tensor(state[None, :], dtype=tf.float32))\n policy = tf.nn.softmax(policy)\n action = np.argmax(policy)\n state, reward, is_done, _ = env.step(action)\n reward_sum += reward\n step_counter += 1\n env.close()\n\nclass Memory():\n def __init__(self):\n self.states = []\n self.actions = []\n self.rewards = []\n\n def store(self, state, action, reward):\n self.states.append(state)\n self.actions.append(action)\n self.rewards.append(reward)\n\n def clear(self):\n self.states = []\n self.actions = []\n self.rewards = []\n\nclass Worker(threading.Thread):\n global_episode = 0\n best_score = 0\n save_lock = threading.Lock()\n\n def __init__(self, state_size, action_size,\n global_model, opt, res_queue,\n idx, game_name):\n super(Worker, self).__init__()\n self.state_size = state_size\n self.action_size = action_size\n self.result_queue = result_queue\n self.global_model = global_model\n self.opt = opt\n self.local_model = A3C(self.state_size, self.action_size)\n self.worker_idx = idx\n self.game_name = game_name\n self.env = gym.make(self.game_name).unwrapped\n self.ep_loss = 0.0\n\n def run(self):\n total_step = 1\n mem = Memory()\n while Worker.global_episode < args.max_eps:\n current_state = self.env.reset()\n mem.clear()\n ep_reward = 0.\n ep_steps = 0\n self.ep_loss = 0\n time_count = 0\n is_done = False\n while not is_done:\n logits, _ = self.local_model(tf.convert_to_tensor(current_state[None, :], dtype=tf.float32))\n probs = tf.nn.softmax(logits)\n action = np.random.choice(self.action_size, p=probs.numpy()[0])\n new_state, reward, is_done, _ = self.env.step(action)\n if done:\n reward = 1\n ep_reward += reward\n mem.store(current_state, action, reward)\n\n if time_count == args.update_freq or is_done:\n with tf.GradientTape() as tape:\n total_loss = self.compute_loss(is_done, new_state, mem, args.gamma)\n self.ep_loss += total_loss\n grads = tape.gradient(total_loss, self.local_model.trainable_weights)\n self.opt.apply_gradients(zip(grads, self.global_model.trainable_weights))\n self.local_model.set_weights(self.global_model.get_weights())\n\n mem.clear()\n time_count = 0\n\n if is_done:\n if ep_reward > Worker.best_score:\n Worker.best_score = ep_reward\n Worker.global_episode += 1\n ep_steps += 1\n time_count += 1\n current_state = new_state\n total_step += 1\n self.res_queu.put(None)\n\n def compute_loss(self, is_done, new_state, memory, gamma=0.99):\n if is_done:\n reward_sum = 0.\n else:\n reward_sum = self.local_model(tf.convert_to_tensor(new_state[None, :], dtype=tf.float32)).numpy()[0]\n\n discounted_rewards = []\n for reward in memory.rewards[::-1]:\n reward_sum = reward + gamma * reward_sum\n discounted_rewards.append(reward_sum)\n discounted_rewards.reverse()\n\n logits, values = self.local_model(tf.convert_to_tensor(np.vstack(memory.states), dtype=tf.float32))\n advantage = tf.convert_to_tensor(np.array(discounted_rewards)[:, None], dtype=tf.float32) - values\n\n value_loss = advantage**2\n\n policy = tf.nn.softmax(logits)\n entropy = tf.nn.softmax_cross_entropy_with_logits_v2(labels=policy, logits=logits)\n policy_loss = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=memory.actions, logits=logits)\n\n policy_loss *= tf.stop_gradient(advantage)\n policy_loss -= 0.01 * entropy\n total_loss = tf.reduce_mean((0.5 * value_loss + policy_loss))\n return total_loss\n\nif __name__ == '__main__':\n print(args)\n master = MasterAgent()\n if args.train:\n master.train()\n else:\n master.play()\n" ]
[ [ "tensorflow.convert_to_tensor", "numpy.array", "tensorflow.train.AdamOptimizer", "tensorflow.GradientTape", "tensorflow.nn.softmax_cross_entropy_with_logits_v2", "tensorflow.enable_eager_execution", "numpy.argmax", "tensorflow.nn.softmax", "numpy.random.random", "tensorflow.reduce_mean", "tensorflow.stop_gradient", "numpy.vstack", "tensorflow.nn.sparse_softmax_cross_entropy_with_logits" ] ]
christopherhesse/atari-reset
[ "0c1b1124d5348ae11ee61442d387e455b05f9fc2" ]
[ "test_atari.py" ]
[ "#!/usr/bin/env python\nimport argparse\nimport os\nimport gym\n\ndef test(game_name, num_timesteps, policy, load_path, save_path, noops=False, sticky=False, epsgreedy=False):\n import tensorflow as tf\n import horovod.tensorflow as hvd\n hvd.init()\n print('initialized worker %d' % hvd.rank(), flush=True)\n from baselines.common import set_global_seeds\n set_global_seeds(hvd.rank())\n from baselines import bench\n from baselines.common import set_global_seeds\n from atari_reset.wrappers import VecFrameStack, VideoWriter, my_wrapper,\\\n EpsGreedyEnv, StickyActionEnv, NoopResetEnv, SubprocVecEnv\n from atari_reset.ppo import learn\n from atari_reset.policies import CnnPolicy, GRUPolicy\n\n set_global_seeds(hvd.rank())\n ncpu = 2\n config = tf.ConfigProto(allow_soft_placement=True,\n intra_op_parallelism_threads=ncpu,\n inter_op_parallelism_threads=ncpu)\n config.gpu_options.allow_growth = True\n config.gpu_options.visible_device_list = str(hvd.local_rank())\n tf.Session(config=config).__enter__()\n\n def make_env(rank):\n def env_fn():\n env = gym.make(game_name + 'NoFrameskip-v4')\n env = bench.Monitor(env, \"{}.monitor.json\".format(rank))\n if rank%nenvs == 0 and hvd.local_rank()==0:\n os.makedirs('results/' + game_name, exist_ok=True)\n videofile_prefix = 'results/' + game_name\n env = VideoWriter(env, videofile_prefix)\n if noops:\n env = NoopResetEnv(env)\n if sticky:\n env = StickyActionEnv(env)\n env = my_wrapper(env, clip_rewards=True)\n if epsgreedy:\n env = EpsGreedyEnv(env)\n return env\n return env_fn\n\n nenvs = 8\n env = SubprocVecEnv([make_env(i + nenvs * hvd.rank()) for i in range(nenvs)])\n env = VecFrameStack(env, 4)\n\n policy = {'cnn' : CnnPolicy, 'gru': GRUPolicy}[policy]\n learn(policy=policy, env=env, nsteps=256, log_interval=1, save_interval=100, total_timesteps=num_timesteps,\n load_path=load_path, save_path=save_path, game_name=game_name, test_mode=True)\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--game', type=str, default='MontezumaRevenge')\n parser.add_argument('--num_timesteps', type=int, default=1e8)\n parser.add_argument('--policy', default='gru')\n parser.add_argument('--load_path', type=str, default=None)\n parser.add_argument('--save_path', type=str, default='results', help='Where to save results to')\n parser.add_argument(\"--noops\", help=\"Use 0 to 30 random noops at the start of each episode\", action=\"store_true\")\n parser.add_argument(\"--sticky\", help=\"Use sticky actions\", action=\"store_true\")\n parser.add_argument(\"--epsgreedy\", help=\"Take random action with probability 0.01\", action=\"store_true\")\n args = parser.parse_args()\n\n test(args.game, args.num_timesteps, args.policy, args.load_path, args.save_path, args.noops, args.sticky, args.epsgreedy)\n" ]
[ [ "tensorflow.ConfigProto", "tensorflow.Session" ] ]
BUTSpeechFIT/MT_Transformer
[ "86e71f93b06ceb937c71171ee781377e2929b0ea" ]
[ "MT_Training.py" ]
[ "#!/usr/bin/python\nimport sys\nimport os\nimport subprocess\nfrom os.path import join, isdir\nimport numpy as np\nimport fileinput\nimport json\nimport random\nfrom itertools import chain\nfrom numpy.random import permutation\n##------------------------------------------------------------------\nimport torch\nfrom torch.autograd import Variable\n#----------------------------------------\nimport torch.nn as nn\nfrom torch import autograd, nn, optim\nos.environ['PYTHONUNBUFFERED'] = '0'\nimport torch.nn.parallel\nimport torch.backends.cudnn as cudnn\nimport torch.optim as optim\n\nfrom random import shuffle\nfrom statistics import mean\n\n\nimport matplotlib\nimport matplotlib.pyplot as plt \nplt.switch_backend('agg')\nmatplotlib.pyplot.viridis()\nimport glob\n\n#*************************************************************************************************************************\n####### Loading the Parser and default arguments\nsys.path.insert(0,'/mnt/matylda3/vydana/HOW2_EXP/MT_Transformer/MT_TransV1/')\nimport MT_Transformer_arg\nfrom MT_Transformer_arg import parser\nargs = parser.parse_args()\n\n###save architecture for decoding\nmodel_path_name=join(args.model_dir,'model_architecture_')\nwith open(model_path_name, 'w') as f:\n json.dump(args.__dict__, f, indent=2)\nprint(args)\n# #####setting the gpus in the gpu cluster\n# #**********************************\nfrom Set_gpus import Set_gpu\nif args.gpu:\n Set_gpu()\n###----------------------------------------\n#==============================================================\nfrom Dataloader_for_MT_v2 import DataLoader\nfrom TRANSFORMER_MT_V1 import Transformer\nfrom Initializing_Transformer_MT import Initialize_Att_model\nfrom Training_loop_MT import train_val_model\nfrom Load_sp_model import Load_sp_models\n##==================================\n#==============================================================\nif not isdir(args.model_dir):\n os.makedirs(args.model_dir)\n\npng_dir=args.model_dir+'_png'\nif not isdir(png_dir):\n os.makedirs(png_dir)\n############################################\n\n#=============================================================\ndef main():\n ##Load setpiece models for Dataloaders\n Src_model=Load_sp_models(args.Src_model_path)\n Tgt_model=Load_sp_models(args.Tgt_model_path)\n ###initilize the model\n model,optimizer=Initialize_Att_model(args)\n #============================================================\n #------------------------------------------------------------\n train_gen = DataLoader({'files': glob.glob(args.data_dir + \"train_splits_V2/*\"),\n 'max_batch_label_len': args.max_batch_label_len,\n 'max_batch_len': args.max_batch_len,\n 'max_feat_len': args.max_feat_len,\n 'max_label_len': args.max_label_len,\n 'Src_model': Src_model,\n 'Tgt_model': Tgt_model,\n 'queue_size': 100,\n 'apply_cmvn': 1,\n 'min_words': args.min_words,\n 'max_words': args.max_words,\n 'min_len_ratio': args.min_len_ratio}) \n\n\n dev_gen = DataLoader({'files': glob.glob(args.data_dir + \"dev_splits/*\"),\n 'max_batch_label_len': 20000,\n 'max_batch_len': args.max_batch_len,\n 'max_feat_len': 1000,\n 'max_label_len': 1000,\n 'Src_model': Src_model,\n 'Tgt_model': Tgt_model,\n 'queue_size': 100,\n 'apply_cmvn': 1,\n 'min_words': 0,\n 'max_words': 10000,\n 'min_len_ratio': 4})\n\n\n #Flags that may change while training \n val_history=np.zeros(args.nepochs)\n #======================================\n for epoch in range(args.nepochs):\n ##start of the epoch\n tr_CER=[]; tr_BPE_CER=[]; L_train_cost=[]\n model.train();\n validate_interval = int(args.validate_interval * args.accm_grad) if args.accm_grad>0 else args.validate_interval\n for trs_no in range(validate_interval):\n B1 = train_gen.next()\n assert B1 is not None, \"None should never come out of the DataLoader\"\n Output_trainval_dict=train_val_model(smp_no=trs_no,\n args = args, \n model = model,\n optimizer = optimizer,\n data_dict = B1,\n trainflag = True)\n #\n #\n #get the losses form the dict\n L_train_cost.append(Output_trainval_dict.get('cost_cpu'))\n tr_CER.append(Output_trainval_dict.get('Char_cer'))\n tr_BPE_CER.append(Output_trainval_dict.get('Word_cer'))\n #attention_map=Output_trainval_dict.get('attention_record').data.cpu().numpy()\n #==========================================\n if (trs_no%args.tr_disp==0):\n print(\"tr ep:==:>\",epoch,\"sampl no:==:>\",trs_no,\"train_cost==:>\",__mean(L_train_cost),\"CER:\",__mean(tr_CER),'BPE_CER',__mean(tr_BPE_CER),flush=True) \n #------------------------\n if args.plot_fig_training:\n plot_name=join(png_dir,'train_epoch'+str(epoch)+'_attention_single_file_'+str(trs_no)+'.png')\n\n plotting(plot_name,attention_map)\n \n ###validate the model\n model.eval()\n #=======================================================\n Vl_CER=[]; Vl_BPE_CER=[];L_val_cost=[]\n val_examples=0\n for vl_smp in range(args.max_val_examples):\n B1 = dev_gen.next()\n smp_feat = B1.get('smp_Src_data')\n val_examples+=smp_feat.shape[0]\n assert B1 is not None, \"None should never come out of the DataLoader\"\n\n ##brak when the examples are more\n if (val_examples >= args.max_val_examples):\n break;\n #-------------------------------------- \n Val_Output_trainval_dict=train_val_model(smp_no=trs_no,\n args=args,\n model = model,\n optimizer = optimizer,\n data_dict = B1,\n trainflag = False)\n \n L_val_cost.append(Val_Output_trainval_dict.get('cost_cpu'))\n Vl_CER.append(Val_Output_trainval_dict.get('Char_cer'))\n Vl_BPE_CER.append(Val_Output_trainval_dict.get('Word_cer'))\n #attention_map=Val_Output_trainval_dict.get('attention_record').data.cpu().numpy()\n #====================================================== \n #======================================================\n if (vl_smp%args.vl_disp==0) or (val_examples==args.max_val_examples-1):\n \n print(\"val epoch:==:>\",epoch,\"val smp no:==:>\",vl_smp,\"val_cost:==:>\",__mean(L_val_cost),\"CER:\",__mean(Vl_CER),'BPE_CER',__mean(Vl_BPE_CER),flush=True) \n if args.plot_fig_validation:\n plot_name=join(png_dir,'val_epoch'+str(epoch)+'_attention_single_file_'+str(vl_smp)+'.png') \n plotting(plot_name,attention_map) \n #----------------------------------------------------\n#==================================================================\n val_history[epoch]=(__mean(Vl_CER)*100)\n print(\"val_history:\",val_history[:epoch+1])\n #================================================================== \n ####saving_weights \n ct=\"model_epoch_\"+str(epoch)+\"_sample_\"+str(trs_no)+\"_\"+str(__mean(L_train_cost))+\"___\"+str(__mean(L_val_cost))+\"__\"+str(__mean(Vl_CER))\n print(ct)\n torch.save(model.state_dict(),join(args.model_dir,str(ct)))\n ####################################################### \n\n #######################################################\n ###open the file write and close it to avoid delays\n with open(args.weight_text_file,'a+') as weight_saving_file:\n print(join(args.model_dir,str(ct)), file=weight_saving_file)\n\n with open(args.Res_text_file,'a+') as Res_saving_file:\n print(float(__mean(Vl_CER)), file=Res_saving_file)\n #=================================\n # early_stopping and checkpoint averaging: \n ##print(np.array(val_his[i:i+5]),np.any(np.abs(np.array(val_his[i:i+5])-np.array(val_his[i]))>0.6))\n\n\n if args.early_stopping:\n A=val_history\n Non_zero_loss=A[A>0]\n min_cpts=np.argmin(Non_zero_loss)\n Non_zero_len=len(Non_zero_loss)\n\n if ((Non_zero_len-min_cpts)>1):\n weight_noise_flag=True\n spec_aug_flag=True\n\n #-----------------------\n if epoch>args.early_stopping_patience:\n #if (Non_zero_len-min_cpts) > args.early_stopping_patience:\n #np.any(np.abs(A[i:i+5]-A[i])>0.5)==False\n\n if np.any(np.abs( Non_zero_loss[ epoch - args.early_stopping_patience:epoch ] - Non_zero_loss[epoch-1])>0.5)==False:\n \"General early stopping has over trained the model or may be should i regularize with dropout\"\n print(\"The model is early stopping........\",\"minimum value of model is:\",min_cpts)\n exit(0)\n#======================================================\n\ndef __mean(inp):\n \"\"\"\n \"\"\"\n if len(inp)==1:\n return inp[0]\n else:\n return mean(inp)\n#=============================================================================================\nif __name__ == '__main__':\n main()\n\n\n\n" ]
[ [ "matplotlib.pyplot.switch_backend", "numpy.zeros", "matplotlib.pyplot.viridis", "numpy.argmin", "numpy.abs" ] ]
ChenyangWang1/face_parsing
[ "506e74eb8a2094920c03f2fe0774656b1043e8a6" ]
[ "test.py" ]
[ "#!/usr/bin/python\n# -*- encoding: utf-8 -*-\n\nfrom logger import setup_logger\nfrom model import BiSeNet\nfrom tqdm.autonotebook import tqdm\nimport torch\nimport os\nfrom utils.utils import *\nfrom torch.utils.data import DataLoader\nfrom face_dataset_test import FaceMask\nimport os.path as osp\nimport numpy as np\nfrom PIL import Image\nimport torchvision.transforms as transforms\nimport cv2\n\n\ndef vis_parsing_maps(im, parsing_anno, stride, save_im=False, save_path='vis_results', imspth=[]):\n # Colors for all 20 parts\n part_colors = [[255, 0, 0], [255, 85, 0], [255, 170, 0],\n [255, 0, 85], [255, 0, 170],\n [0, 255, 0], [85, 255, 0], [170, 255, 0],\n [0, 255, 85], [0, 255, 170],\n [0, 0, 255], [85, 0, 255], [170, 0, 255],\n [0, 85, 255], [0, 170, 255],\n [255, 255, 0], [255, 255, 85], [255, 255, 170],\n [255, 0, 255], [255, 85, 255], [255, 170, 255],\n [0, 255, 255], [85, 255, 255], [170, 255, 255]]\n ims = np.array(im)\n # 逆归一化\n batch_size = ims.shape[0]\n mean = np.tile(np.array([[0.485, 0.456, 0.406]]), [ims.shape[0], 1])\n std = np.tile(np.array([[0.229, 0.224, 0.225]]), [ims.shape[0], 1])\n mean = np.reshape(mean, newshape=[ims.shape[0], 3, 1, 1]) # 扩充维度以触发广播机制\n std = np.reshape(std, newshape=[ims.shape[0], 3, 1, 1])\n ims = (ims*std + mean)*255\n\n ims = np.transpose(ims, (0, 2, 3, 1)) # color channel 放到最后一维\n vis_ims = ims.copy().astype(np.uint8)\n vis_parsing_annos = parsing_anno.copy().astype(np.uint8)\n\n for i in range(ims.shape[0]):\n vis_parsing_anno = cv2.resize(vis_parsing_annos[i], None, fx=stride, fy=stride, interpolation=cv2.INTER_NEAREST)\n vis_parsing_anno_color = np.zeros((vis_parsing_anno.shape[0], vis_parsing_anno.shape[1], 3)) + 255\n\n num_of_class = np.max(vis_parsing_anno)\n\n for pi in range(1, num_of_class + 1):\n index = np.where(vis_parsing_anno == pi)\n vis_parsing_anno_color[index[0], index[1], :] = part_colors[pi]\n\n vis_parsing_anno_color = vis_parsing_anno_color.astype(np.uint8)\n # use addWeighted(src1, alpha, src2, gamma) get dst = src1*alpha + src2*beta + gamma;\n vis_im = cv2.addWeighted(cv2.cvtColor(vis_ims[i], cv2.COLOR_RGB2BGR), 0.4, vis_parsing_anno_color, 0.6, 0)\n\n # Save result or not\n if save_im:\n sv_path = os.path.join('/home/data2/miles/face_parsing', save_path)\n if not os.path.exists(sv_path):\n os.makedirs(sv_path)\n cv2.imwrite(os.path.join(sv_path, imspth[i]), vis_parsing_anno)\n cv2.imwrite(os.path.join(sv_path, 'color_'+imspth[i]), vis_im, [int(cv2.IMWRITE_JPEG_QUALITY), 100])\n\n # return vis_im\n\n\ndef testval(model_path, sv_dir='res', sv_pred=False):\n n_classes = 17\n confusion_matrix = np.zeros((n_classes, n_classes)) # num_classes x num_classes\n cropsize = [448, 448]\n data_root = '/home/data2/DATASET/vschallenge'\n batch_size = 1\n ds = FaceMask(data_root, cropsize=cropsize, mode='val')\n dl = DataLoader(ds,\n batch_size=batch_size,\n shuffle=False,\n num_workers=0\n )\n\n with torch.no_grad():\n net = BiSeNet(n_classes=n_classes)\n net.cuda()\n net.load_state_dict(torch.load(model_path))\n net.eval()\n for iter, data in enumerate(dl):\n im = data['img']\n lb = data['label']\n impth = data['impth']\n lb = torch.squeeze(lb, 1)\n im = im.cuda()\n lb = lb.cuda()\n out = net(im)[0]\n size = lb.size()\n pred = out.cpu().numpy().argmax(1)\n gt = lb.cpu().numpy()\n vis_parsing_maps(im.cpu(), pred, stride=1, save_im=True, save_path='res', imspth=impth)\n # vis_parsing_maps(im.cpu(), gt, stride=1, save_im=True, save_path='res_gt', imspth=impth)\n confusion_matrix += get_confusion_matrix(lb, out, size, n_classes, ignore=-1) # [16, 19, 448, 448]\n\n if sv_pred:\n sv_path = os.path.join(sv_dir, 'test_results')\n if not os.path.exists(sv_path):\n os.mkdir(sv_path)\n # cv2.imwrite(sv_path+'/', ) add imname\n\n if iter % 5 == 0:\n pos = confusion_matrix.sum(1)\n res = confusion_matrix.sum(0)\n tp = np.diag(confusion_matrix)\n pixel_acc = tp.sum() / pos.sum()\n mean_acc = (tp / np.maximum(1.0, pos)).mean()\n IoU_array = (tp / np.maximum(1.0, pos + res - tp))\n mean_IoU = IoU_array.mean()\n print('index/allimg {}/{}. mean_IoU: {:1.5f}. pixel_acc: {:1.5f}. mean_acc: {:1.5f}.'.format(\n iter*batch_size, len(dl)*batch_size, mean_IoU, pixel_acc, mean_acc))\n pos = confusion_matrix.sum(1)\n res = confusion_matrix.sum(0)\n tp = np.diag(confusion_matrix)\n pixel_acc = tp.sum() / pos.sum()\n mean_acc = (tp / np.maximum(1.0, pos)).mean()\n IoU_array = (tp / np.maximum(1.0, pos + res - tp))\n mean_IoU = IoU_array.mean()\n print('mean_IoU: {:1.5f}. pixel_acc: {:1.5f}. mean_acc: {:1.5f}.'.format(\n mean_IoU, pixel_acc, mean_acc))\n return mean_IoU, IoU_array, pixel_acc, mean_acc\n\n\ndef evaluate(respth='./logs/CelebAMask', dspth='./data', cp='model_final_diss.pth'):\n\n if not os.path.exists(respth):\n os.makedirs(respth)\n\n n_classes = 19\n net = BiSeNet(n_classes=n_classes)\n net.cuda()\n save_pth = osp.join(respth, cp)\n net.load_state_dict(torch.load(save_pth))\n net.eval()\n\n to_tensor = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)),\n ])\n with torch.no_grad():\n for image_path in os.listdir(dspth):\n img = Image.open(osp.join(dspth, image_path))\n image = img.resize((512, 512), Image.BILINEAR)\n img = to_tensor(image)\n img = torch.unsqueeze(img, 0)\n img = img.cuda()\n out = net(img)[0] # shape [1, 19, 512, 512]\n parsing = out.squeeze(0).cpu().numpy().argmax(0) # shape [512, 512]\n # print(parsing)\n # print(np.unique(parsing))\n\n vis_parsing_maps(image, parsing, stride=1, save_im=True, save_path=osp.join(respth, image_path))\n\n\n\n\n\n\n\nif __name__ == \"__main__\":\n os.environ['CUDA_VISIBLE_DEVICES']= '8'\n # evaluate(dspth='/home/data2/DATASET/CelebAMask-HQ/CelebA-HQ-img', cp='Bisenet_13_11600.pth')\n testval(model_path='/home/data2/miles/face_parsing/logs/vschallenges/Bisenet_49_11400.pth')\n\n\n" ]
[ [ "numpy.max", "numpy.array", "numpy.reshape", "numpy.zeros", "torch.no_grad", "torch.unsqueeze", "numpy.where", "torch.squeeze", "numpy.transpose", "torch.utils.data.DataLoader", "torch.load", "numpy.diag", "numpy.maximum" ] ]
HMS-IDAC/PythonPixelClassifier
[ "f8673239a6ee08dbe6968aedea3f632030faf933" ]
[ "imtools.py" ]
[ "import matplotlib.pyplot as plt\nimport tifffile\nimport os\nimport numpy as np\nfrom skimage.io import *\nfrom skimage.filters import gabor_kernel, gabor\nfrom skimage.transform import EuclideanTransform, warp\nfrom scipy.ndimage import *\n\ndef tifread(path):\n return tifffile.imread(path)\n\ndef tifwrite(I,path):\n tifffile.imsave(path, I)\n\ndef imshow(I,**kwargs):\n if not kwargs:\n plt.imshow(I,cmap='gray')\n else:\n plt.imshow(I,**kwargs)\n \n plt.axis('off')\n plt.show()\n\ndef imshowlist(L,**kwargs):\n n = len(L)\n for i in range(n):\n plt.subplot(1, n, i+1)\n if not kwargs:\n plt.imshow(L[i],cmap='gray')\n else:\n plt.imshow(L[i],**kwargs)\n plt.axis('off')\n plt.show()\n\ndef imwrite(I,path):\n imsave(path,I)\n\ndef im2double(I):\n if I.dtype == 'uint16':\n return I.astype('float64')/65535\n elif I.dtype == 'uint8':\n return I.astype('float64')/255\n elif I.dtype == 'float32':\n return I.astype('float64')\n elif I.dtype == 'float64':\n return I\n else:\n print('returned original image type: ', I.dtype)\n return I\n\ndef size(I):\n return list(I.shape)\n\ndef normalize(I):\n m = np.min(I)\n M = np.max(I)\n if M > m:\n return (I-m)/(M-m)\n else:\n return I\n\ndef snormalize(I):\n m = np.mean(I)\n s = np.std(I)\n if s > 0:\n return (I-m)/s\n else:\n return I\n\ndef imgaussfilt(I,sigma,**kwargs):\n return gaussian_filter(I,sigma,**kwargs)\n\ndef imlogfilt(I,sigma,**kwargs):\n return -gaussian_laplace(I,sigma,**kwargs)\n\ndef imderivatives(I,sigmas):\n if type(sigmas) is not list:\n sigmas = [sigmas]\n nDerivatives = len(sigmas)*8 # d0,dx,dy,dxx,dxy,dyy,sqrt(dx^2+dy^2),sqrt(dxx^2+dyy^2)\n sI = size(I)\n D = np.zeros((sI[0],sI[1],nDerivatives))\n for i in range(len(sigmas)):\n sigma = sigmas[i]\n D[:,:,8*i ] = imgaussfilt(I,sigma)\n D[:,:,8*i+1] = imgaussfilt(I,sigma,order=[0,1])\n D[:,:,8*i+2] = imgaussfilt(I,sigma,order=[1,0])\n D[:,:,8*i+3] = imgaussfilt(I,sigma,order=[0,2])\n D[:,:,8*i+4] = imgaussfilt(I,sigma,order=[1,1])\n D[:,:,8*i+5] = imgaussfilt(I,sigma,order=[2,0])\n D[:,:,8*i+6] = np.sqrt(D[:,:,8*i+1]**2+D[:,:,8*i+2]**2)\n D[:,:,8*i+7] = np.sqrt(D[:,:,8*i+3]**2+D[:,:,8*i+5]**2)\n return D\n\ndef circcentlikl(I,radius,scale=2,n0piAngles=8):\n angles = np.arange(0,np.pi,np.pi/n0piAngles)\n A = np.zeros(I.shape)\n for i in range(len(angles)):\n angle = angles[i]\n K = gabor_kernel(1/scale,angle).imag\n J = convolve(I,K)\n dx = -radius*np.cos(angle)\n dy = -radius*np.sin(angle)\n T = EuclideanTransform(translation=(-dx,-dy))\n L1 = warp(J,T)\n T = EuclideanTransform(translation=(dx,dy))\n L2 = warp(-J,T)\n\n # imshowlist([I, resize(K,J.shape), J, np.multiply(L1,L1 > 0), np.multiply(L2,L2 > 0)])\n A += np.multiply(L1,L1 > 0)+np.multiply(L2,L2 > 0)\n return A\n\ndef circlikl(I,radii,scale=2,n0piAngles=8,thr=0.75,dst=0.25):\n # warning: radii should either be a number or a python list (not a numpy array)\n C1 = np.zeros(I.shape)\n C2 = np.zeros(I.shape)\n if type(radii) is not list:\n radii = [radii]\n for i in range(len(radii)):\n radius = radii[i]\n A = circcentlikl(I,radius,scale,n0piAngles)\n Cr1 = np.zeros(I.shape)\n Cr2 = np.zeros(I.shape)\n r0,c0 = np.where(A > thr*np.max(A))\n for j in range(len(r0)):\n A0 = A[r0[j],c0[j]]\n for angle in np.arange(0,2*np.pi,1/radius):\n row = int(np.round(r0[j]+radius*np.cos(angle)))\n col = int(np.round(c0[j]+radius*np.sin(angle)))\n if row > -1 and row < I.shape[0] and col > -1 and col < I.shape[1]:# and I[row,col] > 15:\n Cr1[row,col] += A0\n # Cr1[row,col] = np.max([Cr1[row,col],A0])\n rs = np.arange(1,radii[i]+1,1)\n rs = rs[np.where(np.random.rand(len(rs)) < dst)]\n for r in rs:\n angles = np.arange(0,2*np.pi,1/r);\n angles = angles[np.where(np.random.rand(len(angles)) < dst)]\n for angle in angles:\n row = int(np.round(r0[j]+r*np.cos(angle)))\n col = int(np.round(c0[j]+r*np.sin(angle)))\n if row > -1 and row < I.shape[0] and col > -1 and col < I.shape[1]:\n Cr2[row,col] += A0\n # Cr2[row,col] = np.max([Cr2[row,col],A0])\n C1 = np.maximum(C1,Cr1)\n C2 = np.maximum(C2,Cr2)\n CL = np.zeros((I.shape[0],I.shape[1],2))\n CL[:,:,0] = imgaussfilt(C1,scale)\n CL[:,:,1] = imgaussfilt(C2,scale)\n return CL\n\ndef imfeatures(I=[],sigmaDeriv=1,sigmaLoG=1,cfRadii=[],cfSigma=2,cfThr=0.75,cfDst=0.25,justfeatnames=False):\n # warning: cfRadii should either be a number or a python list (not a numpy array)\n if type(sigmaDeriv) is not list:\n sigmaDeriv = [sigmaDeriv]\n if type(sigmaLoG) is not list:\n sigmaLoG = [sigmaLoG]\n if type(cfRadii) is not list:\n cfRadii = [cfRadii]\n nDerivFeats = len(sigmaDeriv)*8\n nLoGFeats = len(sigmaLoG)\n nCircFeats = len(cfRadii)*2\n nFeatures = nDerivFeats+nLoGFeats+nCircFeats\n if justfeatnames == True:\n featNames = []\n derivNames = ['d0','dx','dy','dxx','dxy','dyy','normD1','normD2']\n for i in range(len(sigmaDeriv)):\n for j in range(len(derivNames)):\n featNames.append('derivSigma%d%s' % (sigmaDeriv[i],derivNames[j]))\n for i in range(len(sigmaLoG)):\n featNames.append('logSigma%d' % sigmaLoG[i])\n for i in range(len(cfRadii)):\n featNames.append('cfRad%dCirc' % cfRadii[i])\n featNames.append('cfRad%dDisk' % cfRadii[i])\n return featNames\n sI = size(I)\n F = np.zeros((sI[0],sI[1],nFeatures))\n F[:,:,:nDerivFeats] = imderivatives(I,sigmaDeriv)\n for i in range(nLoGFeats):\n F[:,:,nDerivFeats+i] = imlogfilt(I,sigmaLoG[i])\n for i in range(len(cfRadii)):\n F[:,:,nDerivFeats+nLoGFeats+2*i:nDerivFeats+nLoGFeats+2*(i+1)] = circlikl(I,cfRadii[i],scale=cfSigma,thr=cfThr,dst=cfDst)\n return F\n\ndef stack2list(S):\n L = []\n for i in range(size(S)[2]):\n L.append(S[:,:,i])\n return L" ]
[ [ "numpy.max", "matplotlib.pyplot.subplot", "numpy.sin", "numpy.zeros", "numpy.min", "numpy.mean", "numpy.multiply", "numpy.std", "numpy.arange", "numpy.sqrt", "numpy.maximum", "numpy.cos", "matplotlib.pyplot.show", "matplotlib.pyplot.axis", "matplotlib.pyplot.imshow" ] ]
madsankern/DynamicProgramming
[ "0812b844068c33b2529d4b11940f9c89582bc374" ]
[ "Archive/Mads_Wind/vfi.py" ]
[ "import numpy as np\nimport tools\nimport utility as util\nimport scipy.optimize as optimize\nimport matplotlib.pyplot as plt\n\n##############################\n## Value function iteration ##\n##############################\n# This is the VFI algortihm for solving the simple consumption saving model.\n\ndef solve(sol, par, v_next, state1, state2):\n\n # Loop over asset grid\n for m_i,m in enumerate(par.grid_m):\n\n # FUNCTIONS BELOW CAN BE WRITTEN AS LOOP - for i=0,1 - AND BE STORED IN AN ARRAY/LIST WITH TWO ENTRIES - a la res[i]=optimize.minimize....\n\n # Minimize the minus the value function wrt consumption conditional on unemployment state\n obj_fun = lambda x : - value_of_choice(x,m,par.grid_m,v_next[0,:],par,state1)\n res_1 = optimize.minimize_scalar(obj_fun, bounds=[0+1.0e-4, m+1.0e-4], method='bounded')\n\n # Minimize the minus the value function wrt consumption conditional on employment state\n obj_fun = lambda x : - value_of_choice(x,m,par.grid_m,v_next[1,:],par,state2)\n res_2 = optimize.minimize_scalar(obj_fun, bounds=[0+1.0e-4, m+1.0e-4], method='bounded')\n \n # Unpack solutions\n # State 1\n sol.v[0,m_i] = -res_1.fun\n sol.c[0,m_i] = res_1.x\n\n # State 2\n sol.v[1,m_i] = -res_2.fun\n sol.c[1,m_i] = res_2.x\n\n return sol\n\n# Function that returns value of consumption choice conditional on the state\ndef value_of_choice(x,m,m_next,v_next,par,state):\n \n # Unpack consumption (choice variable)\n c = x\n\n m_plus = par.y + (1 + par.r)*(m - c)\n\n v_plus = tools.interp_linear_1d(m_next, v_next, m_plus) # Returns one point for each state\n\n Ev_next = np.sum(par.P[state]*v_plus)\n\n # Value of choice given choice c = x\n value = util.u(c,par) + par.beta * Ev_next\n\n return value\n\n#####################################\n## Nested value function iteration ##\n#####################################\n# This is the nested VFI algorithm for solving the discrete-continuous model.\n# The solution method is to solve the keeper problem where consumption is the only choice,\n# then solve the adjuster problem and find the implied value by interpolating\n# the solution of the keeper problem\n\n# Objective function for the keeper\ndef obj_keep(arg, n, m, v_next, par):\n\n # Unpack\n c = arg\n\n # End of period assets\n m_plus = (1+par.r)*(m - c) + par.y1\n\n # Continuation value\n v_plus = tools.interp_linear_1d_scalar(par.grid_m, v_next, m_plus)\n\n # Value of choice\n value = util.u_h(c,n,par) + par.beta*v_plus\n\n return value\n\n# Solution algorithm\ndef solve_dc(sol, par, v_next, c_next, h_next):\n\n # a. Solve the keeper problem\n\n shape = (2,np.size(par.grid_m)) # Row for each state of housing - move to model.py file\n\n # Intialize\n v_keep = np.zeros(shape) + np.nan\n c_keep = np.zeros(shape) + np.nan\n h_keep = np.zeros(shape) + np.nan\n\n # Loop over housing states\n for n in range(2):\n\n # Loop over asset grid\n for m_i,m in enumerate(par.grid_m):\n\n # High and low bounds\n c_low = 1e-4 #np.fmin(m/2,1e-6)\n c_high = m\n\n # Call optimizer\n obj_fun = lambda arg : - obj_keep(arg, n, m, v_next[n,:], par)\n res = optimize.minimize_scalar(obj_fun, bounds = [c_low,c_high], method = 'bounded')\n \n # Unpack solution\n v_keep[n,m_i] = -res.fun\n c_keep[n,m_i] = res.x\n h_keep[n,m_i] = n\n\n ## For debugging ##\n # plt.plot(par.grid_m,c_keep[1])\n # plt.plot(par.grid_m,c_keep[0])\n # plt.show()\n\n # b. Solve the adjuster problem\n\n # Intialize\n v_adj = np.zeros(shape) + np.nan\n c_adj = np.zeros(shape) + np.nan\n h_adj = np.zeros(shape) + np.nan\n\n # Loop over housing state\n for n in range(2):\n\n # Housing choice is reverse of state n if adjusting\n h = 1 - n\n\n # Loop over asset grid\n for m_i,m in enumerate(par.grid_m):\n\n # If adjustment is not possible\n if n == 0 and m < par.ph :\n v_adj[n,m_i] = -np.inf\n c_adj[n,m_i] = 0\n h_adj[n,m_i] = np.nan\n\n else:\n\n # Assets available after adjusting\n x = m - par.ph*(h - n)\n\n # Value of choice\n v_adj[n,m_i] = tools.interp_linear_1d_scalar(par.grid_m, v_keep[h,:], x)\n c_adj[n,m_i] = tools.interp_linear_1d_scalar(par.grid_m, c_keep[h,:], x)\n h_adj[n,m_i] = h\n\n # c. Combine solutions\n\n # Loop over asset grid again\n for n in range(2):\n for m_i,m in enumerate(par.grid_m):\n\n # If keeping is optimal\n if v_keep[n,m_i] > v_adj[n,m_i]:\n sol.v[n,m_i] = v_keep[n,m_i]\n sol.c[n,m_i] = c_keep[n,m_i]\n sol.h[n,m_i] = n\n\n # If ajusting is optimal\n else:\n sol.v[n,m_i] = v_adj[n,m_i]\n sol.c[n,m_i] = c_adj[n,m_i]\n sol.h[n,m_i] = 1 - n\n \n return sol\n\n" ]
[ [ "numpy.sum", "numpy.size", "numpy.zeros", "scipy.optimize.minimize_scalar" ] ]
eng-tools/sfsimodels
[ "4771f7693c7ed30c05e82e41401c7d141e02dcf9" ]
[ "sfsimodels/scores.py" ]
[ "import numpy as np\n\n\ndef lc_score(value):\n \"\"\"\n Evaluates the accuracy of a predictive measure (e.g. r-squared)\n\n :param value: float, between 0.0 and 1.0.\n :return:\n \"\"\"\n rebased = 2 * (value - 0.5)\n\n if rebased == 0:\n return 0\n elif rebased > 0:\n compliment = 1.0 - rebased\n score = - np.log2(compliment)\n else:\n compliment = 1.0 + rebased\n score = np.log2(compliment)\n return score\n\n\n# def show_scores():\n# print(lc_score(0.2))\n#\n# r_vals = 1.0 - np.logspace(-4, -0.01)\n# scores = []\n# print(r_vals)\n# for r in r_vals:\n# scores.append(lc_score(r))\n#\n# plt.plot(r_vals, scores)\n# plt.show()\n#\n# if __name__ == '__main__':\n# show_scores()\n" ]
[ [ "numpy.log2" ] ]
Zhangchangh/oneflow
[ "4ea3935458cc83dcea0abd88dd613f09c57dc01a" ]
[ "python/oneflow/test/modules/test_flip.py" ]
[ "\"\"\"\nCopyright 2020 The OneFlow Authors. All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n\nimport unittest\nfrom collections import OrderedDict\n\nimport numpy as np\nfrom automated_test_util import *\nfrom test_util import GenArgList\n\nimport oneflow as flow\nimport oneflow.unittest\n\n\ndef _test_flip(test_case, device):\n np_arr = np.arange(0, 16).reshape((2, 2, 2, 2)).astype(np.float32)\n input = flow.Tensor(np_arr, device=flow.device(device), requires_grad=True)\n out = flow.flip(input, [0, 1, 2])\n np_out = [\n [[[14.0, 15.0], [12.0, 13.0]], [[10.0, 11.0], [8.0, 9.0]]],\n [[[6.0, 7.0], [4.0, 5.0]], [[2.0, 3.0], [0.0, 1.0]]],\n ]\n test_case.assertTrue(np.allclose(out.numpy(), np_out, 1e-05, 1e-05))\n out = out.sum()\n out = out.backward()\n np_grad = np.ones_like(np_arr)\n test_case.assertTrue(np.allclose(input.grad.numpy(), np_grad, 1e-05, 1e-05))\n\n\nclass TestFlip(flow.unittest.TestCase):\n def test_flip(test_case):\n arg_dict = OrderedDict()\n arg_dict[\"test_fun\"] = [_test_flip]\n arg_dict[\"device\"] = [\"cpu\", \"cuda\"]\n for arg in GenArgList(arg_dict):\n arg[0](test_case, *arg[1:])\n\n\nif __name__ == \"__main__\":\n unittest.main()\n" ]
[ [ "numpy.ones_like", "numpy.arange" ] ]
markcx/DER_ControlPrivateTimeSeries
[ "16f9ea14dc5146005c1c88e9b880c10c9b1a3361" ]
[ "CaseStudy_Synthetic/nets.py" ]
[ "# ============================= #\n# @auther markcx'At'stanford.edu\n# ============================= #\n\nimport torch\nfrom torch import nn\nimport math\n\nimport sys\nsys.path.append(\"..\")\n\ntry:\n import OptMiniModule.util as ut\n import OptMiniModule.cvx_runpass as OptMini_cvx\nexcept:\n raise FileNotFoundError(\"== Opt module util import error! ==\")\n\ntry:\n import basic_util as bUtil\n import losses as bLosses\nexcept:\n raise ModuleNotFoundError(\"== basic_util file is not imported! ==\")\n\n# ===========================\n# neural network models\n# ===========================\n\nclass Classifier(nn.Module):\n def __init__(self, z_dim=10, y_dim=0):\n super(Classifier, self).__init__()\n self.z_dim = z_dim\n self.y_dim = y_dim\n self.net = nn.Sequential(\n nn.Linear(z_dim, 15),\n nn.ELU(),\n nn.Linear(15, y_dim)\n # nn.Linear(z_dim, y_dim),\n )\n\n def forward(self, x):\n o = self.net(x)\n return o\n\n\nclass ClassifierLinear(nn.Module):\n def __init__(self, z_dim=10, y_dim=0):\n super(ClassifierLinear, self).__init__()\n self.z_dim = z_dim\n self.y_dim = y_dim\n self.net = nn.Sequential(\n nn.Linear(z_dim, y_dim),\n # nn.ELU(),\n # nn.Linear(15, y_dim)\n # nn.Linear(z_dim, y_dim),\n )\n\n def forward(self, x):\n o = self.net(x)\n return o\n\n\n\nclass LinearFilter(nn.Module):\n def __init__(self, input_dim = 10, y_dim=0, output_dim=10, bias=None, mask=None):\n super(LinearFilter, self).__init__()\n self.input_dim = input_dim\n self.y_dim = y_dim\n self.output_dim = output_dim\n if mask is None:\n self.fc = nn.Linear(self.input_dim + self.y_dim, self.output_dim, bias=bias)\n elif isinstance(mask, torch.Tensor):\n self.fc = CustomizedLinear(mask, bias=bias)\n else:\n raise NotImplementedError(\"support linear layer with masked entries, \"\n \"not ready for {}\".format(mask))\n\n def forward(self, x, y=None):\n \"\"\"\n\n :param x: input the feature vectors\n :param y: the default y input would be one-hot encoding version of discrete labels\n :return:\n \"\"\"\n xy = x if y is None else torch.cat([x, y], dim=1)\n o = self.fc(xy)\n return o\n\n\n#################################\n## A new diag module framework ##\n#################################\n# Define customized autograd function for masked connection.\n# referred: https://github.com/uchida-takumi/CustomizedLinear\n\nclass CustomizedLinearFunction(torch.autograd.Function):\n \"\"\"\n autograd function which masks it's weights by 'mask'.\n \"\"\"\n\n # Note that both forward and backward are @staticmethods\n @staticmethod\n # bias, mask is an optional argument\n def forward(ctx, input, weight, bias=None, mask=None):\n if mask is not None:\n # change weight to 0 where mask == 0\n # print(\"forward mask : {}\".format(mask.shape))\n weight = weight * mask\n # output = input.mm(weight.t())\n output = input.mm(weight)\n if bias is not None:\n output += bias.unsqueeze(0).expand_as(output)\n ctx.save_for_backward(input, weight, bias, mask)\n return output\n\n # This function has only a single output, so it gets only one gradient\n @staticmethod\n def backward(ctx, grad_output):\n # This is a pattern that is very convenient - at the top of backward\n # unpack saved_tensors and initialize all gradients w.r.t. inputs to\n # None. Thanks to the fact that additional trailing Nones are\n # ignored, the return statement is simple even when the function has\n # optional inputs.\n input, weight, bias, mask = ctx.saved_tensors\n grad_input = grad_weight = grad_bias = grad_mask = None\n\n # These needs_input_grad checks are optional and there only to\n # improve efficiency. If you want to make your code simpler, you can\n # skip them. Returning gradients for inputs that don't require it is\n # not an error.\n if ctx.needs_input_grad[0]:\n grad_input = grad_output.mm(weight)\n if ctx.needs_input_grad[1]:\n # print(grad_output, grad_output.shape)\n # print(\"==\"*20)\n # print(input, input.shape)\n # raise NotImplementedError\n grad_weight = grad_output.t().mm(input)\n if mask is not None:\n # change grad_weight to 0 where mask == 0\n # raise NotImplementedError(grad_weight.shape, mask.shape)\n grad_weight = grad_weight.t() * mask\n #if bias is not None and ctx.needs_input_grad[2]:\n if ctx.needs_input_grad[2]:\n grad_bias = grad_output.sum(0).squeeze(0)\n\n return grad_input, grad_weight, grad_bias, grad_mask\n\n\nclass CustomizedLinear(nn.Module):\n def __init__(self, mask, bias=True):\n \"\"\"\n extended torch.nn module which mask connection.\n Argumens\n ------------------\n mask [torch.tensor]:\n the shape is (n_input_feature, n_output_feature).\n the elements are 0 or 1 which declare un-connected or\n connected.\n bias [bool]:\n flg of bias.\n \"\"\"\n super(CustomizedLinear, self).__init__()\n self.input_features = mask.shape[0]\n self.output_features = mask.shape[1]\n if isinstance(mask, torch.Tensor):\n self.mask = mask.type(torch.float).t()\n # self.mask = mask.type(torch.float)\n else:\n self.mask = torch.tensor(mask, dtype=torch.float).t()\n # self.mask = torch.tensor(mask, dtype=torch.float)\n\n self.mask = nn.Parameter(self.mask, requires_grad=False)\n\n # nn.Parameter is a special kind of Tensor, that will get\n # automatically registered as Module's parameter once it's assigned\n # as an attribute. Parameters and buffers need to be registered, or\n # they won't appear in .parameters() (doesn't apply to buffers), and\n # won't be converted when e.g. .cuda() is called. You can use\n # .register_buffer() to register buffers.\n # nn.Parameters require gradients by default.\n self.weight = nn.Parameter(torch.Tensor(self.output_features, self.input_features))\n # self.weight = nn.Parameter(torch.Tensor(self.input_features, self.output_features))\n\n if bias:\n self.bias = nn.Parameter(torch.Tensor(self.output_features))\n else:\n # You should always register all possible parameters, but the\n # optional ones can be None if you want.\n self.register_parameter('bias', None)\n self.reset_parameters()\n\n # mask weight\n self.weight.data = self.weight.data * self.mask\n\n def reset_parameters(self):\n stdv = 1. / math.sqrt(self.weight.size(1))\n self.weight.data.uniform_(-stdv, stdv)\n if self.bias is not None:\n self.bias.data.uniform_(-stdv, stdv)\n\n\n def forward(self, input):\n # See the autograd section for explanation of what happens here.\n return CustomizedLinearFunction.apply(input, self.weight, self.bias, self.mask)\n\n def extra_repr(self):\n # (Optional)Set the extra information about this module. You can test\n # it by printing an object of this class.\n return 'input_features={}, output_features={}, bias={}'.format(\n self.input_features, self.output_features, self.bias is not None\n )\n\n\n\n\n\n\nclass Generator(nn.Module):\n def __init__(self, nn='v1', name='g_filter', z_dim=24, y_priv_dim=2,\n Q=None, G=None, h=None, A=None, b=None, T=24, p=None, mask=None,\n device=None, n_job=1):\n\n super().__init__()\n self.name = name\n self.z_dim = z_dim\n self.y_priv_dim = y_priv_dim\n self._set_convex_prob_param(p, Q, G, h, A, b, T)\n self.device = device\n self.n_job = n_job\n self.has_mask = 1 if isinstance(mask, torch.Tensor) else 0\n # create a linear filter\n self.filter = LinearFilter(self.z_dim, self.y_priv_dim, output_dim=self.z_dim, mask=mask, bias=None) # setting noise dim is same as latent dim\n\n # Set prior as fixed parameter attached to module\n self.z_prior_m = torch.nn.Parameter(torch.zeros(1), requires_grad=False)\n self.z_prior_v = torch.nn.Parameter(torch.ones(1), requires_grad=False)\n self.z_prior = (self.z_prior_m, self.z_prior_v)\n\n\n def _set_convex_prob_param(self, p, Q, G, h, A, b, T):\n self.p = p # usually won't use self.p\n self.Q = Q\n self.G = G\n self.h = h\n self.A = A\n self.b = b\n self.T = T\n self.cached_noise = None\n self.cached_D_priv = None\n\n\n def forward(self, x, y=None):\n batch_size = x.size()[0] # batch size is the first dimension\n\n z_noise = self.sample_z(batch=batch_size)\n z_noise = z_noise / z_noise.norm(2, dim=1).unsqueeze(1).repeat(1, self.z_dim)\n\n x_proc_noise = self.filter(z_noise, y)\n x_noise = x + x_proc_noise\n # x_noise = torch.clamp(x_noise, min=0)\n return x_noise, z_noise\n\n def sample_z(self, batch):\n return ut.sample_gaussian(self.z_prior[0].expand(batch, self.z_dim),\n self.z_prior[1].expand(batch, self.z_dim))\n\n def solve_convex_forumation(self, p, D, Q, G, h, A, b, Y_onehot=None, n_job=10):\n batch_size = D.shape[0]\n D_ = D\n\n def __expand_param_list(x):\n return [ut.to_np(x) for i in range(batch_size)]\n\n Qs, Gs, hs, As, bs = list(map(__expand_param_list, [Q, G, h, A, b])) # to numpy\n p = ut.to_np(p)\n D_detached = ut.to_np(D_.detach())\n\n res = OptMini_cvx.forward_conic_D_batch(Qs, Gs, hs, As, bs, D_detached, self.T, p=p, n_jobs=n_job)\n\n x_sols = bUtil._convert_to_np_arr(res, 0)\n diff_D = bUtil._convert_to_np_arr(res, 1) # it's minus d (neg demand )\n\n return diff_D, x_sols\n\n def evaluate_cost_obj(self, x_sols, D_, p=None):\n # Q = self.Q\n T = self.T\n # return bLosses.objective_task_loss(p, x_sols, D_, Q, T)\n return bLosses.objective_task_loss_linear(p, x_sols, D_, T)\n\n def evaluate_cost_grad(self, x_sol, D, p=None, dD=None, cat_noise=None):\n Q = self.Q\n T = self.T\n avg_grad = bLosses.grad_dldxdD(p, x_sol, D, Q, dD, cat_noise, T)\n return avg_grad\n\n def evaluate_cost_grad_diag(self, x_sol, D, p=None, dD=None, cat_noise=None):\n Q = self.Q\n T = self.T\n return bLosses.grad_dldxdD_diag(p, x_sol, D, Q, dD, cat_noise, T)\n\n\n def _objective_vals_setter(self, obj_raw, obj_priv):\n self.obj_raw = obj_raw\n self.obj_priv = obj_priv\n\n def _objective_vals_getter(self):\n return self.obj_raw, self.obj_priv\n\n def _ctrl_decisions_setter(self, x_raw_ctrl, x_priv_ctrl):\n self.x_raw_ctrl = x_raw_ctrl\n self.x_priv_ctrl = x_priv_ctrl\n\n def _ctrl_decisions_getter(self):\n return self.x_raw_ctrl, self.x_priv_ctrl\n\n def util_loss(self, D, D_priv, z_noise, Y_onehot, p=None, prior=None):\n if p is None:\n p = self.p\n\n d_Xd, x_sol_raw = self.solve_convex_forumation(p, D, self.Q, self.G, self.h, self.A, self.b, Y_onehot=None,\n n_job=self.n_job)\n d_Xd_priv, x_sol_priv = self.solve_convex_forumation(p, D_priv, self.Q, self.G, self.h, self.A, self.b, Y_onehot=None,\n n_job=self.n_job)\n\n [d_Xd_priv, x_sol_raw, x_sol_priv] = [torch.from_numpy(x).to(torch.float) for x in \\\n [d_Xd_priv, x_sol_raw, x_sol_priv]]\n\n cat_noise_ = torch.cat([z_noise, Y_onehot], dim=1)\n if self.has_mask == 0:\n grad = self.evaluate_cost_grad(x_sol_priv, D, p, d_Xd_priv, cat_noise_)\n elif self.has_mask == 1:\n grad = self.evaluate_cost_grad_diag(x_sol_priv, D, p, dD=d_Xd_priv, cat_noise=cat_noise_)\n else:\n raise NotImplementedError(\"NOT supported for the value {}\".format(self.has_mask))\n\n\n obj_priv = self.evaluate_cost_obj(x_sol_priv, D_=D, p=p)\n obj_raw = self.evaluate_cost_obj(x_sol_raw, D_=D, p=p)\n\n self._objective_vals_setter(obj_raw, obj_priv)\n self._ctrl_decisions_setter(x_sol_raw, x_sol_priv)\n\n w_r, w_c = self.filter.fc.weight.shape # decouple the weight matrix rows and columns\n GAMMA = self.filter.fc.weight[:, :self.T] if w_r == self.T else self.filter.fc.weight[:self.T, :]\n bias_vec = self.filter.fc.weight[:, self.T:].mm(prior) if w_r == self.T else (self.filter.fc.weight[self.T:, :].t()).mm(prior)\n distortion = torch.norm(GAMMA, p='fro')**2 + torch.norm(bias_vec, p=2)**2\n\n return obj_priv, grad, distortion\n" ]
[ [ "torch.nn.Linear", "torch.zeros", "torch.cat", "torch.norm", "torch.nn.Parameter", "torch.ones", "torch.from_numpy", "torch.tensor", "torch.Tensor", "torch.nn.ELU" ] ]
shym98/DNA_circuits
[ "6882adece5b2b70317d47e2495d91890606c6982" ]
[ "testDNA/main.py" ]
[ "import networkx as nx\nimport matplotlib.pyplot as plt\nimport sys\nfrom testDNA.DNA import generate_output\n\ninput_logic = \"\"\nerrors = False\nvariables = []\n\n\ndef check_parenthesis(expr):\n stack = []\n global errors\n for i in range(len(expr)):\n if expr[i] == '(':\n stack.append(i)\n else:\n if expr[i] == ')':\n if len(stack) == 0:\n errors = True\n return False\n if stack[len(stack) - 1] == 0 and i == len(expr) - 1:\n return True\n stack.pop()\n if len(stack) != 0:\n errors = True\n return False\n\n\ndef find_operator(expr, operator_type):\n \"\"\"operator_type:\n 1 - NOT\n 2 - OR\n 3 - XOR\n 4 - AND\"\"\"\n\n if operator_type == 1:\n if expr[0] == '!':\n return 0\n else:\n return -1\n\n parenthesis_count = 0\n\n for i in range(len(expr) - 1, 0, -1):\n if expr[i] == ')':\n parenthesis_count += 1\n else:\n if expr[i] == '(':\n parenthesis_count -= 1\n else:\n if parenthesis_count == 0:\n if (operator_type == 4 and expr[i] == '&') or (operator_type == 3 and expr[i] == '^') or \\\n (operator_type == 2 and expr[i] == '|'):\n return i\n\n return -1\n\n\noperators = ['!', '|', '^', '&', '⊼']\n\n\ndef parse(expr):\n global errors\n\n if len(expr) == 0:\n errors = True\n return ()\n\n while check_parenthesis(expr):\n expr = expr[1:-1]\n\n for i in range(2, 5):\n if find_operator(expr, i) != -1:\n return (operators[i - 1], parse(expr[0:find_operator(expr, i)]),\n parse(expr[find_operator(expr, i) + 1:]))\n if find_operator(expr, 1) != -1:\n return operators[0], parse(expr[1:])\n\n if errors:\n return ()\n\n for i in operators:\n if i in expr:\n errors = True\n return ()\n\n if expr not in variables:\n variables.append(expr)\n\n return expr\n\n\noperators_count = [0, 0, 0, 0, 0]\nG = nx.Graph()\nnodes = []\nedges = []\nlabels = {}\n\n\ndef convert_to_graph(parse_expr, prev=''):\n if type(parse_expr) == tuple:\n operator = parse_expr[0]\n node_label = operator\n operators_count[operators.index(operator)] += 1\n operator += str(operators_count[operators.index(operator)])\n\n nodes.append(operator)\n labels[operator] = node_label\n if prev != '':\n edges.append((prev, operator))\n\n arguments = []\n for i in range(1, len(parse_expr)):\n arguments.append(parse_expr[i])\n for i in arguments:\n convert_to_graph(i, operator)\n else:\n nodes.append(parse_expr)\n labels[parse_expr] = parse_expr\n if prev != '':\n edges.append((prev, parse_expr))\n\n\ndef draw_graph(parse_result):\n convert_to_graph(parse_result)\n G.add_nodes_from(nodes)\n G.add_edges_from(edges)\n pos = nx.spring_layout(G)\n nx.draw_networkx_nodes(G, pos)\n nx.draw_networkx_edges(G, pos)\n nx.draw_networkx_labels(G, pos, labels, font_size=16)\n plt.savefig(\"simple_path.png\")\n plt.show()\n\n\ndef replace_to_nand_logic(expr):\n if type(expr) == tuple:\n operator = expr[0]\n if operator == '!':\n return ('⊼', replace_to_nand_logic(expr[1]), replace_to_nand_logic(expr[1]))\n elif operator == '&':\n first_gate = ('⊼', replace_to_nand_logic(expr[1]), replace_to_nand_logic(expr[2]))\n return ('⊼', first_gate, first_gate)\n elif operator == '|':\n first_gate = ('⊼', replace_to_nand_logic(expr[1]), replace_to_nand_logic(expr[1]))\n second_gate = ('⊼', replace_to_nand_logic(expr[2]), replace_to_nand_logic(expr[2]))\n return ('⊼', first_gate, second_gate)\n else:\n first_gate = ('⊼', replace_to_nand_logic(expr[1]), replace_to_nand_logic(expr[2]))\n second_gate = ('⊼', replace_to_nand_logic(expr[1]), first_gate)\n third_gate = ('⊼', first_gate, replace_to_nand_logic(expr[2]))\n return ('⊼', second_gate, third_gate)\n else:\n return expr\n\n\nvalues = {}\n\n\ndef get_input_values():\n for var in variables:\n print(\"Enter\", var, \"value:\")\n input_val = int(input())\n input_val = (False, True)[input_val == 1]\n values[var] = input_val\n\n\ndef DNA_computing_simulation(expr):\n if type(expr) == tuple:\n return generate_output(DNA_computing_simulation(expr[1]), calculate_output(expr[2]))\n else:\n return values[expr]\n\n\ndef calculate_output(expr):\n if type(expr) == tuple:\n return not (calculate_output(expr[1]) and calculate_output(expr[2]))\n else:\n return values[expr]\n\n\ndef check_correctness(input_logic):\n global errors\n errors = False\n logic = parse(input_logic)\n correct_file = open(\"correct.txt\", \"w+\")\n if errors:\n correct_file.write(\"0\")\n else:\n correct_file.write(\"1\")\n var_file = open(\"var.txt\", \"w+\")\n for i in values:\n var_file.write(i)\n\n\ndef reset():\n global errors, values, operators_count, G, nodes, edges, labels, variables\n errors = False\n values = {}\n operators_count = [0, 0, 0, 0, 0]\n G = nx.Graph()\n nodes = []\n edges = []\n labels = {}\n variables = []\n\nif __name__ == 'main':\n args = str(sys.argv)\n args = args[1:]\n reset()\n if args[0] == '-c':\n check_correctness(args[1])\n\n#input_logic = \"!(a1&(b|c&(!v)))\"\n#input_logic = \"a&b|c|(!s&o)\"\n# input_logic = \"a&(b|c)\"\n# logic = parse(input_logic)\n# #draw_graph(logic)\n# get_input_values()\n# nand_logic = replace_to_nand_logic(logic)\n# print(nand_logic)\n# print(\"res:\", calculate_output(nand_logic))\n# print(\"DNA res:\", DNA_computing_simulation(nand_logic))" ]
[ [ "matplotlib.pyplot.savefig", "matplotlib.pyplot.show" ] ]
paulasquin/pixray
[ "9ada7b82c0cb2dd634d5e933a1ac4c5980e8cb1d" ]
[ "pixray/vectorize.py" ]
[ "import argparse\nimport sys\nimport json\nimport numpy as np\nfrom sklearn import metrics\nfrom sklearn import svm\nimport os\nfrom tqdm import tqdm\nfrom util import real_glob\n\nimport torch\nfrom clip import clip\nfrom torchvision.transforms import Compose, Resize, CenterCrop, ToTensor, Normalize\nfrom PIL import Image\n\nfrom pixray.slip import get_clip_perceptor, all_slip_models\n\nperceptors = {}\n\ndef init(args):\n global perceptors, resolutions\n\n device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n\n if args.models is not None:\n # print(\"Running models \", args.models)\n models = args.models.split(\",\")\n args.models = [model.strip() for model in models]\n else:\n args.models = clip.available_models()\n args.models = args.models + all_slip_models\n # print(\"using models \", args.models)\n\n for p_model in args.models:\n perceptor = get_clip_perceptor(p_model, device)\n perceptors[p_model] = perceptor\n\ndef fetch_images(preprocess, image_files):\n images = []\n\n for filename in image_files:\n image = preprocess(Image.open(filename).convert(\"RGB\"))\n images.append(image)\n\n return images\n\ndef do_image_features(model, images):\n image_input = torch.tensor(np.stack(images)).cuda()\n\n with torch.no_grad():\n image_features = model.encode_image(image_input).float()\n\n return image_features\n\ndef spew_vectors(args, inputs, outfile):\n global perceptors, resolutions\n\n input_files = real_glob(inputs)\n save_table = {}\n for clip_model in args.models:\n perceptor = perceptors[clip_model]\n input_resolution = perceptor.input_resolution\n print(f\"Running {clip_model} at {input_resolution}\")\n preprocess = Compose([\n Resize(input_resolution, interpolation=Image.BICUBIC),\n CenterCrop(input_resolution),\n ToTensor()\n ])\n images = fetch_images(preprocess, input_files);\n\n features = do_image_features(perceptor, images)\n print(f\"saving {features.shape} to {clip_model}\")\n save_table[clip_model] = features.tolist()\n\n with open(outfile, 'w') as fp:\n json.dump(save_table, fp)\n\ndef run_avg_diff(args):\n f1, f2 = args.avg_diff.split(\",\")\n with open(f1) as f_in:\n table1 = json.load(f_in)\n with open(f2) as f_in:\n table2 = json.load(f_in)\n save_table = {}\n for k in table1:\n encoded1 = np.array(table1[k])\n encoded2 = np.array(table2[k])\n print(\"Taking the difference between {} and {} vectors\".format(encoded1.shape, encoded2.shape))\n m1 = np.mean(encoded1,axis=0)\n m2 = np.mean(encoded2,axis=0)\n atvec = m2 - m1\n z_dim, = atvec.shape\n atvecs = atvec.reshape(1,z_dim)\n print(\"Computed diff shape: {}\".format(atvecs.shape))\n save_table[k] = atvecs.tolist()\n\n with open(args.outfile, 'w') as fp:\n json.dump(save_table, fp)\n\ndef run_svm_diff(args):\n f1, f2 = args.svm_diff.split(\",\")\n with open(f1) as f_in:\n table1 = json.load(f_in)\n with open(f2) as f_in:\n table2 = json.load(f_in)\n save_table = {}\n for k in table1:\n encoded1 = np.array(table1[k])\n encoded2 = np.array(table2[k])\n print(\"Taking the svm difference between {} and {} vectors\".format(encoded1.shape, encoded2.shape))\n h = .02 # step size in the mesh\n C = 1.0 # SVM regularization parameter\n X_arr = []\n y_arr = []\n for l in range(len(encoded1)):\n X_arr.append(encoded1[l])\n y_arr.append(False)\n for l in range(len(encoded2)):\n X_arr.append(encoded2[l])\n y_arr.append(True)\n X = np.array(X_arr)\n y = np.array(y_arr)\n # svc = svm.LinearSVC(C=C, class_weight=\"balanced\").fit(X, y)\n svc = svm.LinearSVC(C=C,max_iter=20000).fit(X, y)\n # get the separating hyperplane\n w = svc.coef_[0]\n\n #FIXME: this is a scaling hack.\n m1 = np.mean(encoded1,axis=0)\n m2 = np.mean(encoded2,axis=0)\n mean_vector = m1 - m2\n mean_length = np.linalg.norm(mean_vector)\n svn_length = np.linalg.norm(w)\n\n atvec = (mean_length / svn_length) * w\n z_dim, = atvec.shape\n atvecs = atvec.reshape(1,z_dim)\n print(\"Computed svm diff shape: {}\".format(atvecs.shape))\n save_table[k] = atvecs.tolist()\n\n with open(args.outfile, 'w') as fp:\n json.dump(save_table, fp)\n\ndef main():\n parser = argparse.ArgumentParser(description=\"Do vectory things\")\n parser.add_argument(\"--models\", type=str, help=\"CLIP model\", default=None, dest='models')\n parser.add_argument(\"--inputs\", type=str, help=\"Images to process\", default=None, dest='inputs')\n parser.add_argument(\"--avg-diff\", dest='avg_diff', type=str, default=None,\n help=\"Two vector files to average and then diff\")\n parser.add_argument(\"--svm-diff\", dest='svm_diff', type=str, default=None,\n help=\"Two vector files to average and then svm diff\")\n parser.add_argument(\"--z-dim\", dest='z_dim', type=int, default=100,\n help=\"z dimension of vectors\")\n parser.add_argument(\"--encoded-vectors\", type=str, default=None,\n help=\"Comma separated list of json arrays\")\n parser.add_argument(\"--encoded-true\", type=str, default=None,\n help=\"Comma separated list of json arrays (true)\")\n parser.add_argument(\"--encoded-false\", type=str, default=None,\n help=\"Comma separated list of json arrays (false)\")\n parser.add_argument('--thresh', dest='thresh', default=False, action='store_true',\n help=\"Compute thresholds for attribute vectors classifiers\")\n parser.add_argument('--svm', dest='svm', default=False, action='store_true',\n help=\"Use SVM for computing attribute vectors\")\n parser.add_argument(\"--limit\", dest='limit', type=int, default=None,\n help=\"Limit number of inputs when computing atvecs\")\n parser.add_argument(\"--attribute-vectors\", dest='attribute_vectors', default=None,\n help=\"use json file as source of attribute vectors\")\n parser.add_argument(\"--attribute-thresholds\", dest='attribute_thresholds', default=None,\n help=\"use these non-zero values for binary classifier thresholds\")\n parser.add_argument(\"--attribute-set\", dest='attribute_set', default=\"all\",\n help=\"score ROC/accuracy against true/false/all\")\n parser.add_argument('--attribute-indices', dest='attribute_indices', default=None, type=str,\n help=\"indices to select specific attribute vectors\")\n parser.add_argument('--outfile', dest='outfile', default=None,\n help=\"Output json file for vectors.\")\n args = parser.parse_args()\n\n if args.avg_diff:\n run_avg_diff(args)\n sys.exit(0)\n\n if args.svm_diff:\n run_svm_diff(args)\n sys.exit(0)\n\n init(args)\n spew_vectors(args, args.inputs, args.outfile)\n\nif __name__ == '__main__':\n main()" ]
[ [ "numpy.array", "numpy.linalg.norm", "torch.no_grad", "numpy.mean", "torch.cuda.is_available", "numpy.stack", "sklearn.svm.LinearSVC" ] ]
ADockhorn/Forward-Model-Learning-for-Motion-Control-Tasks
[ "46f4fb4bf2c1c8236bea0fa471a1f23381a7a08a" ]
[ "forwardmodellearning/plot_results.py" ]
[ "import matplotlib.pyplot as plt\nimport seaborn as sns\nimport pickle\nimport os\nimport numpy as np\n\n\ndef store_data_into_csv():\n \"\"\" Store training results into CSV files to calculate a smoothed loess with R before plotting.\n \"\"\"\n for ENV_NAME in ['CartPole-v1', 'Pendulum-v0', 'Acrobot-v1', 'LunarLander-v2', 'Swimmer-v2']:\n print(\"processing results of:\", ENV_NAME)\n\n if ENV_NAME in {\"CartPole-v1\", \"Acrobot-v1\", \"LunarLander-v2\"}:\n model_names = [\"DFM\", \"DQN\", \"SARSA\", \"CEM\"]\n else:\n model_names = [\"DFM\", \"NAF\"]\n\n folders = os.listdir(f\"results\\\\{ENV_NAME}\")\n\n histories = {model: [] for model in model_names}\n for folder in folders:\n for model in model_names:\n if os.path.exists(f\"results\\\\{ENV_NAME}\\\\{folder}\\\\training_results_{model}\"):\n try:\n with open(f\"results\\\\{ENV_NAME}\\\\{folder}\\\\training_results_{model}\", \"rb\") as file:\n data = pickle.load(file)\n if isinstance(data, dict):\n histories[model].append(data)\n except Exception:\n pass\n\n colors = sns.color_palette(\"muted\", 8)\n sns.set(style=\"darkgrid\")\n\n for i, model in enumerate(model_names):\n if len(histories[model]) == 0:\n continue\n scatter_data_x = []\n scatter_data_y = []\n end_performance = []\n for history in histories[model]:\n scatter_data_x.extend(history[\"nb_steps\"])\n if model == \"NAF\":\n scatter_data_y.extend([x*100 for x in history[\"episode_reward\"]])\n end_performance.extend([x*100 for x in history[\"episode_reward\"][-10:]])\n else:\n scatter_data_y.extend(history[\"episode_reward\"])\n end_performance.extend(history[\"episode_reward\"][-10:])\n print(model, np.mean(end_performance))\n a = np.array([scatter_data_x, scatter_data_y]).transpose()\n np.savetxt(f\"results\\\\csv\\\\{ENV_NAME}_{model}.csv\", a, \"%4.8f\")\n\n\ndef plot_r_csv_files():\n \"\"\" Plot the csv files return by the R script which includes the loess smoothed values.\n \"\"\"\n for ENV_NAME in ['CartPole-v1', 'Pendulum-v0', 'Acrobot-v1', 'LunarLander-v2', 'Swimmer-v2']:\n print(\"processing results of:\", ENV_NAME)\n\n if ENV_NAME in {\"CartPole-v1\", \"Acrobot-v1\", \"LunarLander-v2\"}:\n model_names = [\"DFM\", \"DQN\", \"SARSA\", \"CEM\"]\n else:\n model_names = [\"DFM\", \"NAF\"]\n\n histories = {model: [] for model in model_names}\n for model in model_names:\n if os.path.exists(f\"results\\\\out\\\\{ENV_NAME}_{model}.csv\"):\n try:\n data = np.genfromtxt(f\"results\\\\out\\\\{ENV_NAME}_{model}.csv\", delimiter=\",\", skip_header=1)\n histories[model] = data\n except Exception:\n pass\n\n colors = sns.color_palette(\"muted\", 8)\n sns.set(style=\"darkgrid\", font_scale=1.3)\n\n cols = 0\n for i, model in enumerate(model_names):\n if len(histories[model]) == 0:\n continue\n if model == \"DDQN\":\n continue\n cols += 1\n x, y, y1, y2 = histories[model][:, 1], histories[model][:, 2], \\\n histories[model][:, 2] - histories[model][:, 3], \\\n histories[model][:, 2] + histories[model][:, 3]\n if model == \"DFM\":\n model = \"DDFM\"\n plt.plot(x, y, c=colors[i], label=model)\n # plt.scatter(scatter_data_x, scatter_data_y)\n # plt.fill_between(x, y1, y2, color=colors[i], alpha=0.2)\n plt.legend()\n plt.xlabel(\"training steps\")\n plt.ylabel(\"average episode return\")\n plt.legend(bbox_to_anchor=(0.5, -0.20), loc=9, borderaxespad=0., ncol=cols, facecolor=\"white\",\n edgecolor=\"white\")\n # plt.title(ENV_NAME)\n plt.tight_layout()\n plt.savefig(f\"results\\\\{ENV_NAME}.png\")\n plt.savefig(f\"results\\\\{ENV_NAME}.pdf\")\n plt.show()\n\n\nif __name__ == \"__main__\":\n # values were smoothed using the loess function of r. please refer to our R-script \"smoother.r\"\n plot_r_csv_files()\n # store_data_into_csv()\n" ]
[ [ "numpy.array", "numpy.savetxt", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.savefig", "matplotlib.pyplot.plot", "matplotlib.pyplot.legend", "numpy.genfromtxt", "numpy.mean", "matplotlib.pyplot.tight_layout", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.show" ] ]
CanItRun/CoMatch
[ "748645d531787502340977e75b48049b629f9e97" ]
[ "Train_CoMatch_a.py" ]
[ "'''\n * Copyright (c) 2018, salesforce.com, inc.\n * All rights reserved.\n * SPDX-License-Identifier: BSD-3-Clause\n * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause\n'''\nfrom __future__ import print_function\nimport random\n\nimport time\nimport argparse\nimport os\nimport sys\nfrom lumo.contrib.nn.loss import contrastive_loss, sup_contrastive_loss, contrastive_loss2\n\nimport numpy as np\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom lumo.proc.path import cache_dir\n\nfrom WideResNet import WideResnet\nfrom datasets.cifar import get_train_loader, get_val_loader\nfrom utils import accuracy, setup_default_logging, AverageMeter, WarmupCosineLrScheduler\n\nfrom lumo import Logger, Meter, AvgMeter\n\nlog = Logger()\nlog.add_log_dir('./log')\n\n\ndef set_model(args):\n model = WideResnet(n_classes=args.n_classes, k=args.wresnet_k, n=args.wresnet_n, proj=True)\n if args.checkpoint:\n checkpoint = torch.load(args.checkpoint)\n msg = model.load_state_dict(checkpoint, strict=False)\n assert set(msg.missing_keys) == {\"classifier.weight\", \"classifier.bias\"}\n print('loaded from checkpoint: %s' % args.checkpoint)\n model.train()\n model.cuda()\n\n if args.eval_ema:\n ema_model = WideResnet(n_classes=args.n_classes, k=args.wresnet_k, n=args.wresnet_n, proj=True)\n for param_q, param_k in zip(model.parameters(), ema_model.parameters()):\n param_k.data.copy_(param_q.detach().data) # initialize\n param_k.requires_grad = False # not update by gradient for eval_net\n ema_model.cuda()\n ema_model.eval()\n else:\n ema_model = None\n\n criteria_x = nn.CrossEntropyLoss().cuda()\n return model, criteria_x, ema_model\n\n\[email protected]_grad()\ndef ema_model_update(model, ema_model, ema_m):\n \"\"\"\n Momentum update of evaluation model (exponential moving average)\n \"\"\"\n for param_train, param_eval in zip(model.parameters(), ema_model.parameters()):\n param_eval.copy_(param_eval * ema_m + param_train.detach() * (1 - ema_m))\n\n for buffer_train, buffer_eval in zip(model.buffers(), ema_model.buffers()):\n buffer_eval.copy_(buffer_train)\n\n\nqueue_ptr = 0\n\n\ndef train_one_epoch(epoch,\n model,\n ema_model,\n prob_list,\n criteria_x,\n optim,\n lr_schdlr,\n dltrain_x,\n dltrain_u,\n args,\n n_iters,\n logger,\n queue_feats,\n queue_probs,\n # queue_ptr,\n dlval=None\n ):\n global queue_ptr\n model.train()\n loss_x_meter = AverageMeter()\n loss_u_meter = AverageMeter()\n loss_contrast_meter = AverageMeter()\n # the number of correct pseudo-labels\n n_correct_u_lbs_meter = AverageMeter()\n # the number of confident unlabeled data\n n_strong_aug_meter = AverageMeter()\n mask_meter = AverageMeter()\n # the number of edges in the pseudo-label graph\n pos_meter = AverageMeter()\n\n epoch_start = time.time() # start time\n dl_x, dl_u = iter(dltrain_x), iter(dltrain_u)\n\n avg = AvgMeter()\n for it in range(1, n_iters + 1):\n meter = Meter()\n (ims_x_weak, _, _), lbs_x = next(dl_x)\n (ims_u_weak, ims_u_strong0, ims_u_strong1), lbs_u_real = next(dl_u)\n\n lbs_x = lbs_x.cuda()\n lbs_u_real = lbs_u_real.cuda()\n\n # --------------------------------------\n bt = ims_x_weak.size(0)\n btu = ims_u_weak.size(0)\n\n imgs = torch.cat([ims_x_weak, ims_u_weak, ims_u_strong0, ims_u_strong1], dim=0).cuda()\n logits, features = model(imgs)\n\n logits_x = logits[:bt]\n logits_u_w, logits_u_s0, logits_u_s1 = torch.split(logits[bt:], btu)\n\n feats_x = features[:bt]\n feats_u_w, feats_u_s0, feats_u_s1 = torch.split(features[bt:], btu)\n\n loss_x = criteria_x(logits_x, lbs_x)\n\n with torch.no_grad():\n logits_u_w = logits_u_w.detach()\n feats_x = feats_x.detach()\n feats_u_w = feats_u_w.detach()\n\n probs = torch.softmax(logits_u_w, dim=1)\n # DA\n prob_list.append(probs.mean(0))\n if len(prob_list) > 32:\n prob_list.pop(0)\n prob_avg = torch.stack(prob_list, dim=0).mean(0)\n probs = probs / prob_avg\n probs = probs / probs.sum(dim=1, keepdim=True)\n\n probs_orig = probs.clone()\n\n if epoch > 0 or it > args.queue_batch: # memory-smoothing\n # A = torch.exp(torch.mm(feats_u_w, queue_feats.t()) / args.temperature)\n # A = A / A.sum(1, keepdim=True) # 概率分布\n A = torch.softmax(torch.mm(feats_u_w, queue_feats.t()) / args.temperature, dim=-1)\n\n sim_prob = torch.mm(A, queue_probs)\n # sim_probs\n probs = args.alpha * probs + (1 - args.alpha) * sim_prob\n meter.mean.As = (sim_prob.argmax(dim=-1) == lbs_u_real).float().mean()\n\n scores, lbs_u_guess = torch.max(probs, dim=1)\n mask = scores.ge(args.thr)\n if mask.any():\n meter.mean.Amop = (probs_orig.argmax(dim=-1) == lbs_u_real)[mask].float().mean()\n meter.mean.Ams = (sim_prob.argmax(dim=-1) == lbs_u_real)[mask].float().mean()\n\n feats_w = torch.cat([feats_u_w, feats_x], dim=0)\n onehot = torch.zeros(bt, args.n_classes).cuda().scatter(1, lbs_x.view(-1, 1), 1)\n probs_w = torch.cat([probs_orig, onehot], dim=0)\n\n # update memory bank\n n = bt + btu\n queue_feats[queue_ptr:queue_ptr + n, :] = feats_w\n queue_probs[queue_ptr:queue_ptr + n, :] = probs_w\n queue_ptr = (queue_ptr + n) % args.queue_size\n\n # embedding similarity\n sim = torch.exp(torch.mm(feats_u_s0, feats_u_s1.t()) / args.temperature)\n sim_probs = sim / sim.sum(1, keepdim=True) # softmax\n\n # pseudo-label graph with self-loop\n Q = torch.mm(probs, probs.t())\n Q.fill_diagonal_(1)\n pos_mask = (Q >= args.contrast_th).float()\n\n Q = Q * pos_mask\n Q = Q / Q.sum(1, keepdim=True)\n\n loss_contrast = contrastive_loss2(feats_u_s0, feats_u_s1, temperature=args.temperature, norm=True, qk_graph=Q)\n\n # contrastive loss\n # loss_contrast = - (torch.log(sim_probs + 1e-7) * Q).sum(1)\n # loss_contrast = loss_contrast.mean()\n\n # unsupervised classification loss\n loss_u = - torch.sum((F.log_softmax(logits_u_s0, dim=1) * probs), dim=1) * mask.float()\n loss_u = loss_u.mean()\n\n loss = loss_x + args.lam_u * loss_u + args.lam_c * loss_contrast\n\n meter.mean.Lall = loss\n meter.mean.Lx = loss_x\n meter.mean.Lu = loss_u\n meter.mean.Lcs = loss_contrast\n with torch.no_grad():\n meter.mean.Pm = pos_mask.float().mean()\n meter.mean.Ax = (logits_x.argmax(dim=-1) == lbs_x).float().mean()\n meter.mean.um = mask.float().mean()\n meter.mean.Au = (logits_u_w.argmax(dim=-1) == lbs_u_real).float().mean()\n if mask.any():\n meter.mean.Aum = (logits_u_w.argmax(dim=-1) == lbs_u_real)[mask].float().mean()\n\n optim.zero_grad()\n loss.backward()\n optim.step()\n lr_schdlr.step()\n\n if args.eval_ema:\n with torch.no_grad():\n ema_model_update(model, ema_model, args.ema_m)\n\n if mask.any():\n corr_u_lb = (lbs_u_guess == lbs_u_real).float()[mask]\n meter.mean.Corr = corr_u_lb.mean()\n # meter.mean.CM = mask.float().mean()\n avg.update(meter)\n log.inline(f'{it}/{n_iters}', avg)\n if it % 150 == 0:\n # evaluate(model, ema_model, dlval)\n # model.train()\n # avg.clear()\n log.newline()\n avg.clear()\n log.newline()\n return loss_x_meter.avg, loss_u_meter.avg, loss_contrast_meter.avg, mask_meter.avg, pos_meter.avg, n_correct_u_lbs_meter, queue_feats, queue_probs, queue_ptr, prob_list\n\n\ndef evaluate(model, ema_model, dataloader):\n model.eval()\n avg = AvgMeter()\n top1_meter = AverageMeter()\n ema_top1_meter = AverageMeter()\n\n with torch.no_grad():\n for ims, lbs in dataloader:\n meter = Meter()\n ims = ims.cuda()\n lbs = lbs.cuda()\n\n logits, _ = model(ims)\n scores = torch.softmax(logits, dim=1)\n top1, top5 = accuracy(scores, lbs, (1, 5))\n top1_meter.update(top1.item())\n meter.sum.A1 = top1\n meter.sum.A5 = top5\n\n if ema_model is not None:\n logits, _ = ema_model(ims)\n scores = torch.softmax(logits, dim=1)\n top1, top5 = accuracy(scores, lbs, (1, 5))\n ema_top1_meter.update(top1.item())\n meter.sum.Ae1 = top1\n meter.sum.Ae5 = top5\n avg.update(meter)\n log.info('TEST', avg)\n return top1_meter.avg, ema_top1_meter.avg\n\n\ndef main():\n parser = argparse.ArgumentParser(description='CoMatch Cifar Training')\n parser.add_argument('--root', default=cache_dir(), type=str, help='dataset directory')\n parser.add_argument('--wresnet-k', default=2, type=int,\n help='width factor of wide resnet')\n parser.add_argument('--wresnet-n', default=28, type=int,\n help='depth of wide resnet')\n parser.add_argument('--dataset', type=str, default='CIFAR10',\n help='number of classes in dataset')\n parser.add_argument('--n-classes', type=int, default=10,\n help='number of classes in dataset')\n parser.add_argument('--n-labeled', type=int, default=40,\n help='number of labeled samples for training')\n parser.add_argument('--n-epoches', type=int, default=512,\n help='number of training epoches')\n parser.add_argument('--batchsize', type=int, default=64,\n help='train batch size of labeled samples')\n parser.add_argument('--mu', type=int, default=7,\n help='factor of train batch size of unlabeled samples')\n parser.add_argument('--n-imgs-per-epoch', type=int, default=64 * 1024,\n help='number of training images for each epoch')\n\n parser.add_argument('--eval-ema', default=True, help='whether to use ema model for evaluation')\n parser.add_argument('--ema-m', type=float, default=0.999)\n\n parser.add_argument('--lam-u', type=float, default=1.,\n help='coefficient of unlabeled loss')\n parser.add_argument('--lr', type=float, default=0.03,\n help='learning rate for training')\n parser.add_argument('--weight-decay', type=float, default=5e-4,\n help='weight decay')\n parser.add_argument('--momentum', type=float, default=0.9,\n help='momentum for optimizer')\n parser.add_argument('--seed', type=int, default=123,\n help='seed for random behaviors, no seed if negtive')\n\n parser.add_argument('--temperature', default=0.2, type=float, help='softmax temperature')\n parser.add_argument('--low-dim', type=int, default=64)\n parser.add_argument('--lam-c', type=float, default=1,\n help='coefficient of contrastive loss')\n parser.add_argument('--contrast-th', default=0.8, type=float,\n help='pseudo label graph threshold')\n parser.add_argument('--thr', type=float, default=0.95,\n help='pseudo label threshold')\n parser.add_argument('--alpha', type=float, default=0.9)\n parser.add_argument('--queue-batch', type=float, default=5,\n help='number of batches stored in memory bank')\n parser.add_argument('--exp-dir', default='CoMatch', type=str, help='experiment id')\n parser.add_argument('--checkpoint', default='', type=str, help='use pretrained model')\n parser.add_argument('--device', default=0, type=int, help='use pretrained model')\n\n args = parser.parse_args()\n\n from torch.cuda import set_device\n set_device(args.device)\n\n logger, output_dir = setup_default_logging(args)\n logger.info(dict(args._get_kwargs()))\n\n # tb_logger = tensorboard_logger.Logger(logdir=output_dir, flush_secs=2)\n\n if args.seed > 0:\n torch.manual_seed(args.seed)\n random.seed(args.seed)\n np.random.seed(args.seed)\n\n n_iters_per_epoch = args.n_imgs_per_epoch // args.batchsize # 1024\n n_iters_all = n_iters_per_epoch * args.n_epoches # 1024 * 200\n\n logger.info(\"***** Running training *****\")\n logger.info(f\" Task = {args.dataset}@{args.n_labeled}\")\n\n model, criteria_x, ema_model = set_model(args)\n logger.info(\"Total params: {:.2f}M\".format(\n sum(p.numel() for p in model.parameters()) / 1e6))\n\n dltrain_x, dltrain_u = get_train_loader(\n args.dataset, args.batchsize, args.mu, n_iters_per_epoch, L=args.n_labeled, root=args.root, method='comatch')\n dlval = get_val_loader(dataset=args.dataset, batch_size=64, num_workers=2, root=args.root)\n\n wd_params, non_wd_params = [], []\n for name, param in model.named_parameters():\n if 'bn' in name:\n non_wd_params.append(param)\n else:\n wd_params.append(param)\n param_list = [\n {'params': wd_params}, {'params': non_wd_params, 'weight_decay': 0}]\n optim = torch.optim.SGD(param_list, lr=args.lr, weight_decay=args.weight_decay,\n momentum=args.momentum, nesterov=True)\n\n lr_schdlr = WarmupCosineLrScheduler(optim, n_iters_all, warmup_iter=0)\n\n # memory bank\n args.queue_size = args.queue_batch * (args.mu + 1) * args.batchsize\n queue_feats = torch.zeros(args.queue_size, args.low_dim).cuda()\n queue_probs = torch.zeros(args.queue_size, args.n_classes).cuda()\n queue_ptr = 0\n\n # for distribution alignment\n prob_list = []\n\n train_args = dict(\n model=model,\n ema_model=ema_model,\n prob_list=prob_list,\n criteria_x=criteria_x,\n optim=optim,\n lr_schdlr=lr_schdlr,\n dltrain_x=dltrain_x,\n dltrain_u=dltrain_u,\n args=args,\n n_iters=n_iters_per_epoch,\n logger=logger\n )\n\n best_acc = -1\n best_epoch = 0\n logger.info('-----------start training--------------')\n for epoch in range(args.n_epoches):\n\n train_one_epoch(epoch, **train_args, queue_feats=queue_feats, queue_probs=queue_probs,\n dlval=dlval)\n\n top1, ema_top1 = evaluate(model, ema_model, dlval)\n\n if best_acc < top1:\n best_acc = top1\n best_epoch = epoch\n\n logger.info(\"Epoch {}. Acc: {:.4f}. Ema-Acc: {:.4f}. best_acc: {:.4f} in epoch{}\".\n format(epoch, top1, ema_top1, best_acc, best_epoch))\n\n if epoch % 10 == 0:\n save_obj = {\n 'model': model.state_dict(),\n 'ema_model': ema_model.state_dict(),\n 'optimizer': optim.state_dict(),\n 'lr_scheduler': lr_schdlr.state_dict(),\n 'prob_list': prob_list,\n 'queue': {'queue_feats': queue_feats, 'queue_probs': queue_probs, 'queue_ptr': queue_ptr},\n 'epoch': epoch,\n }\n torch.save(save_obj, os.path.join(output_dir, 'checkpoint_%02d.pth' % epoch))\n\n\nif __name__ == '__main__':\n main()\n" ]
[ [ "torch.zeros", "torch.cat", "torch.stack", "torch.max", "numpy.random.seed", "torch.no_grad", "torch.optim.SGD", "torch.split", "torch.softmax", "torch.mm", "torch.manual_seed", "torch.cuda.set_device", "torch.nn.functional.log_softmax", "torch.load", "torch.nn.CrossEntropyLoss" ] ]
mesoscope/cellpack
[ "ec6b736fc706c1fae16392befa814b5337a3a692" ]
[ "cellpack/mgl_tools/DejaVu/scenarioInterface/Tests/test_view.py" ]
[ "from DejaVu import Viewer\nfrom DejaVu.Spheres import Spheres\nimport numpy\n\n\ndef test_views001():\n \"\"\"\n Test that:\n we can create a view,\n add it to a director,\n move the scene toa new place,\n save the new place as a second view\n use the director to go back to the initial view\n add the second view to the director at position 40\n move to a new position\n play the animation going from the current position to the initial view\n and the to the second view\n \"\"\"\n vi = Viewer()\n sph = Spheres(\n \"sph\",\n centers=[(0, 0, 0), (10, 0, 0), (0, 10, 0), (0, 0, 10)],\n materials=[(1, 1, 1), (1, 0, 0), (0, 1, 0), (0, 0, 1)],\n inheritMaterial=False,\n )\n vi.AddObject(sph)\n root = vi.rootObject\n cam = vi.currentCamera\n mat1g = root.GetMatrix()\n mat1c = cam.GetMatrix()\n\n # create view with identity transformation\n from DejaVu.scenarioInterface.animations import OrientationMAA\n from DejaVu.states import getRendering, getOrientation\n\n # orient = getOrientation(root)\n orient = None\n rendering = getRendering(vi)\n maa1 = OrientationMAA(root, \"temp\", orient, rendering)\n\n # create a director\n ## from Scenario2.director import Director\n ## d = Director()\n from Scenario2.director import MAADirector\n\n d = MAADirector()\n # add the maa1 to the director\n # val = d.addMultipleActorsActionsAt(maa1)\n val = d.addMAAat(maa1, 0)\n assert val == True\n\n # check the animation\n names, posLabel, posStr, actStr, fullStr = maa1.getStringRepr()\n redrawActor = maa1.actors[0]\n\n ## check that we have this:\n\n ## 1 2 3\n ## 0 0 0 0\n ## | : | : | : |\n ## root.rotation x-----------------------------x\n ## root.translati x-----------------------------x\n ## root.scale x-----------------------------x\n ## root.pivot x-----------------------------x\n ## Camera0.fieldO x---------x---------x---------x\n ## Camera0.lookFr x-----------------------------x\n ## redraw_******* No Keyframes\n\n ## testStr = \" 1 2 3\\n 0 0 0 0\\n | : | : | : |\\n root.rotation x-----------------------------x\\nroot.translati x-----------------------------x\\n root.scale x-----------------------------x\\n root.pivot x-----------------------------x\\nCamera0.fieldO x---------x---------x---------x\\nCamera0.lookFr x-----------------------------x\\n%014s No Keyframes\\n\" % redrawActor.name[:14]\n\n ## assert fullStr == testStr\n\n # translate the scene to (10, 0, 0)\n root.SetTranslation(numpy.array((10, 0, 0)))\n vi.OneRedraw()\n\n # save this position as our second view\n # orient = getOrientation(root)\n orient = None\n rendering = getRendering(vi)\n maa2 = OrientationMAA(root, \"temp2\", orient, rendering)\n # maa2 = OrientationMAA(root, \"Viewer\", 'view1')\n mat2g = root.GetMatrix()\n mat2c = cam.GetMatrix()\n # play the director. We shoudl move from current position to identity tranformation\n # d.actors[1].printValuesWhenSetting = True\n # d.run()\n d.play()\n # maa1.run()\n # check that transformation matrices are correctly returned to identity\n mat3g = root.GetMatrix()\n mat3c = cam.GetMatrix()\n assert numpy.sum(mat1g - mat3g) == 0.0\n assert numpy.sum(mat1c - mat3c) == 0.0\n\n # add second view to director at 40\n # val = d.addMultipleActorsActionsAt(maa2, 40)\n val = d.addMAAat(maa2, 40)\n assert val == True\n\n # move to other position\n root.SetTranslation(numpy.array((-10, 0, 0)))\n vi.OneRedraw()\n\n # play back motion from this position to origin and then to view1\n # d.run()\n d.play()\n mat4g = root.GetMatrix()\n mat4c = cam.GetMatrix()\n assert numpy.sum(mat4g - mat2g) == 0.0\n assert numpy.sum(mat4c - mat2c) == 0.0\n\n maa3 = None\n viewer = vi\n showwarning = 0\n # check if we can reproduce MAA from it's source\n maasrc = maa2.getSourceCode(\"maa3\")\n exec(maasrc)\n assert maa3 != None\n # replace the original MAA (maa2) with the one created from source\n d.removeMAA(maa2, 40)\n d.addMAAat(maa3, 40)\n\n # move to other position and play :\n root.SetTranslation(numpy.array((-10, 0, 0)))\n vi.OneRedraw()\n d.play()\n # check the values\n mat5g = root.GetMatrix()\n mat5c = cam.GetMatrix()\n assert numpy.sum(mat5g - mat2g) == 0.0\n assert numpy.sum(mat5c - mat2c) == 0.0\n vi.Exit()\n" ]
[ [ "numpy.sum", "numpy.array" ] ]
pepCV/PyFstat
[ "b30919962e9730e24d514e9e9fe89289a002d428" ]
[ "pyfstat/core.py" ]
[ "\"\"\" The core tools used in pyfstat \"\"\"\n\n\nimport os\nimport logging\nimport copy\n\nimport glob\nimport numpy as np\nimport scipy.special\nimport scipy.optimize\n\nimport lal\nimport lalpulsar\nimport pyfstat.helper_functions as helper_functions\nimport pyfstat.tcw_fstat_map_funcs as tcw\n\n# workaround for matplotlib on X-less remote logins\nif \"DISPLAY\" in os.environ:\n import matplotlib.pyplot as plt\nelse:\n logging.info(\n 'No $DISPLAY environment variable found, so importing \\\n matplotlib.pyplot with non-interactive \"Agg\" backend.'\n )\n import matplotlib\n\n matplotlib.use(\"Agg\")\n import matplotlib.pyplot as plt\n\nhelper_functions.set_up_matplotlib_defaults()\nargs, tqdm = helper_functions.set_up_command_line_arguments()\ndetector_colors = {\"h1\": \"C0\", \"l1\": \"C1\"}\n\n\nclass Bunch(object):\n \"\"\" Turns dictionary into object with attribute-style access\n\n Parameters\n ----------\n dict\n Input dictionary\n\n Examples\n --------\n >>> data = Bunch(dict(x=1, y=[1, 2, 3], z=True))\n >>> print(data.x)\n 1\n >>> print(data.y)\n [1, 2, 3]\n >>> print(data.z)\n True\n\n \"\"\"\n\n def __init__(self, dictionary):\n self.__dict__.update(dictionary)\n\n\ndef read_par(\n filename=None,\n label=None,\n outdir=None,\n suffix=\"par\",\n return_type=\"dict\",\n comments=[\"%\", \"#\"],\n raise_error=False,\n):\n \"\"\" Read in a .par or .loudest file, returns a dict or Bunch of the data\n\n Parameters\n ----------\n filename : str\n Filename (path) containing rows of `key=val` data to read in.\n label, outdir, suffix : str, optional\n If filename is None, form the file to read as `outdir/label.suffix`.\n return_type : {'dict', 'bunch'}, optional\n If `dict`, return a dictionary, if 'bunch' return a Bunch\n comments : str or list of strings, optional\n Characters denoting that a row is a comment.\n raise_error : bool, optional\n If True, raise an error for lines which are not comments, but cannot\n be read.\n\n Notes\n -----\n This can also be used to read in .loudest files, or any file which has\n rows of `key=val` data (in which the val can be understood using eval(val)\n\n Returns\n -------\n d: Bunch or dict\n The par values as either a `Bunch` or dict type\n\n \"\"\"\n if filename is None:\n filename = \"{}/{}.{}\".format(outdir, label, suffix)\n if os.path.isfile(filename) is False:\n raise ValueError(\"No file {} found\".format(filename))\n d = {}\n with open(filename, \"r\") as f:\n d = _get_dictionary_from_lines(f, comments, raise_error)\n if return_type in [\"bunch\", \"Bunch\"]:\n return Bunch(d)\n elif return_type in [\"dict\", \"dictionary\"]:\n return d\n else:\n raise ValueError(\"return_type {} not understood\".format(return_type))\n\n\ndef _get_dictionary_from_lines(lines, comments, raise_error):\n \"\"\" Return dictionary of key=val pairs for each line in lines\n\n Parameters\n ----------\n comments : str or list of strings\n Characters denoting that a row is a comment.\n raise_error : bool\n If True, raise an error for lines which are not comments, but cannot\n be read.\n\n Returns\n -------\n d: Bunch or dict\n The par values as either a `Bunch` or dict type\n\n \"\"\"\n d = {}\n for line in lines:\n if line[0] not in comments and len(line.split(\"=\")) == 2:\n try:\n key, val = line.rstrip(\"\\n\").split(\"=\")\n key = key.strip()\n val = val.strip()\n if (val[0] in [\"'\", '\"']) and (val[-1] in [\"'\", '\"']):\n d[key] = val.lstrip('\"').lstrip(\"'\").rstrip('\"').rstrip(\"'\")\n else:\n try:\n d[key] = np.float64(eval(val.rstrip(\"; \")))\n except NameError:\n d[key] = val.rstrip(\"; \")\n except SyntaxError:\n if raise_error:\n raise IOError(\"Line {} not understood\".format(line))\n pass\n return d\n\n\ndef predict_fstat(\n h0,\n cosi,\n psi,\n Alpha,\n Delta,\n Freq,\n sftfilepattern,\n minStartTime,\n maxStartTime,\n IFOs=None,\n assumeSqrtSX=None,\n tempory_filename=\"fs.tmp\",\n earth_ephem=None,\n sun_ephem=None,\n **kwargs\n):\n \"\"\" Wrapper to lalapps_PredictFstat\n\n Parameters\n ----------\n h0, cosi, psi, Alpha, Delta, Freq : float\n Signal properties, see `lalapps_PredictFstat --help` for more info.\n sftfilepattern : str\n Pattern matching the sftfiles to use.\n minStartTime, maxStartTime : int\n IFOs : str\n See `lalapps_PredictFstat --help`\n assumeSqrtSX : float or None\n See `lalapps_PredictFstat --help`, if None this option is not used\n\n Returns\n -------\n twoF_expected, twoF_sigma : float\n The expectation and standard deviation of 2F\n\n \"\"\"\n\n cl_pfs = []\n cl_pfs.append(\"lalapps_PredictFstat\")\n cl_pfs.append(\"--h0={}\".format(h0))\n cl_pfs.append(\"--cosi={}\".format(cosi))\n cl_pfs.append(\"--psi={}\".format(psi))\n cl_pfs.append(\"--Alpha={}\".format(Alpha))\n cl_pfs.append(\"--Delta={}\".format(Delta))\n cl_pfs.append(\"--Freq={}\".format(Freq))\n\n cl_pfs.append(\"--DataFiles='{}'\".format(sftfilepattern))\n if assumeSqrtSX:\n cl_pfs.append(\"--assumeSqrtSX={}\".format(assumeSqrtSX))\n # if IFOs:\n # cl_pfs.append(\"--IFOs={}\".format(IFOs))\n\n cl_pfs.append(\"--minStartTime={}\".format(int(minStartTime)))\n cl_pfs.append(\"--maxStartTime={}\".format(int(maxStartTime)))\n cl_pfs.append(\"--outputFstat={}\".format(tempory_filename))\n\n if earth_ephem is not None:\n cl_pfs.append(\"--ephemEarth='{}'\".format(earth_ephem))\n if sun_ephem is not None:\n cl_pfs.append(\"--ephemSun='{}'\".format(sun_ephem))\n\n cl_pfs = \" \".join(cl_pfs)\n helper_functions.run_commandline(cl_pfs)\n d = read_par(filename=tempory_filename)\n os.remove(tempory_filename)\n return float(d[\"twoF_expected\"]), float(d[\"twoF_sigma\"])\n\n\nclass BaseSearchClass(object):\n \"\"\" The base search class providing parent methods to other searches \"\"\"\n\n def _add_log_file(self):\n \"\"\" Log output to a file, requires class to have outdir and label \"\"\"\n logfilename = \"{}/{}.log\".format(self.outdir, self.label)\n fh = logging.FileHandler(logfilename)\n fh.setLevel(logging.INFO)\n fh.setFormatter(\n logging.Formatter(\n \"%(asctime)s %(levelname)-8s: %(message)s\", datefmt=\"%y-%m-%d %H:%M\"\n )\n )\n logging.getLogger().addHandler(fh)\n\n def _shift_matrix(self, n, dT):\n \"\"\" Generate the shift matrix\n\n Parameters\n ----------\n n : int\n The dimension of the shift-matrix to generate\n dT : float\n The time delta of the shift matrix\n\n Returns\n -------\n m : ndarray, shape (n,)\n The shift matrix.\n\n \"\"\"\n m = np.zeros((n, n))\n factorial = np.math.factorial\n for i in range(n):\n for j in range(n):\n if i == j:\n m[i, j] = 1.0\n elif i > j:\n m[i, j] = 0.0\n else:\n if i == 0:\n m[i, j] = 2 * np.pi * float(dT) ** (j - i) / factorial(j - i)\n else:\n m[i, j] = float(dT) ** (j - i) / factorial(j - i)\n return m\n\n def _shift_coefficients(self, theta, dT):\n \"\"\" Shift a set of coefficients by dT\n\n Parameters\n ----------\n theta : array-like, shape (n,)\n Vector of the expansion coefficients to transform starting from the\n lowest degree e.g [phi, F0, F1,...].\n dT : float\n Difference between the two reference times as tref_new - tref_old.\n\n Returns\n -------\n theta_new : ndarray, shape (n,)\n Vector of the coefficients as evaluated as the new reference time.\n \"\"\"\n n = len(theta)\n m = self._shift_matrix(n, dT)\n return np.dot(m, theta)\n\n def _calculate_thetas(self, theta, delta_thetas, tbounds, theta0_idx=0):\n \"\"\" Calculates the set of thetas given delta_thetas, the jumps\n\n This is used when generating data containing glitches or timing noise.\n Specifically, the source parameters of the signal are not constant in\n time, but jump by `delta_theta` at `tbounds`.\n\n Parameters\n ----------\n theta : array_like\n The source parameters of size (n,).\n delta_thetas : array_like\n The jumps in the source parameters of size (m, n) where m is the\n number of jumps.\n tbounds : array_like\n Time boundaries of the jumps of size (m+2,).\n theta0_idx : int\n Index of the segment for which the theta are defined.\n\n Returns\n -------\n ndarray\n The set of thetas, shape (m+1, n).\n\n \"\"\"\n thetas = [theta]\n for i, dt in enumerate(delta_thetas):\n if i < theta0_idx:\n pre_theta_at_ith_glitch = self._shift_coefficients(\n thetas[0], tbounds[i + 1] - self.tref\n )\n post_theta_at_ith_glitch = pre_theta_at_ith_glitch - dt\n thetas.insert(\n 0,\n self._shift_coefficients(\n post_theta_at_ith_glitch, self.tref - tbounds[i + 1]\n ),\n )\n\n elif i >= theta0_idx:\n pre_theta_at_ith_glitch = self._shift_coefficients(\n thetas[i], tbounds[i + 1] - self.tref\n )\n post_theta_at_ith_glitch = pre_theta_at_ith_glitch + dt\n thetas.append(\n self._shift_coefficients(\n post_theta_at_ith_glitch, self.tref - tbounds[i + 1]\n )\n )\n self.thetas_at_tref = thetas\n return thetas\n\n def _get_list_of_matching_sfts(self):\n \"\"\" Returns a list of sfts matching the attribute sftfilepattern \"\"\"\n sftfilepatternlist = np.atleast_1d(self.sftfilepattern.split(\";\"))\n matches = [glob.glob(p) for p in sftfilepatternlist]\n matches = [item for sublist in matches for item in sublist]\n if len(matches) > 0:\n return matches\n else:\n raise IOError(\"No sfts found matching {}\".format(self.sftfilepattern))\n\n def set_ephemeris_files(self, earth_ephem=None, sun_ephem=None):\n \"\"\" Set the ephemeris files to use for the Earth and Sun\n\n Parameters\n ----------\n earth_ephem, sun_ephem: str\n Paths of the two files containing positions of Earth and Sun,\n respectively at evenly spaced times, as passed to CreateFstatInput\n\n Note: If not manually set, default values from get_ephemeris_files()\n are used (looking in ~/.pyfstat or $LALPULSAR_DATADIR)\n\n \"\"\"\n\n earth_ephem_default, sun_ephem_default = helper_functions.get_ephemeris_files()\n\n if earth_ephem is None:\n self.earth_ephem = earth_ephem_default\n else:\n self.earth_ephem = earth_ephem\n if sun_ephem is None:\n self.sun_ephem = sun_ephem_default\n else:\n self.sun_ephem = sun_ephem\n\n\nclass ComputeFstat(BaseSearchClass):\n \"\"\" Base class providing interface to `lalpulsar.ComputeFstat` \"\"\"\n\n @helper_functions.initializer\n def __init__(\n self,\n tref,\n sftfilepattern=None,\n minStartTime=None,\n maxStartTime=None,\n binary=False,\n BSGL=False,\n transientWindowType=None,\n t0Band=None,\n tauBand=None,\n tauMin=None,\n dt0=None,\n dtau=None,\n detectors=None,\n minCoverFreq=None,\n maxCoverFreq=None,\n injectSources=None,\n injectSqrtSX=None,\n assumeSqrtSX=None,\n SSBprec=None,\n tCWFstatMapVersion=\"lal\",\n cudaDeviceName=None,\n computeAtoms=False,\n ):\n \"\"\"\n Parameters\n ----------\n tref : int\n GPS seconds of the reference time.\n sftfilepattern : str\n Pattern to match SFTs using wildcards (*?) and ranges [0-9];\n mutiple patterns can be given separated by colons.\n minStartTime, maxStartTime : float GPStime\n Only use SFTs with timestemps starting from (including, excluding)\n this epoch\n binary : bool\n If true, search of binary parameters.\n BSGL : bool\n If true, compute the BSGL rather than the twoF value.\n transientWindowType: str\n If 'rect' or 'exp',\n allow for the Fstat to be computed over a transient range.\n ('none' instead of None explicitly calls the transient-window\n function, but with the full range, for debugging)\n (if not None, will also force atoms regardless of computeAtoms option)\n t0Band, tauBand: int\n if >0, search t0 in (minStartTime,minStartTime+t0Band)\n and tau in (tauMin,2*Tsft+tauBand).\n if =0, only compute CW Fstat with t0=minStartTime,\n tau=maxStartTime-minStartTime.\n tauMin: int\n defaults to 2*Tsft\n dt0, dtau: int\n grid resolutions in transient start-time and duration,\n both default to Tsft\n detectors : str\n Two character reference to the data to use, specify None for no\n contraint. If multiple-separate by comma.\n minCoverFreq, maxCoverFreq : float\n The min and max cover frequency passed to CreateFstatInput, if\n either is None the range of frequencies in the SFT less 1Hz is\n used.\n injectSources : dict or str\n Either a dictionary of the values to inject, or a string pointing\n to the .cff file to inject\n injectSqrtSX :\n Not yet implemented\n assumeSqrtSX : float\n Don't estimate noise-floors but assume (stationary) per-IFO\n sqrt{SX} (if single value: use for all IFOs). If signal only,\n set sqrtSX=1\n SSBprec : int\n Flag to set the SSB calculation: 0=Newtonian, 1=relativistic,\n 2=relativisitic optimised, 3=DMoff, 4=NO_SPIN\n tCWFstatMapVersion: str\n Choose between standard 'lal' implementation,\n 'pycuda' for gpu, and some others for devel/debug.\n cudaDeviceName: str\n GPU name to be matched against drv.Device output.\n computeAtoms: bool\n request atoms calculations regardless of transientWindowType\n\n \"\"\"\n\n self.set_ephemeris_files()\n self.init_computefstatistic_single_point()\n\n def _get_SFTCatalog(self):\n \"\"\" Load the SFTCatalog\n\n If sftfilepattern is specified, load the data. If not, attempt to\n create data on the fly.\n\n Returns\n -------\n SFTCatalog: lalpulsar.SFTCatalog\n\n \"\"\"\n if hasattr(self, \"SFTCatalog\"):\n return\n if self.sftfilepattern is None:\n for k in [\"minStartTime\", \"maxStartTime\", \"detectors\"]:\n if getattr(self, k) is None:\n raise ValueError('You must provide \"{}\" to injectSources'.format(k))\n C1 = getattr(self, \"injectSources\", None) is None\n C2 = getattr(self, \"injectSqrtSX\", None) is None\n if C1 and C2:\n raise ValueError(\n \"You must specify either one of injectSources\" \" or injectSqrtSX\"\n )\n SFTCatalog = lalpulsar.SFTCatalog()\n Tsft = 1800\n Toverlap = 0\n Tspan = self.maxStartTime - self.minStartTime\n detNames = lal.CreateStringVector(*[d for d in self.detectors.split(\",\")])\n multiTimestamps = lalpulsar.MakeMultiTimestamps(\n self.minStartTime, Tspan, Tsft, Toverlap, detNames.length\n )\n SFTCatalog = lalpulsar.MultiAddToFakeSFTCatalog(\n SFTCatalog, detNames, multiTimestamps\n )\n return SFTCatalog\n\n logging.info(\"Initialising SFTCatalog\")\n constraints = lalpulsar.SFTConstraints()\n if self.detectors:\n if \",\" in self.detectors:\n logging.warning(\n \"Multiple detector selection not available,\"\n \" using all available data\"\n )\n else:\n constraints.detector = self.detectors\n if self.minStartTime:\n constraints.minStartTime = lal.LIGOTimeGPS(self.minStartTime)\n if self.maxStartTime:\n constraints.maxStartTime = lal.LIGOTimeGPS(self.maxStartTime)\n logging.info(\"Loading data matching pattern {}\".format(self.sftfilepattern))\n SFTCatalog = lalpulsar.SFTdataFind(self.sftfilepattern, constraints)\n\n SFT_timestamps = [d.header.epoch for d in SFTCatalog.data]\n self.SFT_timestamps = [float(s) for s in SFT_timestamps]\n if len(SFT_timestamps) == 0:\n raise ValueError(\"Failed to load any data\")\n if args.quite is False and args.no_interactive is False:\n try:\n from bashplotlib.histogram import plot_hist\n\n print(\"Data timestamps histogram:\")\n plot_hist(SFT_timestamps, height=5, bincount=50)\n except ImportError:\n pass\n\n cl_tconv1 = \"lalapps_tconvert {}\".format(int(SFT_timestamps[0]))\n output = helper_functions.run_commandline(cl_tconv1, log_level=logging.DEBUG)\n tconvert1 = output.rstrip(\"\\n\")\n cl_tconv2 = \"lalapps_tconvert {}\".format(int(SFT_timestamps[-1]))\n output = helper_functions.run_commandline(cl_tconv2, log_level=logging.DEBUG)\n tconvert2 = output.rstrip(\"\\n\")\n logging.info(\n \"Data spans from {} ({}) to {} ({})\".format(\n int(SFT_timestamps[0]), tconvert1, int(SFT_timestamps[-1]), tconvert2\n )\n )\n\n if self.minStartTime is None:\n self.minStartTime = int(SFT_timestamps[0])\n if self.maxStartTime is None:\n self.maxStartTime = int(SFT_timestamps[-1])\n\n detector_names = list(set([d.header.name for d in SFTCatalog.data]))\n self.detector_names = detector_names\n if len(detector_names) == 0:\n raise ValueError(\"No data loaded.\")\n logging.info(\n \"Loaded {} data files from detectors {}\".format(\n len(SFT_timestamps), detector_names\n )\n )\n\n return SFTCatalog\n\n def init_computefstatistic_single_point(self):\n \"\"\" Initilisation step of run_computefstatistic for a single point \"\"\"\n\n SFTCatalog = self._get_SFTCatalog()\n\n logging.info(\"Initialising ephems\")\n ephems = lalpulsar.InitBarycenter(self.earth_ephem, self.sun_ephem)\n\n logging.info(\"Initialising FstatInput\")\n dFreq = 0\n self.whatToCompute = lalpulsar.FSTATQ_2F\n if self.transientWindowType or self.computeAtoms:\n self.whatToCompute += lalpulsar.FSTATQ_ATOMS_PER_DET\n\n FstatOAs = lalpulsar.FstatOptionalArgs()\n FstatOAs.randSeed = lalpulsar.FstatOptionalArgsDefaults.randSeed\n if self.SSBprec:\n logging.info(\"Using SSBprec={}\".format(self.SSBprec))\n FstatOAs.SSBprec = self.SSBprec\n else:\n FstatOAs.SSBprec = lalpulsar.FstatOptionalArgsDefaults.SSBprec\n FstatOAs.Dterms = lalpulsar.FstatOptionalArgsDefaults.Dterms\n FstatOAs.runningMedianWindow = (\n lalpulsar.FstatOptionalArgsDefaults.runningMedianWindow\n )\n FstatOAs.FstatMethod = lalpulsar.FstatOptionalArgsDefaults.FstatMethod\n if self.assumeSqrtSX is None:\n FstatOAs.assumeSqrtSX = lalpulsar.FstatOptionalArgsDefaults.assumeSqrtSX\n else:\n mnf = lalpulsar.MultiNoiseFloor()\n assumeSqrtSX = np.atleast_1d(self.assumeSqrtSX)\n mnf.sqrtSn[: len(assumeSqrtSX)] = assumeSqrtSX\n mnf.length = len(assumeSqrtSX)\n FstatOAs.assumeSqrtSX = mnf\n FstatOAs.prevInput = lalpulsar.FstatOptionalArgsDefaults.prevInput\n FstatOAs.collectTiming = lalpulsar.FstatOptionalArgsDefaults.collectTiming\n\n if hasattr(self, \"injectSources\") and type(self.injectSources) == dict:\n logging.info(\"Injecting source with params: {}\".format(self.injectSources))\n PPV = lalpulsar.CreatePulsarParamsVector(1)\n PP = PPV.data[0]\n h0 = self.injectSources[\"h0\"]\n cosi = self.injectSources[\"cosi\"]\n use_aPlus = \"aPlus\" in dir(PP.Amp)\n print(\"use_aPlus = {}\".format(use_aPlus))\n if use_aPlus: # lalsuite interface changed in aff93c45\n PP.Amp.aPlus = 0.5 * h0 * (1.0 + cosi ** 2)\n PP.Amp.aCross = h0 * cosi\n else:\n PP.Amp.h0 = h0\n PP.Amp.cosi = cosi\n\n PP.Amp.phi0 = self.injectSources[\"phi0\"]\n PP.Amp.psi = self.injectSources[\"psi\"]\n PP.Doppler.Alpha = self.injectSources[\"Alpha\"]\n PP.Doppler.Delta = self.injectSources[\"Delta\"]\n if \"fkdot\" in self.injectSources:\n PP.Doppler.fkdot = np.array(self.injectSources[\"fkdot\"])\n else:\n PP.Doppler.fkdot = np.zeros(lalpulsar.PULSAR_MAX_SPINS)\n for i, key in enumerate([\"F0\", \"F1\", \"F2\"]):\n PP.Doppler.fkdot[i] = self.injectSources[key]\n PP.Doppler.refTime = self.tref\n if \"t0\" not in self.injectSources:\n PP.Transient.type = lalpulsar.TRANSIENT_NONE\n FstatOAs.injectSources = PPV\n elif hasattr(self, \"injectSources\") and type(self.injectSources) == str:\n logging.info(\n \"Injecting source from param file: {}\".format(self.injectSources)\n )\n PPV = lalpulsar.PulsarParamsFromFile(self.injectSources, self.tref)\n FstatOAs.injectSources = PPV\n else:\n FstatOAs.injectSources = lalpulsar.FstatOptionalArgsDefaults.injectSources\n if hasattr(self, \"injectSqrtSX\") and self.injectSqrtSX is not None:\n raise ValueError(\"injectSqrtSX not implemented\")\n else:\n FstatOAs.InjectSqrtSX = lalpulsar.FstatOptionalArgsDefaults.injectSqrtSX\n if self.minCoverFreq is None or self.maxCoverFreq is None:\n fAs = [d.header.f0 for d in SFTCatalog.data]\n fBs = [\n d.header.f0 + (d.numBins - 1) * d.header.deltaF for d in SFTCatalog.data\n ]\n self.minCoverFreq = np.min(fAs) + 0.5\n self.maxCoverFreq = np.max(fBs) - 0.5\n logging.info(\n \"Min/max cover freqs not provided, using \"\n \"{} and {}, est. from SFTs\".format(self.minCoverFreq, self.maxCoverFreq)\n )\n\n self.FstatInput = lalpulsar.CreateFstatInput(\n SFTCatalog, self.minCoverFreq, self.maxCoverFreq, dFreq, ephems, FstatOAs\n )\n\n logging.info(\"Initialising PulsarDoplerParams\")\n PulsarDopplerParams = lalpulsar.PulsarDopplerParams()\n PulsarDopplerParams.refTime = self.tref\n PulsarDopplerParams.Alpha = 1\n PulsarDopplerParams.Delta = 1\n PulsarDopplerParams.fkdot = np.array([0, 0, 0, 0, 0, 0, 0])\n self.PulsarDopplerParams = PulsarDopplerParams\n\n logging.info(\"Initialising FstatResults\")\n self.FstatResults = lalpulsar.FstatResults()\n\n if self.BSGL:\n if len(self.detector_names) < 2:\n raise ValueError(\"Can't use BSGL with single detectors data\")\n else:\n logging.info(\"Initialising BSGL\")\n\n # Tuning parameters - to be reviewed\n numDetectors = 2\n if hasattr(self, \"nsegs\"):\n p_val_threshold = 1e-6\n Fstar0s = np.linspace(0, 1000, 10000)\n p_vals = scipy.special.gammaincc(2 * self.nsegs, Fstar0s)\n Fstar0 = Fstar0s[np.argmin(np.abs(p_vals - p_val_threshold))]\n if Fstar0 == Fstar0s[-1]:\n raise ValueError(\"Max Fstar0 exceeded\")\n else:\n Fstar0 = 15.0\n logging.info(\"Using Fstar0 of {:1.2f}\".format(Fstar0))\n oLGX = np.zeros(10)\n oLGX[:numDetectors] = 1.0 / numDetectors\n self.BSGLSetup = lalpulsar.CreateBSGLSetup(\n numDetectors, Fstar0, oLGX, True, 1\n )\n self.twoFX = np.zeros(10)\n self.whatToCompute = self.whatToCompute + lalpulsar.FSTATQ_2F_PER_DET\n\n if self.transientWindowType:\n logging.info(\"Initialising transient parameters\")\n self.windowRange = lalpulsar.transientWindowRange_t()\n transientWindowTypes = {\n \"none\": lalpulsar.TRANSIENT_NONE,\n \"rect\": lalpulsar.TRANSIENT_RECTANGULAR,\n \"exp\": lalpulsar.TRANSIENT_EXPONENTIAL,\n }\n if self.transientWindowType in transientWindowTypes:\n self.windowRange.type = transientWindowTypes[self.transientWindowType]\n else:\n raise ValueError(\n \"Unknown window-type ({}) passed as input, [{}] allows.\".format(\n self.transientWindowType, \", \".join(transientWindowTypes)\n )\n )\n\n # default spacing\n self.Tsft = int(1.0 / SFTCatalog.data[0].header.deltaF)\n self.windowRange.dt0 = self.Tsft\n self.windowRange.dtau = self.Tsft\n\n # special treatment of window_type = none\n # ==> replace by rectangular window spanning all the data\n if self.windowRange.type == lalpulsar.TRANSIENT_NONE:\n self.windowRange.t0 = int(self.minStartTime)\n self.windowRange.t0Band = 0\n self.windowRange.tau = int(self.maxStartTime - self.minStartTime)\n self.windowRange.tauBand = 0\n else: # user-set bands and spacings\n if self.t0Band is None:\n self.windowRange.t0Band = 0\n else:\n if not isinstance(self.t0Band, int):\n logging.warn(\n \"Casting non-integer t0Band={} to int...\".format(\n self.t0Band\n )\n )\n self.t0Band = int(self.t0Band)\n self.windowRange.t0Band = self.t0Band\n if self.dt0:\n self.windowRange.dt0 = self.dt0\n if self.tauBand is None:\n self.windowRange.tauBand = 0\n else:\n if not isinstance(self.tauBand, int):\n logging.warn(\n \"Casting non-integer tauBand={} to int...\".format(\n self.tauBand\n )\n )\n self.tauBand = int(self.tauBand)\n self.windowRange.tauBand = self.tauBand\n if self.dtau:\n self.windowRange.dtau = self.dtau\n if self.tauMin is None:\n self.windowRange.tau = int(2 * self.Tsft)\n else:\n if not isinstance(self.tauMin, int):\n logging.warn(\n \"Casting non-integer tauMin={} to int...\".format(\n self.tauMin\n )\n )\n self.tauMin = int(self.tauMin)\n self.windowRange.tau = self.tauMin\n\n logging.info(\"Initialising transient FstatMap features...\")\n (\n self.tCWFstatMapFeatures,\n self.gpu_context,\n ) = tcw.init_transient_fstat_map_features(\n self.tCWFstatMapVersion == \"pycuda\", self.cudaDeviceName\n )\n\n def get_fullycoherent_twoF(\n self,\n tstart,\n tend,\n F0,\n F1,\n F2,\n Alpha,\n Delta,\n asini=None,\n period=None,\n ecc=None,\n tp=None,\n argp=None,\n ):\n \"\"\" Returns twoF or ln(BSGL) fully-coherently at a single point \"\"\"\n self.PulsarDopplerParams.fkdot = np.array([F0, F1, F2, 0, 0, 0, 0])\n self.PulsarDopplerParams.Alpha = float(Alpha)\n self.PulsarDopplerParams.Delta = float(Delta)\n if self.binary:\n self.PulsarDopplerParams.asini = float(asini)\n self.PulsarDopplerParams.period = float(period)\n self.PulsarDopplerParams.ecc = float(ecc)\n self.PulsarDopplerParams.tp = float(tp)\n self.PulsarDopplerParams.argp = float(argp)\n\n lalpulsar.ComputeFstat(\n self.FstatResults,\n self.FstatInput,\n self.PulsarDopplerParams,\n 1,\n self.whatToCompute,\n )\n\n if not self.transientWindowType:\n if self.BSGL is False:\n return self.FstatResults.twoF[0]\n\n twoF = np.float(self.FstatResults.twoF[0])\n self.twoFX[0] = self.FstatResults.twoFPerDet(0)\n self.twoFX[1] = self.FstatResults.twoFPerDet(1)\n log10_BSGL = lalpulsar.ComputeBSGL(twoF, self.twoFX, self.BSGLSetup)\n return log10_BSGL / np.log10(np.exp(1))\n\n self.windowRange.t0 = int(tstart) # TYPE UINT4\n if self.windowRange.tauBand == 0:\n # true single-template search also in transient params:\n # actual (t0,tau) window was set with tstart, tend before\n self.windowRange.tau = int(tend - tstart) # TYPE UINT4\n\n self.FstatMap, self.timingFstatMap = tcw.call_compute_transient_fstat_map(\n self.tCWFstatMapVersion,\n self.tCWFstatMapFeatures,\n self.FstatResults.multiFatoms[0],\n self.windowRange,\n )\n if self.tCWFstatMapVersion == \"lal\":\n F_mn = self.FstatMap.F_mn.data\n else:\n F_mn = self.FstatMap.F_mn\n\n twoF = 2 * np.max(F_mn)\n if self.BSGL is False:\n if np.isnan(twoF):\n return 0\n else:\n return twoF\n\n FstatResults_single = copy.copy(self.FstatResults)\n FstatResults_single.lenth = 1\n FstatResults_single.data = self.FstatResults.multiFatoms[0].data[0]\n FS0 = lalpulsar.ComputeTransientFstatMap(\n FstatResults_single.multiFatoms[0], self.windowRange, False\n )\n FstatResults_single.data = self.FstatResults.multiFatoms[0].data[1]\n FS1 = lalpulsar.ComputeTransientFstatMap(\n FstatResults_single.multiFatoms[0], self.windowRange, False\n )\n\n # for now, use the Doppler parameter with\n # multi-detector F maximised over t0,tau\n # to return BSGL\n # FIXME: should we instead compute BSGL over the whole F_mn\n # and return the maximum of that?\n idx_maxTwoF = np.argmax(F_mn)\n\n self.twoFX[0] = 2 * FS0.F_mn.data[idx_maxTwoF]\n self.twoFX[1] = 2 * FS1.F_mn.data[idx_maxTwoF]\n log10_BSGL = lalpulsar.ComputeBSGL(twoF, self.twoFX, self.BSGLSetup)\n\n return log10_BSGL / np.log10(np.exp(1))\n\n def calculate_twoF_cumulative(\n self,\n F0,\n F1,\n F2,\n Alpha,\n Delta,\n asini=None,\n period=None,\n ecc=None,\n tp=None,\n argp=None,\n tstart=None,\n tend=None,\n npoints=1000,\n ):\n \"\"\" Calculate the cumulative twoF along the obseration span\n\n Parameters\n ----------\n F0, F1, F2, Alpha, Delta: float\n Parameters at which to compute the cumulative twoF\n asini, period, ecc, tp, argp: float, optional\n Binary parameters at which to compute the cumulative 2F\n tstart, tend: int\n GPS times to restrict the range of data used - automatically\n truncated to the span of data available\n npoints: int\n Number of points to compute twoF along the span\n\n Notes\n -----\n The minimum cumulatibe twoF is hard-coded to be computed over\n the first 6 hours from either the first timestampe in the data (if\n tstart is smaller than it) or tstart.\n\n \"\"\"\n SFTminStartTime = self.SFT_timestamps[0]\n SFTmaxStartTime = self.SFT_timestamps[-1]\n tstart = np.max([SFTminStartTime, tstart])\n min_tau = np.max([SFTminStartTime - tstart, 0]) + 3600 * 6\n max_tau = SFTmaxStartTime - tstart\n taus = np.linspace(min_tau, max_tau, npoints)\n twoFs = []\n if not self.transientWindowType:\n # still call the transient-Fstat-map function, but using the full range\n self.transientWindowType = \"none\"\n self.init_computefstatistic_single_point()\n for tau in taus:\n detstat = self.get_fullycoherent_twoF(\n tstart=tstart,\n tend=tstart + tau,\n F0=F0,\n F1=F1,\n F2=F2,\n Alpha=Alpha,\n Delta=Delta,\n asini=asini,\n period=period,\n ecc=ecc,\n tp=tp,\n argp=argp,\n )\n twoFs.append(detstat)\n\n return taus, np.array(twoFs)\n\n def _calculate_predict_fstat_cumulative(\n self, N, label=None, outdir=None, IFO=None, pfs_input=None\n ):\n \"\"\" Calculates the predicted 2F and standard deviation cumulatively\n\n Parameters\n ----------\n N : int\n Number of timesteps to use between minStartTime and maxStartTime.\n label, outdir : str, optional\n The label and directory to read in the .loudest file from\n IFO : str\n pfs_input : dict, optional\n Input kwargs to predict_fstat (alternative to giving label and\n outdir).\n\n Returns\n -------\n times, pfs, pfs_sigma : ndarray, size (N,)\n\n \"\"\"\n\n if pfs_input is None:\n if os.path.isfile(\"{}/{}.loudest\".format(outdir, label)) is False:\n raise ValueError(\"Need a loudest file to add the predicted Fstat\")\n loudest = read_par(label=label, outdir=outdir, suffix=\"loudest\")\n pfs_input = {\n key: loudest[key]\n for key in [\"h0\", \"cosi\", \"psi\", \"Alpha\", \"Delta\", \"Freq\"]\n }\n times = np.linspace(self.minStartTime, self.maxStartTime, N + 1)[1:]\n times = np.insert(times, 0, self.minStartTime + 86400 / 2.0)\n out = [\n predict_fstat(\n minStartTime=self.minStartTime,\n maxStartTime=t,\n sftfilepattern=self.sftfilepattern,\n IFO=IFO,\n **pfs_input\n )\n for t in times\n ]\n pfs, pfs_sigma = np.array(out).T\n return times, pfs, pfs_sigma\n\n def plot_twoF_cumulative(\n self,\n label,\n outdir,\n add_pfs=False,\n N=15,\n injectSources=None,\n ax=None,\n c=\"k\",\n savefig=True,\n title=None,\n plt_label=None,\n **kwargs\n ):\n \"\"\" Plot the twoF value cumulatively\n\n Parameters\n ----------\n label, outdir : str\n add_pfs : bool\n If true, plot the predicted 2F and standard deviation\n N : int\n Number of points to use\n injectSources : dict\n See `ComputeFstat`\n ax : matplotlib.axes._subplots_AxesSubplot, optional\n Axis to add the plot to.\n c : str\n Colour\n savefig : bool\n If true, save the figure in outdir\n title, plt_label: str\n Figure title and label\n\n Returns\n -------\n tauS, tauF : ndarray shape (N,)\n If savefig, the times and twoF (cumulative) values\n ax : matplotlib.axes._subplots_AxesSubplot, optional\n If savefig is False\n\n \"\"\"\n if ax is None:\n fig, ax = plt.subplots()\n if injectSources:\n pfs_input = dict(\n h0=injectSources[\"h0\"],\n cosi=injectSources[\"cosi\"],\n psi=injectSources[\"psi\"],\n Alpha=injectSources[\"Alpha\"],\n Delta=injectSources[\"Delta\"],\n Freq=injectSources[\"fkdot\"][0],\n )\n else:\n pfs_input = None\n\n taus, twoFs = self.calculate_twoF_cumulative(**kwargs)\n ax.plot(taus / 86400.0, twoFs, label=plt_label, color=c)\n if len(self.detector_names) > 1:\n detector_names = self.detector_names\n detectors = self.detectors\n for d in self.detector_names:\n self.detectors = d\n self.init_computefstatistic_single_point()\n taus, twoFs = self.calculate_twoF_cumulative(**kwargs)\n ax.plot(\n taus / 86400.0,\n twoFs,\n label=\"{}\".format(d),\n color=detector_colors[d.lower()],\n )\n self.detectors = detectors\n self.detector_names = detector_names\n\n if add_pfs:\n times, pfs, pfs_sigma = self._calculate_predict_fstat_cumulative(\n N=N, label=label, outdir=outdir, pfs_input=pfs_input\n )\n ax.fill_between(\n (times - self.minStartTime) / 86400.0,\n pfs - pfs_sigma,\n pfs + pfs_sigma,\n color=c,\n label=(\n r\"Predicted $\\langle 2\\mathcal{F} \" r\"\\rangle\\pm $ 1-$\\sigma$ band\"\n ),\n zorder=-10,\n alpha=0.2,\n )\n if len(self.detector_names) > 1:\n for d in self.detector_names:\n out = self._calculate_predict_fstat_cumulative(\n N=N,\n label=label,\n outdir=outdir,\n IFO=d.upper(),\n pfs_input=pfs_input,\n )\n times, pfs, pfs_sigma = out\n ax.fill_between(\n (times - self.minStartTime) / 86400.0,\n pfs - pfs_sigma,\n pfs + pfs_sigma,\n color=detector_colors[d.lower()],\n alpha=0.5,\n label=(\n \"Predicted $2\\mathcal{{F}}$ 1-$\\sigma$ band ({})\".format(\n d.upper()\n )\n ),\n zorder=-10,\n )\n\n ax.set_xlabel(r\"Days from $t_{{\\rm start}}={:.0f}$\".format(kwargs[\"tstart\"]))\n if self.BSGL:\n ax.set_ylabel(r\"$\\log_{10}(\\mathrm{BSGL})_{\\rm cumulative}$\")\n else:\n ax.set_ylabel(r\"$\\widetilde{2\\mathcal{F}}_{\\rm cumulative}$\")\n ax.set_xlim(0, taus[-1] / 86400)\n if plt_label:\n ax.legend(frameon=False, loc=2, fontsize=6)\n if title:\n ax.set_title(title)\n if savefig:\n plt.tight_layout()\n plt.savefig(\"{}/{}_twoFcumulative.png\".format(outdir, label))\n return taus, twoFs\n else:\n return ax\n\n def get_full_CFSv2_output(self, tstart, tend, F0, F1, F2, Alpha, Delta, tref):\n \"\"\" Basic wrapper around CFSv2 to get the full (h0..) output \"\"\"\n cl_CFSv2 = \"lalapps_ComputeFstatistic_v2 --minStartTime={} --maxStartTime={} --Freq={} --f1dot={} --f2dot={} --Alpha={} --Delta={} --refTime={} --DataFiles='{}' --outputLoudest='{}' --ephemEarth={} --ephemSun={}\"\n LoudestFile = \"loudest.temp\"\n helper_functions.run_commandline(\n cl_CFSv2.format(\n tstart,\n tend,\n F0,\n F1,\n F2,\n Alpha,\n Delta,\n tref,\n self.sftfilepattern,\n LoudestFile,\n self.earth_ephem,\n self.sun_ephem,\n )\n )\n loudest = read_par(LoudestFile, return_type=\"dict\")\n os.remove(LoudestFile)\n return loudest\n\n def write_atoms_to_file(self, fnamebase=\"\"):\n multiFatoms = getattr(self.FstatResults, \"multiFatoms\", None)\n if multiFatoms and multiFatoms[0]:\n dopplerName = lalpulsar.PulsarDopplerParams2String(self.PulsarDopplerParams)\n # fnameAtoms = os.path.join(self.outdir,'Fstatatoms_%s.dat' % dopplerName)\n fnameAtoms = fnamebase + \"_Fstatatoms_%s.dat\" % dopplerName\n fo = lal.FileOpen(fnameAtoms, \"w\")\n lalpulsar.write_MultiFstatAtoms_to_fp(fo, multiFatoms[0])\n del fo # instead of lal.FileClose() which is not SWIG-exported\n else:\n raise RuntimeError(\n \"Cannot print atoms vector to file: no FstatResults.multiFatoms, or it is None!\"\n )\n\n def __del__(self):\n \"\"\"\n In pyCuda case without autoinit,\n we need to make sure the context is removed at the end\n \"\"\"\n if hasattr(self, \"gpu_context\") and self.gpu_context:\n self.gpu_context.detach()\n\n\nclass SemiCoherentSearch(ComputeFstat):\n \"\"\" A semi-coherent search \"\"\"\n\n @helper_functions.initializer\n def __init__(\n self,\n label,\n outdir,\n tref,\n nsegs=None,\n sftfilepattern=None,\n binary=False,\n BSGL=False,\n minStartTime=None,\n maxStartTime=None,\n minCoverFreq=None,\n maxCoverFreq=None,\n detectors=None,\n injectSources=None,\n assumeSqrtSX=None,\n SSBprec=None,\n ):\n \"\"\"\n Parameters\n ----------\n label, outdir: str\n A label and directory to read/write data from/to.\n tref, minStartTime, maxStartTime: int\n GPS seconds of the reference time, and start and end of the data.\n nsegs: int\n The (fixed) number of segments\n sftfilepattern: str\n Pattern to match SFTs using wildcards (*?) and ranges [0-9];\n mutiple patterns can be given separated by colons.\n\n For all other parameters, see pyfstat.ComputeFStat.\n \"\"\"\n\n self.fs_file_name = \"{}/{}_FS.dat\".format(self.outdir, self.label)\n self.set_ephemeris_files()\n self.transientWindowType = \"rect\"\n self.t0Band = None\n self.tauBand = None\n self.tCWFstatMapVersion = \"lal\"\n self.cudaDeviceName = None\n self.init_computefstatistic_single_point()\n self.init_semicoherent_parameters()\n\n def init_semicoherent_parameters(self):\n logging.info(\n (\n \"Initialising semicoherent parameters from {} to {} in\" \" {} segments\"\n ).format(self.minStartTime, self.maxStartTime, self.nsegs)\n )\n self.transientWindowType = \"rect\"\n self.whatToCompute = lalpulsar.FSTATQ_2F + lalpulsar.FSTATQ_ATOMS_PER_DET\n self.tboundaries = np.linspace(\n self.minStartTime, self.maxStartTime, self.nsegs + 1\n )\n self.Tcoh = self.tboundaries[1] - self.tboundaries[0]\n\n if hasattr(self, \"SFT_timestamps\"):\n if self.tboundaries[0] < self.SFT_timestamps[0]:\n logging.debug(\n \"Semi-coherent start time {} before first SFT timestamp {}\".format(\n self.tboundaries[0], self.SFT_timestamps[0]\n )\n )\n if self.tboundaries[-1] > self.SFT_timestamps[-1]:\n logging.debug(\n \"Semi-coherent end time {} after last SFT timestamp {}\".format(\n self.tboundaries[-1], self.SFT_timestamps[-1]\n )\n )\n\n def get_semicoherent_twoF(\n self,\n F0,\n F1,\n F2,\n Alpha,\n Delta,\n asini=None,\n period=None,\n ecc=None,\n tp=None,\n argp=None,\n record_segments=False,\n ):\n \"\"\" Returns twoF or ln(BSGL) semi-coherently at a single point \"\"\"\n\n self.PulsarDopplerParams.fkdot = np.array([F0, F1, F2, 0, 0, 0, 0])\n self.PulsarDopplerParams.Alpha = float(Alpha)\n self.PulsarDopplerParams.Delta = float(Delta)\n if self.binary:\n self.PulsarDopplerParams.asini = float(asini)\n self.PulsarDopplerParams.period = float(period)\n self.PulsarDopplerParams.ecc = float(ecc)\n self.PulsarDopplerParams.tp = float(tp)\n self.PulsarDopplerParams.argp = float(argp)\n\n lalpulsar.ComputeFstat(\n self.FstatResults,\n self.FstatInput,\n self.PulsarDopplerParams,\n 1,\n self.whatToCompute,\n )\n\n # if not self.transientWindowType:\n # if self.BSGL is False:\n # return self.FstatResults.twoF[0]\n # twoF = np.float(self.FstatResults.twoF[0])\n # self.twoFX[0] = self.FstatResults.twoFPerDet(0)\n # self.twoFX[1] = self.FstatResults.twoFPerDet(1)\n # log10_BSGL = lalpulsar.ComputeBSGL(twoF, self.twoFX,\n # self.BSGLSetup)\n # return log10_BSGL/np.log10(np.exp(1))\n\n detStat = 0\n if record_segments:\n self.detStat_per_segment = []\n\n self.windowRange.tau = int(self.Tcoh) # TYPE UINT4\n for tstart in self.tboundaries[:-1]:\n d_detStat = self._get_per_segment_det_stat(tstart)\n detStat += d_detStat\n if record_segments:\n self.detStat_per_segment.append(d_detStat)\n\n return detStat\n\n def _get_per_segment_det_stat(self, tstart):\n self.windowRange.t0 = int(tstart) # TYPE UINT4\n\n FS = lalpulsar.ComputeTransientFstatMap(\n self.FstatResults.multiFatoms[0], self.windowRange, False\n )\n\n if self.BSGL is False:\n d_detStat = 2 * FS.F_mn.data[0][0]\n else:\n FstatResults_single = copy.copy(self.FstatResults)\n FstatResults_single.lenth = 1\n FstatResults_single.data = self.FstatResults.multiFatoms[0].data[0]\n FS0 = lalpulsar.ComputeTransientFstatMap(\n FstatResults_single.multiFatoms[0], self.windowRange, False\n )\n FstatResults_single.data = self.FstatResults.multiFatoms[0].data[1]\n FS1 = lalpulsar.ComputeTransientFstatMap(\n FstatResults_single.multiFatoms[0], self.windowRange, False\n )\n\n self.twoFX[0] = 2 * FS0.F_mn.data[0][0]\n self.twoFX[1] = 2 * FS1.F_mn.data[0][0]\n log10_BSGL = lalpulsar.ComputeBSGL(\n 2 * FS.F_mn.data[0][0], self.twoFX, self.BSGLSetup\n )\n d_detStat = log10_BSGL / np.log10(np.exp(1))\n if np.isnan(d_detStat):\n logging.debug(\"NaNs in semi-coherent twoF treated as zero\")\n d_detStat = 0\n\n return d_detStat\n\n\nclass SemiCoherentGlitchSearch(ComputeFstat):\n \"\"\" A semi-coherent glitch search\n\n This implements a basic `semi-coherent glitch F-stat in which the data\n is divided into segments either side of the proposed glitches and the\n fully-coherent F-stat in each segment is summed to give the semi-coherent\n F-stat\n \"\"\"\n\n @helper_functions.initializer\n def __init__(\n self,\n label,\n outdir,\n tref,\n minStartTime,\n maxStartTime,\n nglitch=1,\n sftfilepattern=None,\n theta0_idx=0,\n BSGL=False,\n minCoverFreq=None,\n maxCoverFreq=None,\n assumeSqrtSX=None,\n detectors=None,\n SSBprec=None,\n injectSources=None,\n ):\n \"\"\"\n Parameters\n ----------\n label, outdir: str\n A label and directory to read/write data from/to.\n tref, minStartTime, maxStartTime: int\n GPS seconds of the reference time, and start and end of the data.\n nglitch: int\n The (fixed) number of glitches; this can zero, but occasionally\n this causes issue (in which case just use ComputeFstat).\n sftfilepattern: str\n Pattern to match SFTs using wildcards (*?) and ranges [0-9];\n mutiple patterns can be given separated by colons.\n theta0_idx, int\n Index (zero-based) of which segment the theta refers to - uyseful\n if providing a tight prior on theta to allow the signal to jump\n too theta (and not just from)\n\n For all other parameters, see pyfstat.ComputeFStat.\n \"\"\"\n\n self.fs_file_name = \"{}/{}_FS.dat\".format(self.outdir, self.label)\n self.set_ephemeris_files()\n self.transientWindowType = \"rect\"\n self.t0Band = None\n self.tauBand = None\n self.tCWFstatMapVersion = \"lal\"\n self.cudaDeviceName = None\n self.binary = False\n self.init_computefstatistic_single_point()\n\n def get_semicoherent_nglitch_twoF(self, F0, F1, F2, Alpha, Delta, *args):\n \"\"\" Returns the semi-coherent glitch summed twoF \"\"\"\n\n args = list(args)\n tboundaries = [self.minStartTime] + args[-self.nglitch :] + [self.maxStartTime]\n delta_F0s = args[-3 * self.nglitch : -2 * self.nglitch]\n delta_F1s = args[-2 * self.nglitch : -self.nglitch]\n delta_F2 = np.zeros(len(delta_F0s))\n delta_phi = np.zeros(len(delta_F0s))\n theta = [0, F0, F1, F2]\n delta_thetas = np.atleast_2d(\n np.array([delta_phi, delta_F0s, delta_F1s, delta_F2]).T\n )\n\n thetas = self._calculate_thetas(\n theta, delta_thetas, tboundaries, theta0_idx=self.theta0_idx\n )\n\n twoFSum = 0\n for i, theta_i_at_tref in enumerate(thetas):\n ts, te = tboundaries[i], tboundaries[i + 1]\n if te - ts > 1800:\n twoFVal = self.get_fullycoherent_twoF(\n ts,\n te,\n theta_i_at_tref[1],\n theta_i_at_tref[2],\n theta_i_at_tref[3],\n Alpha,\n Delta,\n )\n twoFSum += twoFVal\n\n if np.isfinite(twoFSum):\n return twoFSum\n else:\n return -np.inf\n\n def compute_glitch_fstat_single(\n self, F0, F1, F2, Alpha, Delta, delta_F0, delta_F1, tglitch\n ):\n \"\"\" Returns the semi-coherent glitch summed twoF for nglitch=1\n\n Note: OBSOLETE, used only for testing\n \"\"\"\n\n theta = [F0, F1, F2]\n delta_theta = [delta_F0, delta_F1, 0]\n tref = self.tref\n\n theta_at_glitch = self._shift_coefficients(theta, tglitch - tref)\n theta_post_glitch_at_glitch = theta_at_glitch + delta_theta\n theta_post_glitch = self._shift_coefficients(\n theta_post_glitch_at_glitch, tref - tglitch\n )\n\n twoFsegA = self.get_fullycoherent_twoF(\n self.minStartTime, tglitch, theta[0], theta[1], theta[2], Alpha, Delta\n )\n\n if tglitch == self.maxStartTime:\n return twoFsegA\n\n twoFsegB = self.get_fullycoherent_twoF(\n tglitch,\n self.maxStartTime,\n theta_post_glitch[0],\n theta_post_glitch[1],\n theta_post_glitch[2],\n Alpha,\n Delta,\n )\n\n return twoFsegA + twoFsegB\n" ]
[ [ "matplotlib.use", "numpy.max", "numpy.array", "numpy.dot", "numpy.isnan", "numpy.zeros", "numpy.float", "numpy.min", "matplotlib.pyplot.subplots", "numpy.exp", "numpy.argmax", "numpy.atleast_1d", "numpy.isfinite", "matplotlib.pyplot.tight_layout", "numpy.abs", "numpy.linspace", "numpy.insert" ] ]
AnimeshKoratana/blurryface
[ "c6cb5feec02f6d5af3acb1678336800390715d65" ]
[ "facenet_pytorch/models/inception_resnet_v1.py" ]
[ "import torch\nfrom torch import nn\nfrom torch.nn import functional as F\nimport requests\nfrom requests.adapters import HTTPAdapter\nimport os\n\n\nclass BasicConv2d(nn.Module):\n\n def __init__(self, in_planes, out_planes, kernel_size, stride, padding=0):\n super().__init__()\n self.conv = nn.Conv2d(\n in_planes, out_planes,\n kernel_size=kernel_size, stride=stride,\n padding=padding, bias=False\n ) # verify bias false\n self.bn = nn.BatchNorm2d(\n out_planes,\n eps=0.001, # value found in tensorflow\n momentum=0.1, # default pytorch value\n affine=True\n )\n self.relu = nn.ReLU(inplace=False)\n\n def forward(self, x):\n x = self.conv(x)\n x = self.bn(x)\n x = self.relu(x)\n return x\n\n\nclass Block35(nn.Module):\n \n def __init__(self, scale=1.0):\n super().__init__()\n\n self.scale = scale\n\n self.branch0 = BasicConv2d(256, 32, kernel_size=1, stride=1)\n\n self.branch1 = nn.Sequential(\n BasicConv2d(256, 32, kernel_size=1, stride=1),\n BasicConv2d(32, 32, kernel_size=3, stride=1, padding=1)\n )\n\n self.branch2 = nn.Sequential(\n BasicConv2d(256, 32, kernel_size=1, stride=1),\n BasicConv2d(32, 32, kernel_size=3, stride=1, padding=1),\n BasicConv2d(32, 32, kernel_size=3, stride=1, padding=1)\n )\n\n self.conv2d = nn.Conv2d(96, 256, kernel_size=1, stride=1)\n self.relu = nn.ReLU(inplace=False)\n\n def forward(self, x):\n x0 = self.branch0(x)\n x1 = self.branch1(x)\n x2 = self.branch2(x)\n out = torch.cat((x0, x1, x2), 1)\n out = self.conv2d(out)\n out = out * self.scale + x\n out = self.relu(out)\n return out\n\n\nclass Block17(nn.Module):\n\n def __init__(self, scale=1.0):\n super().__init__()\n\n self.scale = scale\n\n self.branch0 = BasicConv2d(896, 128, kernel_size=1, stride=1)\n\n self.branch1 = nn.Sequential(\n BasicConv2d(896, 128, kernel_size=1, stride=1),\n BasicConv2d(128, 128, kernel_size=(1,7), stride=1, padding=(0,3)),\n BasicConv2d(128, 128, kernel_size=(7,1), stride=1, padding=(3,0))\n )\n\n self.conv2d = nn.Conv2d(256, 896, kernel_size=1, stride=1)\n self.relu = nn.ReLU(inplace=False)\n\n def forward(self, x):\n x0 = self.branch0(x)\n x1 = self.branch1(x)\n out = torch.cat((x0, x1), 1)\n out = self.conv2d(out)\n out = out * self.scale + x\n out = self.relu(out)\n return out\n\n\nclass Block8(nn.Module):\n\n def __init__(self, scale=1.0, noReLU=False):\n super().__init__()\n\n self.scale = scale\n self.noReLU = noReLU\n\n self.branch0 = BasicConv2d(1792, 192, kernel_size=1, stride=1)\n\n self.branch1 = nn.Sequential(\n BasicConv2d(1792, 192, kernel_size=1, stride=1),\n BasicConv2d(192, 192, kernel_size=(1,3), stride=1, padding=(0,1)),\n BasicConv2d(192, 192, kernel_size=(3,1), stride=1, padding=(1,0))\n )\n\n self.conv2d = nn.Conv2d(384, 1792, kernel_size=1, stride=1)\n if not self.noReLU:\n self.relu = nn.ReLU(inplace=False)\n\n def forward(self, x):\n x0 = self.branch0(x)\n x1 = self.branch1(x)\n out = torch.cat((x0, x1), 1)\n out = self.conv2d(out)\n out = out * self.scale + x\n if not self.noReLU:\n out = self.relu(out)\n return out\n\n\nclass Mixed_6a(nn.Module):\n\n def __init__(self):\n super().__init__()\n\n self.branch0 = BasicConv2d(256, 384, kernel_size=3, stride=2)\n\n self.branch1 = nn.Sequential(\n BasicConv2d(256, 192, kernel_size=1, stride=1),\n BasicConv2d(192, 192, kernel_size=3, stride=1, padding=1),\n BasicConv2d(192, 256, kernel_size=3, stride=2)\n )\n\n self.branch2 = nn.MaxPool2d(3, stride=2)\n\n def forward(self, x):\n x0 = self.branch0(x)\n x1 = self.branch1(x)\n x2 = self.branch2(x)\n out = torch.cat((x0, x1, x2), 1)\n return out\n\n\nclass Mixed_7a(nn.Module):\n\n def __init__(self):\n super().__init__()\n\n self.branch0 = nn.Sequential(\n BasicConv2d(896, 256, kernel_size=1, stride=1),\n BasicConv2d(256, 384, kernel_size=3, stride=2)\n )\n\n self.branch1 = nn.Sequential(\n BasicConv2d(896, 256, kernel_size=1, stride=1),\n BasicConv2d(256, 256, kernel_size=3, stride=2)\n )\n\n self.branch2 = nn.Sequential(\n BasicConv2d(896, 256, kernel_size=1, stride=1),\n BasicConv2d(256, 256, kernel_size=3, stride=1, padding=1),\n BasicConv2d(256, 256, kernel_size=3, stride=2)\n )\n\n self.branch3 = nn.MaxPool2d(3, stride=2)\n\n def forward(self, x):\n x0 = self.branch0(x)\n x1 = self.branch1(x)\n x2 = self.branch2(x)\n x3 = self.branch3(x)\n out = torch.cat((x0, x1, x2, x3), 1)\n return out\n\n\nclass InceptionResnetV1(nn.Module):\n \"\"\"Inception Resnet V1 model with optional loading of pretrained weights.\n\n Model parameters can be loaded based on pretraining on the VGGFace2 or CASIA-Webface\n datasets.\n \n Keyword Arguments:\n pretrained {str} -- Pretraining dataset. Either 'vggface2' or 'casia-webface'. (default: {None})\n classify {bool} -- Whether the model should output classification probabilities or feature.\n embeddings (default: {False})\n num_classes {int} -- Number of output classes. Ignored if 'pretrained' is set. (default: {1001})\n \"\"\"\n def __init__(self, pretrained=None, classify=False, num_classes=1001):\n super().__init__()\n\n # Set simple attributes\n self.pretrained = pretrained\n self.classify = classify\n self.num_classes = num_classes\n\n if pretrained == 'vggface2':\n self.num_classes = 8631\n elif pretrained == 'casia-webface':\n self.num_classes = 10575\n \n # Define layers\n self.conv2d_1a = BasicConv2d(3, 32, kernel_size=3, stride=2)\n self.conv2d_2a = BasicConv2d(32, 32, kernel_size=3, stride=1)\n self.conv2d_2b = BasicConv2d(32, 64, kernel_size=3, stride=1, padding=1)\n self.maxpool_3a = nn.MaxPool2d(3, stride=2)\n self.conv2d_3b = BasicConv2d(64, 80, kernel_size=1, stride=1)\n self.conv2d_4a = BasicConv2d(80, 192, kernel_size=3, stride=1)\n self.conv2d_4b = BasicConv2d(192, 256, kernel_size=3, stride=2)\n self.repeat_1 = nn.Sequential(\n Block35(scale=0.17),\n Block35(scale=0.17),\n Block35(scale=0.17),\n Block35(scale=0.17),\n Block35(scale=0.17),\n )\n self.mixed_6a = Mixed_6a()\n self.repeat_2 = nn.Sequential(\n Block17(scale=0.10),\n Block17(scale=0.10),\n Block17(scale=0.10),\n Block17(scale=0.10),\n Block17(scale=0.10),\n Block17(scale=0.10),\n Block17(scale=0.10),\n Block17(scale=0.10),\n Block17(scale=0.10),\n Block17(scale=0.10),\n )\n self.mixed_7a = Mixed_7a()\n self.repeat_3 = nn.Sequential(\n Block8(scale=0.20),\n Block8(scale=0.20),\n Block8(scale=0.20),\n Block8(scale=0.20),\n Block8(scale=0.20),\n )\n self.block8 = Block8(noReLU=True)\n self.avgpool_1a = nn.AdaptiveAvgPool2d(1)\n self.last_linear = nn.Linear(1792, 512, bias=False)\n self.last_bn = nn.BatchNorm1d(512, eps=0.001, momentum=0.1, affine=True)\n\n self.logits = nn.Linear(512, self.num_classes)\n self.softmax = nn.Softmax()\n\n if pretrained is not None:\n load_weights(self, pretrained)\n\n def forward(self, x):\n x = self.conv2d_1a(x)\n x = self.conv2d_2a(x)\n x = self.conv2d_2b(x)\n x = self.maxpool_3a(x)\n x = self.conv2d_3b(x)\n x = self.conv2d_4a(x)\n x = self.conv2d_4b(x)\n x = self.repeat_1(x)\n x = self.mixed_6a(x)\n x = self.repeat_2(x)\n x = self.mixed_7a(x)\n x = self.repeat_3(x)\n x = self.block8(x)\n x = self.avgpool_1a(x)\n x = self.last_linear(x.view(x.shape[0], -1))\n x = self.last_bn(x)\n x = F.normalize(x, p=2, dim=1)\n if self.classify:\n x = self.logits(x)\n x = self.softmax(x)\n return x\n\n\ndef load_weights(mdl, name):\n \"\"\"Download pretrained state_dict and load into model.\n \n Arguments:\n mdl {torch.nn.Module} -- Pytorch model.\n name {str} -- Name of dataset that was used to generate pretrained state_dict.\n \n Raises:\n ValueError: If 'pretrained' not equal to 'vggface2' or 'casia-webface'.\n \"\"\"\n if name == 'vggface2':\n features_path = 'https://drive.google.com/uc?export=download&id=1cWLH_hPns8kSfMz9kKl9PsG5aNV2VSMn'\n logits_path = 'https://drive.google.com/uc?export=download&id=1mAie3nzZeno9UIzFXvmVZrDG3kwML46X'\n elif name == 'casia-webface':\n features_path = 'https://drive.google.com/uc?export=download&id=1LSHHee_IQj5W3vjBcRyVaALv4py1XaGy'\n logits_path = 'https://drive.google.com/uc?export=download&id=1QrhPgn1bGlDxAil2uc07ctunCQoDnCzT'\n else:\n raise ValueError('Pretrained models only exist for \"vggface2\" and \"casia-webface\"')\n\n torch_home = get_torch_home()\n model_dir = os.path.join(torch_home, 'checkpoints')\n os.makedirs(model_dir, exist_ok=True)\n \n state_dict = {}\n for i, path in enumerate([features_path, logits_path]):\n cached_file = os.path.join(model_dir, '{}_{}.pt'.format(name, path[-10:]))\n if not os.path.exists(cached_file):\n print('Downloading parameters ({}/2)'.format(i+1))\n s = requests.Session()\n s.mount('https://', HTTPAdapter(max_retries=10))\n r = s.get(path, allow_redirects=True)\n with open(cached_file, 'wb') as f:\n f.write(r.content)\n state_dict.update(torch.load(cached_file))\n \n mdl.load_state_dict(state_dict)\n\n\ndef get_torch_home():\n torch_home = os.path.expanduser(\n os.getenv(\n 'TORCH_HOME',\n os.path.join(os.getenv('XDG_CACHE_HOME', '~/.cache'), 'torch')\n )\n )\n return torch_home\n" ]
[ [ "torch.nn.Linear", "torch.nn.functional.normalize", "torch.cat", "torch.nn.Softmax", "torch.nn.MaxPool2d", "torch.nn.BatchNorm2d", "torch.nn.ReLU", "torch.nn.Conv2d", "torch.nn.BatchNorm1d", "torch.load", "torch.nn.AdaptiveAvgPool2d" ] ]
astatt/azplugins
[ "cc3b613ff5a79e166149b5454bff2d765019bde5" ]
[ "azplugins/test-py/test_evaporate_particles.py" ]
[ "# Copyright (c) 2018-2020, Michael P. Howard\n# Copyright (c) 2021-2022, Auburn University\n# This file is part of the azplugins project, released under the Modified BSD License.\n\nimport hoomd\nfrom hoomd import md\nhoomd.context.initialize()\ntry:\n from hoomd import azplugins\nexcept ImportError:\n import azplugins\nimport unittest\nimport numpy as np\n\nclass evaporate_particles_tests(unittest.TestCase):\n def setUp(self):\n snap = hoomd.data.make_snapshot(N=4, box=hoomd.data.boxdim(L=20), particle_types=['A','B','C'])\n if hoomd.comm.get_rank() == 0:\n snap.particles.position[:,0] = (-5.,-5.,5.,5.)\n snap.particles.position[:,2] = (-7.5,2.5,4.5,3.)\n snap.particles.typeid[:] = [0,1,0,2]\n\n if hoomd.comm.get_num_ranks() > 1:\n hoomd.comm.decomposition(nx=2, ny=1, nz=1)\n\n self.s = hoomd.init.read_snapshot(snap)\n self.u = azplugins.evaporate.particles(solvent='A', evaporated='B', lo=-5.0, hi=5.0, seed=42)\n\n # test for basic initialization and call of cpp updater\n def test_basic(self):\n self.assertEqual(self.u.cpp_updater.outside, 0)\n self.assertEqual(self.u.cpp_updater.inside, 1)\n self.assertAlmostEqual(self.u.cpp_updater.lo, -5.0, 5)\n self.assertAlmostEqual(self.u.cpp_updater.hi, 5.0, 5)\n\n # should not throw\n self.u.cpp_updater.update(0)\n\n # test error handling for solvent type parameter\n def test_set_solvent(self):\n # set params should switch inside type and leave others alone\n self.u.set_params(solvent='C')\n self.assertEqual(self.u.cpp_updater.outside, 2)\n self.assertEqual(self.u.cpp_updater.inside, 1)\n self.assertAlmostEqual(self.u.cpp_updater.lo, -5.0, 5)\n self.assertAlmostEqual(self.u.cpp_updater.hi, 5.0, 5)\n\n # update call should still be safe\n self.u.cpp_updater.update(0)\n\n # cannot have same type inside and outside types\n with self.assertRaises(ValueError):\n self.u.set_params(solvent='B')\n\n # cannot set a nonexistent type\n with self.assertRaises(ValueError):\n self.u.set_params(solvent='D')\n\n # test error handling for evaporated type parameter\n def test_set_evaporated(self):\n # set params should switch outside type and leave others alone\n self.u.set_params(evaporated='C')\n self.assertEqual(self.u.cpp_updater.outside, 0)\n self.assertEqual(self.u.cpp_updater.inside, 2)\n self.assertAlmostEqual(self.u.cpp_updater.lo, -5.0, 5)\n self.assertAlmostEqual(self.u.cpp_updater.hi, 5.0, 5)\n\n # update call should still be safe\n self.u.cpp_updater.update(0)\n\n # cannot have same type inside and outside types\n with self.assertRaises(ValueError):\n self.u.set_params(evaporated='A')\n\n # cannot set a nonexistent type\n with self.assertRaises(ValueError):\n self.u.set_params(evaporated='D')\n\n # test error handling for lo parameter\n def test_set_lo(self):\n # set params should update lo of region and leave others alone\n self.u.set_params(lo=-7.0)\n self.assertEqual(self.u.cpp_updater.outside, 0)\n self.assertEqual(self.u.cpp_updater.inside, 1)\n self.assertAlmostEqual(self.u.cpp_updater.lo, -7.0, 5)\n self.assertAlmostEqual(self.u.cpp_updater.hi, 5.0, 5)\n\n # update call is still safe\n self.u.cpp_updater.update(0)\n\n # region cannot lie above hi\n with self.assertRaises(ValueError):\n self.u.set_params(lo=6.0)\n\n # region cannot lie outside box, caught at runtime\n self.u.set_params(lo=-11.0)\n with self.assertRaises(RuntimeError):\n self.u.cpp_updater.update(1)\n\n # test error handling for hi parameter\n def test_set_hi(self):\n # set params should update hi of region and leave others alone\n self.u.set_params(hi=7.0)\n self.assertEqual(self.u.cpp_updater.outside, 0)\n self.assertEqual(self.u.cpp_updater.inside, 1)\n self.assertAlmostEqual(self.u.cpp_updater.lo, -5.0, 5)\n self.assertAlmostEqual(self.u.cpp_updater.hi, 7.0, 5)\n\n # update call is still safe\n self.u.cpp_updater.update(0)\n\n # region cannot lie below lo\n with self.assertRaises(ValueError):\n self.u.set_params(hi=-6.0)\n\n # region cannot lie outside box, caught at runtime\n self.u.set_params(hi=11.0)\n with self.assertRaises(RuntimeError):\n self.u.cpp_updater.update(1)\n\n # test details of the type changing algorithm\n def test_change_types(self):\n # require initial types are set correctly\n snap = self.s.take_snapshot(all=True)\n if hoomd.comm.get_rank() == 0:\n np.testing.assert_array_equal(snap.particles.typeid[:], [0,1,0,2])\n\n # first run should evaporate the last particle\n hoomd.run(1)\n snap = self.s.take_snapshot(all=True)\n if hoomd.comm.get_rank() == 0:\n np.testing.assert_array_equal(snap.particles.typeid, [0,1,1,2])\n\n # make sure multiple particles can be evaporated at once\n if hoomd.comm.get_rank() == 0:\n snap.particles.typeid[:-1] = (0,0,0)\n self.s.restore_snapshot(snap)\n hoomd.run(1)\n snap = self.s.take_snapshot(all=True)\n if hoomd.comm.get_rank() == 0:\n np.testing.assert_array_equal(snap.particles.typeid, [0,1,1,2])\n\n # make sure at least one particle gets evaporated with limit set\n # this is a random choice of the number generator, so we just count the number of ones\n self.u.set_params(Nmax=1)\n if hoomd.comm.get_rank() == 0:\n snap.particles.typeid[:-1] = (0,0,0)\n self.s.restore_snapshot(snap)\n hoomd.run(1)\n snap = self.s.take_snapshot(all=True)\n if hoomd.comm.get_rank() == 0:\n self.assertEqual(list(snap.particles.typeid).count(1), 1)\n\n # test that nothing quirky happens with empty region\n def test_empty_region(self):\n # check first with particles in region, but none of type to process\n snap = self.s.take_snapshot(all=True)\n if hoomd.comm.get_rank() == 0:\n snap.particles.typeid[:] = (2,2,2,2)\n self.s.restore_snapshot(snap)\n hoomd.run(1)\n snap = self.s.take_snapshot(all=True)\n if hoomd.comm.get_rank() == 0:\n np.testing.assert_array_equal(snap.particles.typeid, [2,2,2,2])\n\n # now check with particles of solvent type, but outside evaporation region\n if hoomd.comm.get_rank() == 0:\n snap.particles.position[:,2] = (-7.5, -7.5, -7.5, -7.5)\n snap.particles.typeid[:] = (0,0,0,0)\n self.s.restore_snapshot(snap)\n hoomd.run(1)\n snap = self.s.take_snapshot(all=True)\n if hoomd.comm.get_rank() == 0:\n np.testing.assert_array_equal(snap.particles.typeid, (0,0,0,0))\n\n # test box change signal\n def test_box_change(self):\n snap = self.s.take_snapshot(all=True)\n if hoomd.comm.get_rank() == 0:\n snap.particles.position[:,2] = [-2., 0., 2. ,0.]\n self.s.restore_snapshot(snap)\n hoomd.run(1)\n\n # shrink box smaller than region, which should trigger signal to check\n # box and cause a runtime error\n hoomd.update.box_resize(L=5.0, period=None)\n with self.assertRaises(RuntimeError):\n hoomd.run(1)\n\n def tearDown(self):\n del self.s, self.u\n hoomd.context.initialize()\n\nclass evaporate_particles_big_test(unittest.TestCase):\n # put all particles into the deletion zone\n def setUp(self):\n snap = hoomd.data.make_snapshot(N=5000, box=hoomd.data.boxdim(L=20), particle_types=['A','B'])\n if hoomd.comm.get_rank() == 0:\n # some in -x, some in +x in MPI\n snap.particles.position[:500,0] = -5.\n snap.particles.position[500:,0] = 5.\n snap.particles.position[:,2] = 0.\n snap.particles.typeid[:] = np.zeros(snap.particles.N)\n\n if hoomd.comm.get_num_ranks() > 1:\n hoomd.comm.decomposition(nx=2, ny=1, nz=1)\n\n self.s = hoomd.init.read_snapshot(snap)\n self.u = azplugins.evaporate.particles(solvent='A', evaporated='B', lo=-5.0, hi=5.0, seed=771991)\n\n # test that all particles can be evaporated at once\n def test_all(self):\n hoomd.run(1)\n snap = self.s.take_snapshot(all=True)\n if hoomd.comm.get_rank() == 0:\n np.testing.assert_array_equal(snap.particles.typeid, np.ones(snap.particles.N))\n\n def test_limit(self):\n self.u.set_params(Nmax=50)\n\n hoomd.run(1)\n snap = self.s.take_snapshot(all=True)\n if hoomd.comm.get_rank() == 0:\n self.assertEqual(list(snap.particles.typeid).count(1), 50)\n\n hoomd.run(1)\n snap = self.s.take_snapshot(all=True)\n if hoomd.comm.get_rank() == 0:\n self.assertEqual(list(snap.particles.typeid).count(1), 100)\n\n self.u.set_params(Nmax=900)\n hoomd.run(1)\n snap = self.s.take_snapshot(all=True)\n if hoomd.comm.get_rank() == 0:\n self.assertEqual(list(snap.particles.typeid).count(1), 1000)\n\n self.u.set_params(Nmax=4000)\n hoomd.run(1)\n snap = self.s.take_snapshot(all=True)\n if hoomd.comm.get_rank() == 0:\n self.assertEqual(list(snap.particles.typeid).count(1), 5000)\n np.testing.assert_array_equal(snap.particles.typeid, np.ones(snap.particles.N))\n\n hoomd.run(1)\n snap = self.s.take_snapshot(all=True)\n if hoomd.comm.get_rank() == 0:\n np.testing.assert_array_equal(snap.particles.typeid, np.ones(snap.particles.N))\n\n def tearDown(self):\n del self.s, self.u\n hoomd.context.initialize()\n\nif __name__ == '__main__':\n unittest.main(argv = ['test.py', '-v'])\n" ]
[ [ "numpy.testing.assert_array_equal", "numpy.ones", "numpy.zeros" ] ]
Cai-Lab-at-University-of-Michigan/MiCV
[ "8d18a1f177d16a5b09f54c211a0c2b1238d6ce01" ]
[ "src/tasks/tasks.py" ]
[ "from sendgrid import SendGridAPIClient\nfrom sendgrid.helpers.mail import Mail\n\nimport zarr\nfrom numcodecs import Blosc\nimport scipy.sparse as sp\n\nfrom .celery import task_queue\nfrom layouts import demo\nif (demo == False):\n try:\n from configmodule.production_config import ProductionConfig as FlaskConfig\n except:\n from configmodule.default_config import DefaultConfig as FlaskConfig\nelse:\n from configmodule.default_config import DefaultConfig as FlaskConfig\n\n@task_queue.task\ndef send_flask_mail(subject=None, sender=None,\n recipients=None, body=None,\n html=None):\n print(\"[DEBUG] running send_flask_mail\")\n # Get mail config\n c = FlaskConfig()\n\n # Construct the message\n message = Mail(\n from_email=sender,\n to_emails=recipients,\n subject=subject,\n plain_text_content=body,\n html_content=html\n )\n try:\n sg = SendGridAPIClient(c.SENDGRID_API_KEY)\n print(\"[DEBUG] apikey: \" + str(c.SENDGRID_API_KEY))\n response = sg.send(message)\n print(response.status_code)\n print(response.body)\n print(response.headers)\n except Exception as e:\n print(e) \n return None\n\n## Helper zarr caching\n@task_queue.task\ndef write_dense(zarr_cache_dir, key, dense_name, chunk_factors):\n compressor = Blosc(cname='blosclz', clevel=3, shuffle=Blosc.SHUFFLE)\n store = zarr.open(zarr_cache_dir, mode='a')\n \n if (len(store[key]) == 3):\n # assume csr sparse matrix - parse as such\n array_keys = list(store[key].array_keys())\n X = sp.csr_matrix((store[key + \"/\" + array_keys[0]], \n store[key + \"/\" + array_keys[1]], store[key + \"/\" + array_keys[2]]))\n else:\n # assume dense matrix\n # TODO: checking for other cases of sparse matrices/mixed groups\n X = store[key]\n if ((not (dense_name in store))\n or (X.shape != store[dense_name].shape)) :\n store.create_dataset(dense_name, shape=X.shape,\n dtype=X.dtype, fill_value=0, \n chunks=(int(X.shape[0]/chunk_factors[0]), int(X.shape[1]/chunk_factors[1])),\n compressor=compressor, overwrite=True)\n if(sp.issparse(X) is True):\n X = X.tocoo()\n store[dense_name].set_coordinate_selection((X.row, X.col), X.data)\n else:\n store[dense_name] = X\n return None\n### end celery queue task function definitions" ]
[ [ "scipy.sparse.issparse", "scipy.sparse.csr_matrix" ] ]
openneuropet/PET2BIDS
[ "bf88910059f0cc986c3fcb266e1c23c8c37c4eaf" ]
[ "pypet2bids/tests/test_helper_functions.py" ]
[ "import collections\nimport tempfile\nimport unittest\nimport pypet2bids.helper_functions as helper_functions\nfrom os import remove\nimport pandas\nfrom pathlib import Path\nfrom os.path import join\n\n# collect config files\n# fields to check for\nmodule_folder = Path(__file__).parent.resolve()\npython_folder = module_folder.parent\npet2bids_folder = python_folder.parent\nmetadata_folder = join(pet2bids_folder, 'spreadsheet_conversion')\nsingle_subject_metadata_file = join(metadata_folder, 'single_subject_sheet', 'subject_metadata_example.xlsx')\n\nclass TestHelperFunctions(unittest.TestCase):\n @classmethod\n def setUp(cls) -> None:\n test_config_string = '''\n test_int=0\n test_int_list=[1,2,3,4]\n test_float=99.9\n test_float_list=[1.0,2.0,3.0,4.0]\n test_string=CharlieWorks\n test_string_list=['entry1', 'entry2', 'entry3', 'entry4']\n test_mixed_list=['a', 1, 2.0, 'longstring']\n '''\n cls.test_env_file_path = '.test_env'\n with open(cls.test_env_file_path, 'w') as outfile:\n outfile.write(test_config_string)\n\n cls.test_load = helper_functions.load_vars_from_config(cls.test_env_file_path)\n\n def test_load_vars_from_config(self):\n self.test_load = helper_functions.load_vars_from_config(self.test_env_file_path)\n self.assertEqual(type(self.test_load), collections.OrderedDict) # add assertion here\n\n def test_int(self):\n self.assertEqual(self.test_load['test_int'], 0)\n\n def test_float(self):\n self.assertEqual(self.test_load['test_float'], 99.9)\n\n def test_int_list(self):\n self.assertEqual(self.test_load['test_int_list'], [1, 2, 3, 4])\n\n def test_float_list(self):\n self.assertEqual(self.test_load['test_float_list'], [1.0, 2.0, 3.0, 4.0])\n\n def test_string(self):\n self.assertEqual(self.test_load['test_string'], 'CharlieWorks')\n\n def test_string_list(self):\n self.assertEqual(self.test_load['test_string_list'],\n ['entry1', 'entry2', 'entry3', 'entry4'])\n\n def test_mixed_list(self):\n self.assertEqual(self.test_load['test_mixed_list'],\n ['a', 1, 2.0, 'longstring'])\n\n @classmethod\n def tearDown(cls) -> None:\n remove(cls.test_env_file_path)\n\ndef test_open_metadata():\n # read in a known metadata spreadsheet\n test_dataframe = pandas.read_excel(single_subject_metadata_file)\n\n # read in the the same dataframe using the helper function\n metadata_dataframe = helper_functions.open_meta_data(single_subject_metadata_file)\n\n # assert that open metadata opens an excel spreadsheet\n pandas.testing.assert_frame_equal(test_dataframe, metadata_dataframe)\n\n # write the excel spreadsheet data to a csv and make sure the open_meta_data function\n # still works on that\n with tempfile.TemporaryDirectory():\n pass\n\ndef test_translate_metadata():\n test_translate_script_path = join(module_folder, 'metadata_excel_example_reader.py')\n\n test_output = helper_functions.translate_metadata(single_subject_metadata_file,test_translate_script_path)\n\n # values below manually parsed out of the file 'subject_metadata_example.xlsx'\n assert test_output['nifti_json']['ImageDecayCorrectionTime'] == 0\n assert test_output['nifti_json']['ReconMethodName'] == '3D-OSEM-PSF'\n assert test_output['nifti_json']['ReconMethodParameterLabels'] == ['subsets', 'iterations']\n assert test_output['nifti_json']['ReconMethodParameterUnits'] == ['none', 'none']\n assert test_output['nifti_json']['ReconMethodParameterValues'] == [16, 10]\n assert test_output['nifti_json']['ReconFilterType'] == 'none'\n\nif __name__ == '__main__':\n unittest.main()\n" ]
[ [ "pandas.testing.assert_frame_equal", "pandas.read_excel" ] ]
renardeinside/scout
[ "107a45410e501399a315bedf69482bf5b4812612" ]
[ "scout/nuclei.py" ]
[ "\"\"\"\nNuclei Module\n==============\n\nThis module performs nuclei detection, segmentation, and cytometry.\n\nThese include the following subcommands:\n\n - detect : detect all nuclei in image\n - segment : segment all detected nuclei\n - fluorescence : measure fluorescence for each cell\n - gate : assign cell-type labels by fluorescence thresholding\n - morphology : compute morphological features of segmented nuclei\n - name : assign names to each cell-type\n\n\"\"\"\n\nimport subprocess\nimport os\nimport warnings\nfrom functools import partial\nimport multiprocessing\nimport tempfile\nimport numpy as np\nimport pandas as pd\nimport zarr\nfrom scipy import ndimage as ndi\nfrom skimage import morphology\nfrom skimage.measure import regionprops\nfrom sklearn.neighbors import NearestNeighbors\nfrom tqdm import tqdm\nfrom scout import io\nfrom scout.preprocess import gaussian_blur_parallel\nfrom scout import detection\nfrom scout import utils\nfrom scout.utils import verbose_print\nfrom scout.synthetic import points_to_binary\nfrom scout.niche import name_cli, name_main\nimport matplotlib\n\ntry:\n matplotlib.use(\"tkagg\")\nexcept:\n pass\nimport matplotlib.pyplot as plt\nfrom matplotlib import colors\n\n\n# Nuclei segmentation\n\n\ndef _threshold_chunk(inputs, threshold, output):\n arr, start, chunks = inputs\n prob, _, stop = utils.extract_ghosted_chunk(arr, start, chunks, overlap=0)\n foreground = (prob > threshold).astype(np.uint8)\n utils.insert_box(output, start, stop, foreground)\n\n\ndef watershed_centers(image, centers, mask, **watershed_kwargs):\n seeds = points_to_binary(tuple(centers.T), image.shape, cval=1)\n markers = ndi.label(seeds)[0]\n labels = morphology.watershed(-image, markers, mask=mask, **watershed_kwargs)\n return labels\n\n\ndef _watershed_probability_chunk(\n input_tuple, output, centers, mask, overlap, **watershed_kwargs\n):\n arr, start_coord, chunks = input_tuple\n\n # extract ghosted chunk of data\n mask_overlap, start_ghosted, stop_ghosted = utils.extract_ghosted_chunk(\n mask, start_coord, chunks, overlap\n )\n if not np.any(mask_overlap):\n # # write zeros for blank chunk\n # start_local = start_coord - start_ghosted\n # stop_local = np.minimum(start_local + np.asarray(chunks), np.asarray(arr.shape) - start_ghosted)\n # binary_seg = np.zeros(tuple(stop_local - start_local), output.dtype)\n # stop_coord = start_coord + np.asarray(binary_seg.shape)\n # utils.insert_box(output, start_coord, stop_coord, binary_seg)\n return\n data_overlap, _, _ = utils.extract_ghosted_chunk(arr, start_coord, chunks, overlap)\n\n # Find seeds within the ghosted chunk\n centers_internal = utils.filter_points_in_box(centers, start_ghosted, stop_ghosted)\n centers_internal_local = centers_internal - start_ghosted\n # Skip if no centers in ghosted chunk\n if len(centers_internal) == 0:\n return\n\n # segment the chunk\n labels_overlap = watershed_centers(\n data_overlap, centers_internal_local, mask_overlap, watershed_line=True\n )\n binary_overlap = labels_overlap > 0\n # binary_overlap_eroded = ndi.binary_erosion(binary_overlap)\n\n # write the segmentation result\n start_local = start_coord - start_ghosted\n stop_local = np.minimum(\n start_local + np.asarray(chunks), np.asarray(arr.shape) - start_ghosted\n )\n # binary_seg = utils.extract_box(binary_overlap_eroded, start_local, stop_local)\n binary_seg = utils.extract_box(binary_overlap, start_local, stop_local)\n stop_coord = start_coord + np.asarray(binary_seg.shape)\n utils.insert_box(output, start_coord, stop_coord, binary_seg)\n\n\ndef watershed_centers_parallel(\n prob, centers, mask, output, chunks, overlap, nb_workers=None\n):\n f = partial(\n _watershed_probability_chunk,\n output=output,\n centers=centers,\n mask=mask,\n overlap=overlap,\n )\n utils.pmap_chunks(\n f, prob, chunks, nb_workers, use_imap=True, unordered=True, chunksize=10\n )\n # utils.pmap_chunks(f, prob, chunks, 2, use_imap=True)\n\n\n# Fluorescence sampling, statistics, and gating\n\n\ndef sample_intensity_cube(center, image, radius):\n start = [max(0, int(c - radius)) for c in center]\n stop = [min(int(c + radius + 1), d - 1) for c, d in zip(center, image.shape)]\n bbox = utils.extract_box(image, start, stop)\n return bbox.flatten()\n\n\ndef nuclei_centered_intensities(image, centers, radius, mode=\"cube\", nb_workers=None):\n if nb_workers is None:\n nb_workers = multiprocessing.cpu_count()\n\n if mode == \"cube\":\n f = partial(sample_intensity_cube, image=image, radius=radius)\n else:\n raise ValueError(\"Only cube sampling is currently supported\")\n\n with multiprocessing.Pool(nb_workers) as pool:\n intensities = list(tqdm(pool.imap(f, centers), total=centers.shape[0]))\n\n return intensities\n\n\ndef calculate_mfi(input):\n \"\"\"Calculate the Mean Fluorescence Intensity (MFI) for input list of nucleus-centered samples\n\n Parameters\n ----------\n input : list\n List of ndarrays containing image intensities near nuclei\n\n Returns\n -------\n output : ndarray\n 1D array of MFIs for each nucleus\n \"\"\"\n return np.asarray([x.mean() for x in input])\n\n\ndef calculate_stdev(input):\n \"\"\"Calculate the standard deviation for input list of nucleus-centered samples\n\n Parameters\n ----------\n input : list\n List of ndarrays containing image intensities near nuclei\n\n Returns\n -------\n output : ndarray\n 1D array of standard deviations for each nucleus\n \"\"\"\n return np.asarray([x.std() for x in input])\n\n\ndef threshold_mfi(mfi, threshold):\n positive_idx = np.where(mfi > threshold)[0]\n labels = np.zeros(mfi.shape, dtype=np.int)\n labels[positive_idx] = 1\n return labels\n\n\n# Nuclei morphological features\n\n\ndef segment_centroid(centroid, window_size, binary_seg, return_seg=False):\n window_size = np.asarray(window_size)\n\n # Extract ROI centered on centroid\n start = np.maximum(np.zeros(3), centroid - window_size // 2).astype(np.int)\n stop = np.minimum(np.asarray(binary_seg.shape), centroid + window_size // 2).astype(\n np.int\n )\n patch = utils.extract_box(binary_seg, start, stop)\n lbl, _ = ndi.label(patch)\n\n # Extract pixels with the same label as the centroid\n centroid_local = centroid - start\n value = lbl[centroid_local[0], centroid_local[1], centroid_local[2]]\n if value > 0:\n # print('Found segmentation!')\n single = (lbl == value).astype(np.uint8)\n else:\n print(\"No foreground on centroid point!\")\n single = np.zeros(patch.shape, np.uint8)\n single[centroid_local[0], centroid_local[1], centroid_local[2]] = 1\n\n # Compute morphological features\n region = regionprops(single)[0]\n center = region.centroid + start\n volume = region.area\n eq_diam = region.equivalent_diameter\n minor_length = region.minor_axis_length\n major_length = region.major_axis_length\n axis_ratio = major_length / np.clip(minor_length, 1, None)\n features = np.array(\n [\n center[0],\n center[1],\n center[2],\n volume,\n eq_diam,\n minor_length,\n major_length,\n axis_ratio,\n ]\n )\n\n # Pad to window_size if needed\n # This needs to happen after center of mass is computed because padding will offset from original start\n if single.shape != tuple(window_size):\n middle = window_size // 2\n start_offset = tuple(np.clip(middle - centroid_local, 0, None)) # pre-padding\n stop_offset = tuple(\n np.clip(middle - (stop - centroid), 0, None)\n ) # post-padding\n pad_width = tuple(zip(start_offset, stop_offset))\n single = np.pad(single, pad_width, \"constant\")\n\n if return_seg:\n return features, single\n else:\n return (features,)\n\n\ndef _segment_centroid(inputs):\n return segment_centroid(*inputs)\n\n\ndef morphological_features(seg):\n # Old code, replaced with centroid labeling\n props = regionprops(seg)\n nb_labels = len(props)\n centers = np.zeros((nb_labels, seg.ndim))\n volumes = np.zeros(nb_labels)\n eq_diams = np.zeros(nb_labels)\n minor_lengths = np.zeros(nb_labels)\n major_lengths = np.zeros(nb_labels)\n for i, region in tqdm(enumerate(props), total=nb_labels):\n centers[i] = region.centroid\n volumes[i] = region.area\n eq_diams[i] = region.equivalent_diameter\n minor_lengths[i] = region.minor_axis_length\n major_lengths[i] = region.major_axis_length\n axis_ratios = major_lengths / np.clip(minor_lengths, 1, None)\n return centers, volumes, eq_diams, minor_lengths, major_lengths, axis_ratios\n\n\n# Define command-line main functions\n\n\ndef detect_main(args):\n if args.voxel_size is not None and args.output_um is None:\n raise ValueError(\n \"A path to output_um array must be specified if given voxel dimensions\"\n )\n elif args.voxel_size is None and args.output_um is not None:\n raise ValueError(\"Voxel size must be specified if path to output_um is given\")\n\n if args.n < 0:\n nb_workers = multiprocessing.cpu_count()\n else:\n nb_workers = int(args.n)\n\n # Open nuclei Zarr array\n verbose_print(args, f\"Detecting nuclei in {args.input}\")\n arr = io.open(args.input, mode=\"r\")\n shape, dtype, chunks = arr.shape, arr.dtype, arr.chunks\n verbose_print(args, f\"Opened image: {shape} {dtype}\")\n\n # Create probability Zarr array\n prob_arr = io.new_zarr(\n args.probability, shape=shape, chunks=chunks, dtype=\"float32\"\n )\n\n # Detect nuclei\n centroids = detection.detect_nuclei_parallel(\n arr,\n sigma=args.g,\n min_intensity=args.m,\n steepness=args.s,\n offset=args.b,\n I0=args.r,\n stdev=args.x,\n prob_thresh=args.p,\n min_dist=args.d,\n chunks=tuple(args.c),\n overlap=args.o,\n nb_workers=nb_workers, # GPU requires one worker\n prob_output=prob_arr,\n )\n nb_centroids = centroids.shape[0]\n verbose_print(args, f\"Found {nb_centroids} nuclei centroids\")\n\n # Convert to micron if possible\n if args.voxel_size is not None:\n voxel_size = utils.read_voxel_size(args.voxel_size)\n centroids_um = centroids * np.asarray(voxel_size)\n\n # Save centroids\n np.save(args.output, centroids)\n verbose_print(args, f\"Saved centroids to {args.output}\")\n if args.output_um is not None:\n np.save(args.output_um, centroids_um)\n verbose_print(args, f\"Saved centroids in micron to {args.output_um}\")\n\n verbose_print(args, f\"Nuclei detection done!\")\n\n\ndef detect_cli(subparsers):\n detect_parser = subparsers.add_parser(\n \"detect\",\n help=\"Detect all nuclei centroids in image\",\n description=\"Detects nuclei centroids using a curvature-based filter\",\n )\n detect_parser.add_argument(\"input\", help=\"Path to nuclei image Zarr array\")\n detect_parser.add_argument(\n \"probability\", help=\"Path to nuclei probability map Zarr array\"\n )\n detect_parser.add_argument(\n \"output\", help=\"Path to save numpy array of nuclei centroids\"\n )\n detect_parser.add_argument(\n \"--voxel-size\", help=\"Path to voxel size CSV\", default=None\n )\n detect_parser.add_argument(\n \"--output-um\",\n help=\"Path to save numpy array of centroids in micron\",\n default=None,\n )\n detect_parser.add_argument(\n \"-g\",\n help=\"Amount of gaussian blur\",\n type=float,\n nargs=\"+\",\n default=(1.0, 3.0, 3.0),\n )\n detect_parser.add_argument(\n \"-s\", help=\"Steepness of curvature filter\", type=float, default=600\n )\n detect_parser.add_argument(\n \"-b\", help=\"Bias of curvature filter\", type=float, default=-0.0005\n )\n detect_parser.add_argument(\n \"-r\", help=\"Reference intensity prior\", type=float, default=1.0\n )\n detect_parser.add_argument(\n \"-x\", help=\"Crossover intensity prior\", type=float, default=0.10\n )\n detect_parser.add_argument(\n \"-d\", help=\"Minimum distance between centroids\", type=float, default=3\n )\n detect_parser.add_argument(\n \"-p\", help=\"Minimum probability of a centroid\", type=float, default=0.2\n )\n detect_parser.add_argument(\n \"-c\",\n help=\"Chunk shape to process at a time\",\n type=int,\n nargs=\"+\",\n default=3 * (64,),\n )\n detect_parser.add_argument(\n \"-m\", help=\"Minimum intensity to skip chunk\", type=float, default=0.1\n )\n detect_parser.add_argument(\n \"-o\", help=\"Overlap in pixels between chunks\", type=int, default=8\n )\n detect_parser.add_argument(\n \"-n\",\n help=\"Number of parallel CPU processes (Must be 1 for GPU).\",\n type=int,\n default=1,\n )\n detect_parser.add_argument(\n \"-v\", \"--verbose\", help=\"Verbose flag\", action=\"store_true\"\n )\n\n\ndef segment_main(args):\n if args.n is None:\n nb_workers = multiprocessing.cpu_count()\n else:\n nb_workers = args.n\n\n # Open probability map Zarr array\n verbose_print(args, f\"Segmenting nuclei in {args.input}\")\n prob_arr = io.open(args.input, mode=\"r\")\n shape, dtype, chunks = prob_arr.shape, prob_arr.dtype, prob_arr.chunks\n verbose_print(args, f\"Opened image: {shape} {dtype}\")\n if dtype != \"float32\":\n warnings.warn(\n \"Input dtype is not float32... may not have passed a probability map\"\n )\n\n # Load nuclei centroids\n centroids = np.load(args.centroids)\n\n # Create foreground mask by thresholding the probability map\n verbose_print(\n args,\n f\"Thresholding probability at {args.t}, writing foreground to {args.foreground}\",\n )\n foreground_arr = io.new_zarr(\n args.foreground, shape=shape, chunks=chunks, dtype=\"uint8\"\n )\n f = partial(_threshold_chunk, threshold=args.t, output=foreground_arr)\n utils.pmap_chunks(f, prob_arr, chunks, 1, use_imap=True)\n\n # Add watershed lines to the foreground mask to break up touching nuclei\n verbose_print(\n args, f\"Performing watershed, writing binary segmentation to {args.output}\"\n )\n binary_seg = io.new_zarr(args.output, shape, chunks, \"uint8\")\n watershed_centers_parallel(\n prob_arr,\n centers=centroids,\n mask=foreground_arr,\n output=binary_seg,\n chunks=chunks,\n overlap=args.o,\n nb_workers=nb_workers,\n )\n\n verbose_print(args, \"Nuclei segmentation done!\")\n\n\ndef segment_cli(subparsers):\n segment_parser = subparsers.add_parser(\n \"segment\",\n help=\"Segment all nuclei from probability map\",\n description=\"Segments all nuclei to binary using 3D watershed\",\n )\n segment_parser.add_argument(\n \"input\", help=\"Path to nuclei probability map Zarr array\"\n )\n segment_parser.add_argument(\n \"centroids\", help=\"Path to nuclei centroids numpy array\"\n )\n segment_parser.add_argument(\n \"foreground\", help=\"Path to nuclei foreground Zarr array\"\n )\n segment_parser.add_argument(\n \"output\", help=\"Path to nuclei binary segmentation Zarr array\"\n )\n segment_parser.add_argument(\n \"-t\", help=\"Probability threshold for segmentation\", type=float, default=0.1\n )\n segment_parser.add_argument(\n \"-n\", help=\"Number of workers for segmentation\", type=int, default=None\n )\n segment_parser.add_argument(\n \"-o\", help=\"Overlap in pixels between chunks\", type=int, default=8\n )\n segment_parser.add_argument(\n \"-v\", \"--verbose\", help=\"Verbose flag\", action=\"store_true\"\n )\n\n\ndef fluorescence_main(args):\n if isinstance(args.inputs, list):\n inputs = args.inputs\n else:\n inputs = [args.inputs]\n\n nb_images = len(inputs)\n verbose_print(args, f\"Passed {nb_images} images to measure fluorescence\")\n\n # Load centroids\n centroids = np.load(args.centroids)\n\n # Initialize output arrays\n mfis = np.zeros((centroids.shape[0], nb_images))\n stdevs = np.zeros((centroids.shape[0], nb_images))\n for i, path in enumerate(inputs):\n # Open image\n arr = io.open(path, mode=\"r\")\n shape, dtype, chunks = arr.shape, arr.dtype, arr.chunks\n verbose_print(args, f\"Sampling from {path}: {shape} {dtype}\")\n\n # Sample image\n if args.g is not None:\n # Perform smoothing in a temporary array\n verbose_print(args, f\"Smoothing {path} with sigma {tuple(args.g)}\")\n with tempfile.TemporaryDirectory(prefix=os.path.abspath(\".\")) as temp_path:\n smoothed_arr = io.new_zarr(temp_path, shape, chunks, dtype)\n gaussian_blur_parallel(\n arr, args.g, smoothed_arr, arr.chunks, args.o, args.w\n ) # Too many workers gives Zarr race condition\n verbose_print(args, f\"Sampling fluorescence from smoothed {path}\")\n intensities = nuclei_centered_intensities(\n smoothed_arr, centroids, args.r, mode=args.m, nb_workers=args.w\n )\n # Temporary array deleted when context ends\n else:\n intensities = nuclei_centered_intensities(\n arr, centroids, args.r, mode=args.m, nb_workers=args.w\n )\n\n # Compute statistics\n mfis[:, i] = calculate_mfi(intensities)\n stdevs[:, i] = calculate_stdev(intensities)\n\n # Make output folder\n os.makedirs(args.output, exist_ok=True)\n\n # Save numpy array of MFIs and stdevs\n mfi_path = os.path.join(args.output, \"nuclei_mfis.npy\")\n np.save(mfi_path, mfis)\n verbose_print(args, f\"MFIs written to {mfi_path}\")\n\n stdev_path = os.path.join(args.output, \"nuclei_stdevs.npy\")\n np.save(stdev_path, stdevs)\n verbose_print(args, f\"StDevs written to {stdev_path}\")\n\n # Save CSV containing morphologies for each detected centroid\n # sox2.zarr/ <-- forward slash makes os.path.basename eval to empty string\n # Can use os.path.dirname(path) to get sox2.zarr, then use basename on that\n basenames = [\n os.path.basename(os.path.dirname(path)).split(\".\")[0] for path in inputs\n ]\n csv_names = [\"fluorescence_\" + str(base) + \".csv\" for base in basenames]\n csv_paths = [os.path.join(args.output, name) for name in csv_names]\n for i, (base, path) in enumerate(zip(basenames, csv_paths)):\n df = pd.DataFrame({\"mfi\": mfis[:, i], \"stdev\": stdevs[:, i]})\n df.to_csv(path)\n verbose_print(args, f\"Fluorescence statistics for {base} written to {path}\")\n\n verbose_print(args, f\"Fluorescence measurements done!\")\n\n\ndef fluorescence_cli(subparsers):\n fluorescence_parser = subparsers.add_parser(\n \"fluorescence\",\n help=\"Measure fluorescence for each cell\",\n description=\"Measures fluorescence statistics at each centroid\",\n )\n fluorescence_parser.add_argument(\n \"centroids\", help=\"Path to nuclei centroids numpy array\"\n )\n fluorescence_parser.add_argument(\n \"output\", help=\"Path to output folder to save fluorescence CSVs\"\n )\n fluorescence_parser.add_argument(\n \"inputs\", help=\"Path to input images to sample from\", nargs=\"+\"\n )\n fluorescence_parser.add_argument(\n \"-g\", help=\"Amount of gaussian blur\", type=float, nargs=\"+\", default=None\n )\n fluorescence_parser.add_argument(\n \"-m\", help=\"Sampling mode {'cube'}\", type=str, default=\"cube\"\n )\n fluorescence_parser.add_argument(\"-r\", help=\"Sampling radius\", type=int, default=1)\n fluorescence_parser.add_argument(\n \"-w\", help=\"Number of workers\", type=int, default=None\n )\n fluorescence_parser.add_argument(\n \"-o\", help=\"Overlap in pixels between chunks for smoothing\", type=int, default=8\n )\n fluorescence_parser.add_argument(\n \"-v\", \"--verbose\", help=\"Verbose flag\", action=\"store_true\"\n )\n\n\n# scout niche radial tests/data/centroids_um.npy tests/data/gate_lp=\"Verbose flag\", action='store_true')\n\n\ndef gate_main(args):\n verbose_print(args, f\"Gating cells based on fluorescence in {args.input}\")\n\n # Load MFIs and check for mismatch\n mfis = np.load(args.input)\n if mfis.shape[-1] != len(args.thresholds):\n raise ValueError(\n \"Number of thresholds must match the number of channels in MFI array\"\n )\n\n # Show plot\n if args.plot:\n verbose_print(args, f\"Showing cytometry plot...\")\n\n mfi_x, mfi_y = mfis[:, args.x], mfis[:, args.y]\n\n if args.r is None:\n x_max = mfi_x.max()\n y_max = mfi_y.max()\n else:\n x_max = args.r[0]\n y_max = args.r[1]\n\n plt.hist2d(\n mfi_x,\n mfi_y,\n bins=args.b,\n norm=colors.PowerNorm(0.25),\n range=((0, x_max), (0, y_max)),\n )\n plt.plot([args.thresholds[0], args.thresholds[0]], [0, y_max], \"r-\")\n plt.plot([0, x_max], [args.thresholds[1], args.thresholds[1]], \"r-\")\n plt.xlim([0, x_max])\n plt.ylim([0, y_max])\n plt.xlabel(f\"MFI column {args.x}\")\n plt.ylabel(f\"MFI column {args.y}\")\n plt.show()\n\n # Gate each channel\n labels = np.asarray(\n [threshold_mfi(mfi, t) for mfi, t in zip(mfis.T, args.thresholds)],\n dtype=np.uint8,\n ).T\n # TODO: Add DN labels in here\n\n # Save the result\n np.save(args.output, labels)\n verbose_print(args, f\"Gating results written to {args.output}\")\n\n verbose_print(args, f\"Gating cells done!\")\n\n\ndef gate_cli(subparsers):\n gate_parser = subparsers.add_parser(\n \"gate\",\n help=\"Gate cells based on fluorescence\",\n description=\"Gates cells and classify cell-types based on fluorescence\",\n )\n gate_parser.add_argument(\"input\", help=\"Path to input MFI numpy array\")\n gate_parser.add_argument(\"output\", help=\"Path to output labels numpy array\")\n gate_parser.add_argument(\n \"thresholds\", help=\"MFI gates for each channel\", nargs=\"+\", type=float\n )\n gate_parser.add_argument(\n \"-p\", \"--plot\", help=\"Flag to show plot\", action=\"store_true\"\n )\n gate_parser.add_argument(\n \"-b\", help=\"Number of bins to use in historgram\", type=int, default=128\n )\n gate_parser.add_argument(\n \"-r\", help=\"Ranges for each axis\", nargs=\"+\", type=float, default=None\n )\n gate_parser.add_argument(\n \"-x\", help=\"MFI column index for x-axis\", type=int, default=0\n )\n gate_parser.add_argument(\n \"-y\", help=\"MFI column index for y-axis\", type=int, default=1\n )\n gate_parser.add_argument(\n \"-v\", \"--verbose\", help=\"Verbose flag\", action=\"store_true\"\n )\n\n\ndef morphology_main(args):\n if args.n is None:\n nb_workers = multiprocessing.cpu_count()\n else:\n nb_workers = args.n\n\n if args.segmentations is not None:\n return_seg = True\n else:\n return_seg = False\n\n verbose_print(args, f\"Computing morphological features for {args.input}\")\n\n # Get window size\n window_size = np.asarray(args.w)\n verbose_print(args, f\"Using window size of {window_size} around each cell\")\n\n # Load the detected centroids and open binary segmentation\n centroids = np.load(args.centroids) # TODO: Make this consider voxel dimensions\n binary_seg = io.open(args.input, mode=\"r\")\n\n # Compute labeled segmentation and morphologies for each cell\n if return_seg:\n verbose_print(\n args, f\"Computing segmentations and morphologies with {nb_workers} workers\"\n )\n else:\n verbose_print(args, f\"Computing morphologies with {nb_workers} workers\")\n args_list = [\n (centroid, window_size, binary_seg, return_seg) for centroid in centroids\n ]\n with multiprocessing.Pool(nb_workers) as pool:\n results = list(\n tqdm(pool.imap(_segment_centroid, args_list), total=len(args_list))\n )\n # Unpack morphological features\n # features = np.array([center, volume, eq_diam, minor_length, major_length, axis_ratio])\n features = np.asarray([r[0] for r in results]) # N x feats\n centers_z = features[:, 0]\n centers_y = features[:, 1]\n centers_x = features[:, 2]\n volumes = features[:, 3]\n eq_diams = features[:, 4]\n minor_lengths = features[:, 5]\n major_lengths = features[:, 6]\n axis_ratios = features[:, 7]\n\n # Save each segmentation\n if return_seg:\n verbose_print(args, f\"Saving single-cell segmentations to {args.segmentations}\")\n singles = np.asarray([r[1] for r in results])\n np.savez_compressed(args.segmentations, singles)\n\n # Save CSV containing morphologies for each detected centroid\n data = {\n \"com_z\": centers_z,\n \"com_y\": centers_y,\n \"com_x\": centers_x,\n \"volume\": volumes,\n \"eq_diam\": eq_diams,\n \"minor_length\": minor_lengths,\n \"major_length\": major_lengths,\n \"axis_ratio\": axis_ratios,\n }\n df = pd.DataFrame(data)\n df.to_csv(args.output)\n verbose_print(args, f\"Morphological features written to {args.output}\")\n\n verbose_print(args, f\"Computing morphologies done!\")\n\n\ndef morphology_cli(subparsers):\n morphology_parser = subparsers.add_parser(\n \"morphology\",\n help=\"Measure morphological features of nuclei\",\n description=\"Compute morphological features from nuclei segmentation\",\n )\n morphology_parser.add_argument(\n \"input\", help=\"Path to input nuclei binary segmentation Zarr\"\n )\n morphology_parser.add_argument(\n \"centroids\", help=\"Path to nuclei centroids numpy array\"\n )\n morphology_parser.add_argument(\n \"output\", help=\"Path to output morphological features CSV\"\n )\n morphology_parser.add_argument(\n \"--segmentations\",\n help=\"Path to output nuclei segmentations numpy array\",\n default=None,\n )\n morphology_parser.add_argument(\n \"-w\", help=\"Window size\", type=int, nargs=\"+\", default=(8, 25, 25)\n )\n morphology_parser.add_argument(\n \"-n\", help=\"Number of workers for segmentation\", type=int, default=None\n )\n morphology_parser.add_argument(\n \"-v\", \"--verbose\", help=\"Verbose flag\", action=\"store_true\"\n )\n\n\ndef nuclei_cli(subparsers):\n nuclei_parser = subparsers.add_parser(\n \"nuclei\",\n help=\"nuclei detection and segmentation\",\n description=\"Nuclei detection and segmentation tool\",\n )\n nuclei_subparsers = nuclei_parser.add_subparsers(\n dest=\"nuclei_command\", title=\"nuclei subcommands\"\n )\n detect_cli(nuclei_subparsers)\n segment_cli(nuclei_subparsers)\n fluorescence_cli(nuclei_subparsers)\n gate_cli(nuclei_subparsers)\n morphology_cli(nuclei_subparsers)\n name_cli(nuclei_subparsers)\n return nuclei_parser\n\n\ndef nuclei_main(args):\n commands_dict = {\n \"detect\": detect_main,\n \"segment\": segment_main,\n \"fluorescence\": fluorescence_main,\n \"gate\": gate_main,\n \"morphology\": morphology_main,\n \"name\": name_main,\n }\n func = commands_dict.get(args.nuclei_command, None)\n if func is None:\n print(\"Pickle Rick uses nuclei subcommands... be like Pickle Rick\\n\")\n subprocess.call([\"scout\", \"nuclei\", \"-h\"])\n else:\n func(args)\n\n\n# scout nuclei morphology nuclei_binary_segmentation.zarr/ centroids.npy nuclei_segmentations.npz nuclei_morphologies.csv -v\n" ]
[ [ "matplotlib.pyplot.xlim", "numpy.load", "numpy.where", "pandas.DataFrame", "numpy.save", "numpy.savez_compressed", "matplotlib.colors.PowerNorm", "matplotlib.use", "numpy.array", "numpy.pad", "numpy.zeros", "numpy.clip", "matplotlib.pyplot.show", "numpy.asarray", "scipy.ndimage.label", "matplotlib.pyplot.ylim", "matplotlib.pyplot.plot", "matplotlib.pyplot.xlabel", "numpy.any", "matplotlib.pyplot.ylabel" ] ]
robertsawko/proteus
[ "6f1e4c2ca1af85a906b35a5162430006f0343861" ]
[ "proteus/tests/POD/deim_utils.py" ]
[ "#!/usr/bin/env python\n\"\"\"\nutility module for generating deim interpolants\n\"\"\"\nimport numpy as np\n\ndef read_from_hdf5(hdfFile,label,dof_map=None):\n \"\"\"\n Just grab the array stored in the node with label label and return it\n If dof_map is not none, use this to map values in the array\n If dof_map is not none, this determines shape of the output array\n \"\"\"\n assert hdfFile != None, \"requires hdf5 for heavy data\"\n vals = hdfFile.getNode(label).read()\n if dof_map is not None:\n dof = vals[dof_map]\n else:\n dof = vals\n\n return dof\n\ndef read_snapshots(archive,nsnap,val_name):\n \"\"\"\n assumes nsnap values of array in val_name are stored in h5file as\n /val_name'i' for i=0,nspap-1\n\n loads these into a matrix and returns\n \"\"\"\n label_base=\"/%s%d\"\n u = read_from_hdf5(archive.hdfFile,label_base % (val_name,0))\n S = np.reshape(u,(u.shape[0],1))\n for i in range(1,nsnap):\n label=label_base % (val_name,i)\n u = read_from_hdf5(archive.hdfFile,label)\n u = np.reshape(u,(u.shape[0],1))\n S = np.append(S,u,axis=1)\n #\n return S\n\n\ndef generate_svd_decomposition(archive,nsnap,val_name,outbase):\n \"\"\"\n assumes nsnap values of array in val_name are stored in h5file as\n /val_name'i' for i=0,nspap-1\n\n loads these into a matrix, performs an SVD, and stores the output in outbase_SVD_basis, \n outbase_singular_values in numpy's binary format\n\n returns U,s,V svd decomposition of snapshots\n \"\"\"\n S = read_snapshots(archive,nsnap,val_name)\n\n U, s, V= np.linalg.svd(S,full_matrices=False)\n \n np.savetxt(outbase+'_SVD_basis',U,delimiter=' ')\n np.savetxt(outbase+'_SVD_singular_values',s,delimiter=' ')\n\n return U,s,V\n\ndef calculate_deim_indices(Uin):\n \"\"\"\n input: Uin n x m array of basis vectors for nonlinear function snapshots\n output: rho, m vector of indices \\rho_i for extracting $\\vec F$ values\n\n \"\"\"\n n,m=Uin.shape\n rind = np.argmax(np.absolute(Uin[:,0]))\n U=np.array(Uin[:,0])\n rho=np.array([rind],'i')\n #Pt = np.zeros((1,n),'d')\n #P[0,rind]=1.0\n for j in range(1,m):\n u = Uin[:,j] \n Up=U[rho]#Up= np.dot(Pt,U)\n up=u[rho]#up= np.dot(Pt,u)\n if j==1:\n c=up/Up\n r=u-U*c\n else:\n c =np.linalg.solve(Up,up)\n r=u-np.dot(U,c) \n rind=np.argmax(np.absolute(r))\n rho_new = np.zeros(j+1,'i'); \n rho_new[:-1]=rho; rho_new[-1]=rind; rho = rho_new\n U_new=np.zeros((n,j+1),'d')\n U_new[:,:-1]=U.reshape(n,j); U_new[:,-1]=u\n U=U_new\n #\n return rho\n\ndef deim_alg(Uin,m):\n \"\"\"\n Basic procedure\n\n - given $m$, dimension for $F$ reduced basis $\\mathbf{U}_m$\n - call DEIM algorithm to determine $\\vec \\rho$. \n - build $\\mathbf{P}$ from $\\rho$ as \n $$\n \\mathbf{P} = [\\vec e_{\\rho_1},\\vec e_{\\rho_2},\\dots,\\vec e_{\\rho_m}]\n $$\n - invert $\\mathbf{P}^T\\mathbf{U}_m$\n - return \\rho and $\\mathbf{P}_F=\\mathbf{U}_m(\\mathbf{P}^T\\mathbf{U}_m)^{-1}$\n\n \n \"\"\"\n assert m <= Uin.shape[1]\n Um = Uin[:,0:m]\n rho = calculate_deim_indices(Um)\n PtUm = Um[rho]\n assert PtUm.shape == (m,m)\n PtUmInv = np.linalg.inv(PtUm)\n PF= np.dot(Um,PtUmInv)\n return rho,PF\n\ndef visualize_zslice(variable,nnx,nny,iz,x=None,y=None,name=None):\n \"\"\"\n convenience function for plotting a slice\n \"\"\"\n istart = nnx*nny*iz\n iend = nnx*nny*(iz+1)\n v_slice= variable[istart:iend]\n v_slice= v_slice.reshape(nnx,nny)\n if x == None:\n x = np.outer(np.arange(nnx),np.arange(nnx))\n if y == None:\n y = np.outer(np.arange(nny),np.arange(nny))\n assert x.shape == v_slice.shape\n assert y.shape == v_slice.shape\n\n import matplotlib.pyplot as plt\n from mpl_toolkits.mplot3d import Axes3D\n from matplotlib import cm\n from matplotlib.ticker import LinearLocator, FormatStrFormatter\n fig = plt.figure()\n ax = fig.gca(projection='3d')\n surf=ax.plot_surface(x,y,v_slice,rstride=1,cstride=1,cmap=cm.coolwarm,linewidth=0,antialiased=False)\n plt.xlabel('x'); plt.ylabel('y')\n if name == None:\n name = 'deim_slice_z={0}.png'.format(iz)\n plt.savefig(name)\n\n\n return surf\n\ndef extract_sub_matrix_csr(rho,rowptr,colind,nnzval):\n \"\"\"\n manually extract the rows in the deim index vector rho from a csr matrix representation \n returns a csr representation \n \"\"\"\n m = len(rho)\n rowptr_sub = np.zeros(m+1,'i')\n nnz_sub = 0\n for k,I in enumerate(rho):#count number of nonzero entries\n diff = rowptr[I+1]-rowptr[I]\n rowptr_sub[k+1]=rowptr_sub[k]+diff\n nnz_sub += diff\n colind_sub = np.zeros(nnz_sub,'i'); nzval_sub=np.zeros(nnz_sub,'d')\n for k,KK in enumerate(rho):\n for m,MM in enumerate(range(rowptr[KK],rowptr[KK+1])):\n colind_sub[rowptr_sub[k]+m]=colind[MM]\n nzval_sub[rowptr_sub[k]+m]=nnzval[MM]\n #\n return rowptr_sub,colind_sub,nzval_sub\n" ]
[ [ "numpy.append", "numpy.array", "numpy.dot", "numpy.savetxt", "numpy.reshape", "numpy.zeros", "numpy.absolute", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.savefig", "matplotlib.pyplot.figure", "numpy.arange", "numpy.linalg.svd", "matplotlib.pyplot.ylabel", "numpy.linalg.solve", "numpy.linalg.inv" ] ]
zealoussnow/chromium
[ "fd8a8914ca0183f0add65ae55f04e287543c7d4a", "fd8a8914ca0183f0add65ae55f04e287543c7d4a", "fd8a8914ca0183f0add65ae55f04e287543c7d4a" ]
[ "third_party/tensorflow-text/src/tensorflow_text/python/ops/item_selector_ops.py", "third_party/tensorflow-text/src/tensorflow_text/python/ops/masking_ops.py", "third_party/tensorflow-text/src/tensorflow_text/python/keras/layers/todense_test.py" ]
[ "# coding=utf-8\n# Copyright 2021 TF.Text Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Ops for selecting items in RaggedTensors.\"\"\"\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import gen_array_ops\nfrom tensorflow.python.ops import map_fn\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import random_ops\nfrom tensorflow.python.ops.ragged import ragged_array_ops\nfrom tensorflow.python.ops.ragged import ragged_functional_ops\nfrom tensorflow.python.ops.ragged import ragged_math_ops\nfrom tensorflow.python.ops.ragged import ragged_tensor\n\n\nclass ItemSelector(object):\n \"\"\"A class encapsulating the logic for selecting items.\n\n `ItemSelector` implementations contain algorithms for selecting items in a\n `RaggedTensor`. Users of `ItemSelector` implementations can call\n `get_selection_mask()` to retrieve a bool `RaggedTensor` mask indicating the\n items that have been selected. For example:\n\n ```\n inputs = tf.ragged.constant([\n [1, 2, 3, 4],\n [100, 200]\n ])\n\n selector = RandomItemSelector(...)\n\n selected = selector.get_selection_mask(inputs)\n\n # selected = [\n # [True, False, False, True],\n # [True, True],\n # ]\n ```\n\n For subclass writers that wish to implement their own custom, selection\n algorithm, please override `get_selection_mask()`.\n\n A helper function `get_selectable()` is provided to help subclass writers\n filter out undesirable items from selection. The default implementation will\n filter out items listed in `unselectable_ids`. Subclass writers may also\n override `get_selectable()` if they wish to customize the items to filter out\n from the selection algorithm.\n \"\"\"\n\n def __init__(self, unselectable_ids=None):\n \"\"\"Creates an instance of a `ItemSelector`.\n\n Args:\n unselectable_ids: a list, or `Tensor` of ids that are not selectable.\n \"\"\"\n if unselectable_ids is None:\n unselectable_ids = []\n if isinstance(unselectable_ids, list):\n self._unselectable_ids = unselectable_ids\n elif isinstance(unselectable_ids, ops.Tensor):\n if unselectable_ids.shape.rank not in (1, None):\n raise ValueError(f\"`unselectable_ids` must have a rank of 1 or None, \"\n f\"but was: {unselectable_ids.shape.rank}\")\n self._unselectable_ids = array_ops.unstack(unselectable_ids)\n else:\n raise ValueError(\"`unselectable_ids` must be either a list or \" +\n \"`1 dimensional Tensor`, instead it is a \" +\n str(unselectable_ids))\n\n @property\n def unselectable_ids(self):\n return self._unselectable_ids\n\n def get_selectable(self, input_ids, axis):\n \"\"\"Return a boolean mask of items that can be chosen for selection.\n\n Args:\n input_ids: a `RaggedTensor`.\n axis: axis to apply selection on.\n\n Returns:\n a `RaggedTensor` with dtype of bool and with shape\n `input_ids.shape[:axis]`. Its values are True if the\n corresponding item (or broadcasted subitems) should be considered for\n masking. In the default implementation, all `input_ids` items that are not\n listed in `unselectable_ids` (from the class arg) are considered\n selectable.\n \"\"\"\n # merge to the desired axis\n input_ids = input_ids.merge_dims(1, axis) if axis > 1 else input_ids\n\n all_selectable_flats = [\n ragged_functional_ops.map_flat_values(math_ops.not_equal, input_ids,\n i).flat_values\n for i in self._unselectable_ids\n ]\n\n # if there are no blacklisted ids, mark everything as selectable\n if all_selectable_flats:\n reduce_flat = math_ops.reduce_all(all_selectable_flats, axis=0)\n else:\n reduce_flat = array_ops.ones_like(\n input_ids.flat_values, dtype=dtypes.bool)\n\n # reduce to the requested axis and broadcast to match original shape\n axis = array_ops.get_positive_axis(\n axis, input_ids.ragged_rank + input_ids.flat_values.shape.rank)\n results = input_ids.with_flat_values(reduce_flat)\n if axis < input_ids.ragged_rank:\n reduce_axis = list(range(input_ids.ragged_rank, axis, -1))\n results = math_ops.reduce_all(results, reduce_axis)\n\n return results\n\n def get_selection_mask(self, input_ids, axis=1):\n \"\"\"Returns a mask of items that have been selected.\n\n The default implementation returns all selectable items as selectable.\n\n Args:\n input_ids: A `RaggedTensor`.\n axis: (optional) An int detailing the dimension to apply selection on.\n Default is the 1st dimension.\n\n Returns:\n a `RaggedTensor` with shape `input_ids.shape[:axis]`. Its values are True\n if the corresponding item (or broadcasted subitems) should be selected.\n \"\"\"\n return self.get_selectable(input_ids, axis)\n\n\nclass RandomItemSelector(ItemSelector):\n \"\"\"An `ItemSelector` implementation that randomly selects items in a batch.\n\n `RandomItemSelector` randomly selects items in a batch subject to\n restrictions given (max_selections_per_batch, selection_rate and\n unselectable_ids).\n \"\"\"\n\n def __init__(self,\n max_selections_per_batch,\n selection_rate,\n unselectable_ids=None,\n shuffle_fn=None):\n \"\"\"Creates instance of `RandomItemSelector`.\n\n Args:\n max_selections_per_batch: An int of the max number of items to mask out.\n selection_rate: The rate at which items are randomly selected.\n unselectable_ids: (optional) A list of python ints or 1D `Tensor` of ints\n which are ids that will be not be masked.\n shuffle_fn: (optional) A function that shuffles a 1D `Tensor`. Default\n uses `tf.random.shuffle`.\n \"\"\"\n if selection_rate is None:\n raise ValueError(\"`selection_rate` cannot be None\")\n if shuffle_fn is None:\n self._shuffle_fn = random_ops.random_shuffle\n else:\n self._shuffle_fn = shuffle_fn\n\n self._max_selections_per_batch = max_selections_per_batch\n self._selection_rate = selection_rate\n super(RandomItemSelector, self).__init__(unselectable_ids)\n\n @property\n def shuffle_fn(self):\n return self._shuffle_fn\n\n @property\n def max_selections_per_batch(self):\n return self._max_selections_per_batch\n\n @property\n def selection_rate(self):\n return self._selection_rate\n\n def get_selection_mask(self, input_ids, axis):\n selectable = super(RandomItemSelector, self).get_selectable(\n input_ids, axis)\n\n # Run the selection algorithm on positions RT\n positions_flat = math_ops.range(array_ops.size(input_ids.flat_values))\n positions = input_ids.with_flat_values(positions_flat)\n # Mask out positions that are not selectable\n positions = ragged_array_ops.boolean_mask(positions, selectable)\n\n # merge to the desired axis\n positions = positions.merge_dims(1, axis) if axis > 1 else positions\n\n # Figure out how many we are going to select\n num_to_select = math_ops.ceil(\n math_ops.cast(positions.row_lengths(), dtypes.float32) *\n self.selection_rate)\n num_to_select = math_ops.minimum(num_to_select,\n self.max_selections_per_batch)\n num_to_select = math_ops.cast(num_to_select, dtypes.int64)\n\n # Shuffle and trim to items that are going to be selected\n def _shuffle_and_trim(x):\n positions, top_n = x\n if isinstance(positions, ragged_tensor.RaggedTensor):\n positions_at_axis = math_ops.range(positions.nrows())\n chosen_positions_at_axis = self._shuffle_fn(positions_at_axis)[:top_n]\n return array_ops.gather(positions, chosen_positions_at_axis)\n else:\n shuffled = self._shuffle_fn(positions)\n return shuffled[:top_n]\n\n selected_for_mask = map_fn.map_fn(\n _shuffle_and_trim, (positions, num_to_select),\n fn_output_signature=ragged_tensor.RaggedTensorSpec(\n ragged_rank=positions.ragged_rank - 1, dtype=positions.dtype))\n selected_for_mask.flat_values.set_shape([None])\n\n # Construct the result which is a boolean RT\n # Scatter 1's to positions that have been selected_for_mask\n update_values = array_ops.ones_like(selected_for_mask.flat_values)\n update_values = math_ops.cast(update_values, input_ids.dtype)\n update_indices = selected_for_mask.flat_values\n update_indices = array_ops.expand_dims(update_indices, -1)\n update_indices = math_ops.cast(update_indices, input_ids.dtype)\n\n results_flat = array_ops.zeros_like(input_ids.flat_values)\n results_flat = gen_array_ops.tensor_scatter_update(\n results_flat, update_indices, update_values)\n results = math_ops.cast(\n input_ids.with_flat_values(results_flat), dtypes.bool)\n\n if axis < results.ragged_rank:\n reduce_axis = list(range(results.ragged_rank, axis, -1))\n results = math_ops.reduce_all(results, reduce_axis)\n return results\n\n\ndef _get_row_lengths_merged_to_axis(segments, axis=-1):\n \"\"\"Get the row lengths relative to a desired axis.\"\"\"\n axis = array_ops.get_positive_axis(axis, segments.shape.ndims) - 1\n row_lengths = ragged_tensor.RaggedTensor.from_nested_row_lengths(\n segments.nested_row_lengths()[axis],\n segments.nested_row_lengths()[:axis])\n for _ in range(axis):\n row_lengths = math_ops.reduce_sum(row_lengths, -1)\n return row_lengths\n\n\ndef _get_selection_mask(original, num_to_select, axis=-1):\n \"\"\"Get a selection mask given how many items to select.\"\"\"\n num_to_select = ops.convert_to_tensor(num_to_select)\n num_to_select = array_ops.reshape(num_to_select, [-1])\n row_lengths = _get_row_lengths_merged_to_axis(original, axis)\n num_to_select = array_ops.broadcast_to(num_to_select,\n array_ops.shape(row_lengths))\n num_to_select = math_ops.cast(num_to_select, row_lengths.dtype)\n num_to_select = math_ops.minimum(num_to_select, row_lengths)\n ones = array_ops.ones_like(ragged_math_ops.range(num_to_select))\n ones = math_ops.cast(ones, dtypes.int32)\n zeros_row_length = row_lengths - num_to_select\n zeros = math_ops.cast(\n array_ops.zeros_like(ragged_math_ops.range(zeros_row_length)),\n dtypes.int32)\n results = array_ops.concat([ones, zeros], 1)\n results = math_ops.cast(results, dtypes.bool)\n return results\n\n\nclass FirstNItemSelector(ItemSelector):\n \"\"\"An `ItemSelector` that selects the first `n` items in the batch.\"\"\"\n\n def __init__(self, num_to_select, unselectable_ids=None):\n \"\"\"Creates an instance of `FirstNItemSelector`.\n\n Args:\n num_to_select: An int which is the leading number of items to select.\n unselectable_ids: (optional) A list of int ids that cannot be selected.\n Default is empty list.\n \"\"\"\n super(FirstNItemSelector, self).__init__(unselectable_ids)\n self._num_to_select = num_to_select\n\n def get_selectable(self, input_ids, axis):\n \"\"\"See `get_selectable()` in superclass.\"\"\"\n selectable = super(FirstNItemSelector, self).get_selectable(input_ids, axis)\n axis = array_ops.get_positive_axis(\n axis, input_ids.ragged_rank + input_ids.flat_values.shape.rank)\n # Create a positions RT and mask out positions that are not selectable\n positions_flat = math_ops.range(array_ops.size(input_ids.flat_values))\n positions = input_ids.with_flat_values(positions_flat)\n selectable_positions = ragged_array_ops.boolean_mask(positions, selectable)\n\n # merge to the desired axis\n selectable_positions = selectable_positions.merge_dims(\n 1, axis) if axis > 1 else selectable_positions\n\n # Get a selection mask based off of how many items are desired for selection\n merged_axis = axis - (axis - 1)\n selection_mask = _get_selection_mask(selectable_positions,\n self._num_to_select, merged_axis)\n # Mask out positions that were not selected.\n selected_positions = ragged_array_ops.boolean_mask(selectable_positions,\n selection_mask)\n\n # Now that we have all the positions which were chosen, we recreate a mask\n # (matching the original input's shape) where the value is True if it was\n # selected. We do this by creating a \"all false\" RT and scattering true\n # values to the positions chosen for selection.\n all_true = selected_positions.with_flat_values(\n array_ops.ones_like(selected_positions.flat_values))\n all_false = math_ops.cast(\n array_ops.zeros(array_ops.shape(input_ids.flat_values)), dtypes.int32)\n results_flat = array_ops.tensor_scatter_update(\n all_false, array_ops.expand_dims(selected_positions.flat_values, -1),\n all_true.flat_values)\n results = input_ids.with_flat_values(results_flat)\n results = math_ops.cast(results, dtypes.bool)\n\n # Reduce until input.shape[:axis]\n for _ in range(input_ids.shape.ndims - axis - 1):\n results = math_ops.reduce_all(results, -1)\n return results\n\n\nclass NothingSelector(ItemSelector):\n \"\"\"An `ItemSelector` that selects nothing.\"\"\"\n\n def __init__(self):\n super(NothingSelector, self).__init__([])\n\n def get_selectable(self, tokens, axis):\n \"\"\"See `get_selectable()` in superclass.\"\"\"\n flat_false_values = math_ops.cast(\n array_ops.zeros_like(tokens.flat_values), dtypes.bool)\n results = tokens.with_flat_values(flat_false_values)\n for _ in range(tokens.ragged_rank - axis):\n results = math_ops.reduce_all(results, -1)\n return results\n", "# coding=utf-8\n# Copyright 2021 TF.Text Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Ops for applying language model masking dynamically to inputs.\"\"\"\n\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import control_flow_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import random_ops\nfrom tensorflow.python.ops.ragged import ragged_array_ops\nfrom tensorflow.python.ops.ragged import ragged_math_ops\nfrom tensorflow.python.ops.ragged import ragged_tensor\nfrom tensorflow.python.ops.ragged import ragged_where_op\nfrom tensorflow_text.python.ops import item_selector_ops\n\n\n# TODO(b/166323018): Replace once tensor_scatter_nd_update for RaggedTensor is\n# available.\ndef _ragged_tensor_scatter_nd_update(params, indices, updates):\n \"\"\"Version of tensor_scatter_nd_update() where the values are ragged.\"\"\"\n # Create a RT in the shape of `params` and containing the \"global\" positions.\n # Here \"global\" means the element position in the flat values Tensor.\n global_positions_flat = math_ops.range(array_ops.size(params.flat_values))\n global_positions = params.with_flat_values(global_positions_flat)\n\n global_indices = array_ops.batch_gather(global_positions, indices)\n update_indices = global_indices.flat_values\n update_indices = array_ops.expand_dims(update_indices, -1)\n update_indices = math_ops.cast(update_indices, params.dtype)\n params_flat = params.flat_values\n update_values = math_ops.cast(updates.flat_values, params_flat.dtype)\n results_flat = array_ops.tensor_scatter_update(\n params_flat, update_indices, update_values)\n return params.with_flat_values(results_flat)\n\n\ndef _get_random(positions):\n \"\"\"Get a random tensor like `positions`.\"\"\"\n flat_random = random_ops.random_uniform(\n array_ops.shape(positions.flat_values), 0, 1, dtype=dtypes.float32)\n return positions.with_flat_values(flat_random)\n\n\ndef _get_selected_item_positions(item_selector, input_ids, axis=1):\n \"\"\"Get the positions of the items that have been selected.\n\n Args:\n item_selector: an instance of `ItemSelector`.\n input_ids: a `RaggedTensor` with n dimensions, whose items will be\n selected on.\n axis: (optional) An int detailing the dimension to apply selection on.\n Default is the 1st dimension.\n\n Returns:\n A `RaggedTensor` of int64s, with rank 2, shape\n [batch, (num_selections)] and whose values are the positions of items\n that have been selected.\n \"\"\"\n original_input_ids = input_ids\n\n # select items for masking\n selected_for_mask = item_selector.get_selection_mask(input_ids, axis)\n\n # create a positions RT\n original_input_ids = (\n original_input_ids.merge_dims(1, -1)\n if original_input_ids.ragged_rank > 1 else original_input_ids)\n positions = ragged_math_ops.range(original_input_ids.row_lengths())\n positions = input_ids.with_flat_values(positions.flat_values)\n\n # drop out not-masked positions\n results = ragged_array_ops.boolean_mask(positions, selected_for_mask)\n results = results.merge_dims(1, -1) if results.ragged_rank > 1 else results\n return results\n\n\ndef mask_language_model(\n input_ids,\n item_selector,\n mask_values_chooser,\n axis=1):\n \"\"\"Applies dynamic language model masking.\n\n `mask_language_model` implements the `Masked LM and Masking Procedure`\n described in `BERT: Pre-training of Deep Bidirectional Transformers for\n Language Understanding` (https://arxiv.org/pdf/1810.04805.pdf).\n `mask_language_model` uses an `ItemSelector` to select the items for masking,\n and a `MaskValuesChooser` to assign the values to the selected items.\n The purpose of this is to bias the representation towards the actual\n observed item.\n\n Masking is performed on items in an axis. A decision is taken independently at\n random to mask with [MASK], mask with random tokens from the full vocab, or\n not mask at all. Note that the masking decision is broadcasted to the\n sub-dimensions.\n\n For example, in a RaggedTensor of shape `[batch, (wordpieces)]` and if axis=1,\n each wordpiece independently gets masked (or not).\n\n With the following input:\n\n ```\n [[b\"Sp\", b\"##onge\", b\"bob\", b\"Sq\", b\"##uare\", b\"##pants\" ],\n [b\"Bar\", b\"##ack\", b\"Ob\", b\"##ama\"],\n [b\"Mar\", b\"##vel\", b\"A\", b\"##ven\", b\"##gers\"]],\n ```\n\n `mask_language_model` could end up masking individual wordpieces:\n\n ```\n [[b\"[MASK]\", b\"##onge\", b\"bob\", b\"Sq\", b\"[MASK]\", b\"##pants\" ],\n [b\"Bar\", b\"##ack\", b\"[MASK]\", b\"##ama\"],\n [b\"[MASK]\", b\"##vel\", b\"A\", b\"##ven\", b\"##gers\"]]\n ```\n\n Or with random token inserted\n\n ```\n [[b\"[MASK]\", b\"##onge\", b\"bob\", b\"Sq\", b\"[MASK]\", b\"##pants\" ],\n [b\"Bar\", b\"##ack\", b\"Sq\", b\"##ama\"], # random token inserted for 'Ob'\n [b\"Bar\", b\"##vel\", b\"A\", b\"##ven\", b\"##gers\"]] # random token inserted for\n # 'Mar'\n ```\n\n In a RaggedTensor of shape `[batch, (words), (wordpieces)]`, whole words get\n masked (or not). If a word gets masked, all its tokens are independently\n either replaced by `[MASK]`, by random tokens, or no substitution occurs.\n Note that any arbitrary spans that can be constructed by a `RaggedTensor` can\n be masked in the same way.\n\n For example, if we have an `RaggedTensor` with shape\n `[batch, (token), (wordpieces)]`:\n\n ```\n [[[b\"Sp\", \"##onge\"], [b\"bob\"], [b\"Sq\", b\"##uare\", b\"##pants\"]],\n [[b\"Bar\", \"##ack\"], [b\"Ob\", b\"##ama\"]],\n [[b\"Mar\", \"##vel\"], [b\"A\", b\"##ven\", b\"##gers\"]]]\n ```\n\n `mask_language_model` could mask whole spans (items grouped together\n by the same 1st dimension):\n\n ```\n [[[b\"[MASK]\", \"[MASK]\"], [b\"bob\"], [b\"Sq\", b\"##uare\", b\"##pants\"]],\n [[b\"Bar\", \"##ack\"], [b\"[MASK]\", b\"[MASK]\"]],\n [[b\"[MASK]\", \"[MASK]\"], [b\"A\", b\"##ven\", b\"##gers\"]]]\n ```\n\n or insert randoms items in spans:\n\n ```\n [[[b\"Mar\", \"##ama\"], [b\"bob\"], [b\"Sq\", b\"##uare\", b\"##pants\"]],\n [[b\"Bar\", \"##ack\"], [b\"##onge\", b\"##gers\"]],\n [[b\"Ob\", \"Sp\"], [b\"A\", b\"##ven\", b\"##gers\"]]]\n ```\n\n Args:\n input_ids: A `RaggedTensor` of n dimensions (where n >= 2) on which\n masking will be applied to items up to dimension 1.\n item_selector: An instance of `ItemSelector` that is used for selecting\n items to be masked.\n mask_values_chooser: An instance of `MaskValuesChooser` which determines the\n values assigned to the ids chosen for masking.\n axis: the axis where items will be treated atomically for masking.\n Returns:\n A tuple of (masked_input_ids, masked_positions, masked_ids) where:\n\n masked_input_ids: A `RaggedTensor` in the same shape and dtype as\n `input_ids`, but with items in `masked_positions` possibly replaced\n with `mask_token`, random id, or no change.\n masked_positions: A `RaggedTensor` of ints with shape\n [batch, (num_masked)] containing the positions of items selected for\n masking.\n masked_ids: A `RaggedTensor` with shape [batch, (num_masked)] and same\n type as `input_ids` containing the original values before masking\n and thus used as labels for the task.\n \"\"\"\n if not isinstance(item_selector, item_selector_ops.ItemSelector):\n raise ValueError(\"`item_selector` must be an instance of `ItemSelector`\")\n\n if not isinstance(mask_values_chooser, MaskValuesChooser):\n raise ValueError(\"`mask_values_chooser` must be an instance of \" +\n \"`MaskValuesChooser`\")\n\n input_ids = ragged_tensor.convert_to_tensor_or_ragged_tensor(input_ids)\n\n # Identify the items that are maskable and obtain their positions in the\n # rank 2 space.\n masked_token_positions = _get_selected_item_positions(\n item_selector, input_ids, axis)\n\n # Flatten everything down to a 2D RaggedTensor\n masked_token_positions = (\n masked_token_positions if masked_token_positions.ragged_rank == 1 else\n masked_token_positions.merge_dims(1, -1))\n input_ids = (\n input_ids if input_ids.ragged_rank == 1 else input_ids.merge_dims(1, -1))\n\n # Gather all the current ids in the places selected for masking.\n masked_lm_ids = array_ops.batch_gather(input_ids, masked_token_positions)\n\n # Figure out what we are going to replace these values with -- either masked\n # token, random int id, or do nothing.\n mask_values = mask_values_chooser.get_mask_values(masked_lm_ids)\n\n # scatter the new mask values back to their respective positions\n new_input_ids = _ragged_tensor_scatter_nd_update(input_ids,\n masked_token_positions,\n mask_values)\n return new_input_ids, masked_token_positions, masked_lm_ids\n\n\nclass MaskValuesChooser(object):\n \"\"\"Assigns values to the items chosen for masking.\n\n `MaskValuesChooser` encapsulates the logic for deciding the value to assign\n items that where chosen for masking. The following are the behavior in the\n default implementation:\n\n For `mask_token_rate` of the time, replace the item with the `[MASK]` token:\n\n ```\n my dog is hairy -> my dog is [MASK]\n ```\n\n For `random_token_rate` of the time, replace the item with a random word:\n\n ```\n my dog is hairy -> my dog is apple\n ```\n\n For `1 - mask_token_rate - random_token_rate` of the time, keep the item\n unchanged:\n\n ```\n my dog is hairy -> my dog is hairy.\n ```\n\n The default behavior is consistent with the methodology specified in\n `Masked LM and Masking Procedure` described in `BERT: Pre-training of Deep\n Bidirectional Transformers for Language Understanding`\n (https://arxiv.org/pdf/1810.04805.pdf).\n\n Users may further customize this with behavior through subclassing and\n overriding `get_mask_values()`.\n \"\"\"\n\n def __init__(self,\n vocab_size,\n mask_token,\n mask_token_rate=0.8,\n random_token_rate=0.1):\n \"\"\"Creates an instance of `MaskValueChooser`.\n\n Args:\n vocab_size: size of vocabulary.\n mask_token: The id of the mask token.\n mask_token_rate: (optional) A float between 0 and 1 which indicates how\n often the `mask_token` is substituted for tokens selected for masking.\n Default is 0.8, NOTE: `mask_token_rate` + `random_token_rate` <= 1.\n random_token_rate: A float between 0 and 1 which indicates how often a\n random token is substituted for tokens selected for masking. Default is\n 0.1. NOTE: `mask_token_rate` + `random_token_rate` <= 1.\n \"\"\"\n if mask_token_rate is None:\n raise ValueError(\"`mask_token_rate` cannot be None\")\n if random_token_rate is None:\n raise ValueError(\"`random_token_rate` cannot be None\")\n self._mask_token_rate = mask_token_rate\n self._random_token_rate = random_token_rate\n self._mask_token = mask_token\n self._vocab_size = vocab_size\n\n @property\n def mask_token(self):\n return self._mask_token\n\n @property\n def random_token_rate(self):\n return self._random_token_rate\n\n @property\n def vocab_size(self):\n return self._vocab_size\n\n def get_mask_values(self, masked_lm_ids):\n \"\"\"Get the values used for masking, random injection or no-op.\n\n Args:\n masked_lm_ids: a `RaggedTensor` of n dimensions and dtype int32 or int64\n whose values are the ids of items that have been selected for masking.\n Returns:\n a `RaggedTensor` of the same dtype and shape with `masked_lm_ids` whose\n values contain either the mask token, randomly injected token or original\n value.\n \"\"\"\n validate_rates = control_flow_ops.Assert(\n self._mask_token_rate + self._random_token_rate <= 1,\n [\"mask_token_rate + random_token_rate must be <= 1\"])\n with ops.control_dependencies([validate_rates]):\n\n # Generate a random number for all mask-able items. Items that should be\n # treated atomically (e.g. all wordpieces in a token, span, etc) will have\n # the same random number.\n random_uniform = _get_random(masked_lm_ids)\n\n # Merge down to rank 2.\n random_uniform = (\n random_uniform if random_uniform.ragged_rank == 1 else\n random_uniform.merge_dims(1, -1))\n mask_values = masked_lm_ids\n\n all_mask_flat = array_ops.tile([self._mask_token],\n array_ops.shape(mask_values.flat_values))\n\n # Maybe add mask token `mask_token_rate`% of the time\n should_mask_flat = random_uniform.flat_values < math_ops.cast(\n self._mask_token_rate, dtypes.float32)\n mask_values = mask_values.with_flat_values(\n ragged_where_op.where(\n should_mask_flat,\n x=math_ops.cast(all_mask_flat, mask_values.flat_values.dtype),\n y=mask_values.flat_values))\n\n # Maybe inject random token `random_token_rate`% of the time.\n all_random_flat = random_ops.random_uniform(\n array_ops.shape(mask_values.flat_values), maxval=math_ops.cast(\n self._vocab_size, dtypes.float32))\n should_inject_random_flat = math_ops.logical_and(\n random_uniform.flat_values > self._mask_token_rate,\n random_uniform.flat_values < self._random_token_rate)\n mask_values = mask_values.with_flat_values(\n ragged_where_op.where(\n should_inject_random_flat,\n x=math_ops.cast(all_random_flat, mask_values.flat_values.dtype),\n y=mask_values.flat_values))\n return mask_values\n", "# coding=utf-8\n# Copyright 2021 TF.Text Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Tests for ToDense Keras layer.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom absl.testing import parameterized\nimport numpy as np\n\nfrom tensorflow.python import keras\nfrom tensorflow.python.data.ops import dataset_ops\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import sparse_tensor\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.keras import backend as K\nfrom tensorflow.python.keras import keras_parameterized\nfrom tensorflow.python.keras import testing_utils\nfrom tensorflow.python.keras.engine.base_layer import Layer\nfrom tensorflow.python.keras.layers import recurrent as rnn_v1\nfrom tensorflow.python.keras.layers import recurrent_v2 as rnn_v2\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops.ragged import ragged_factory_ops\nfrom tensorflow.python.platform import test\nfrom tensorflow_text.python.keras.layers.todense import ToDense\n\n\nclass Final(Layer):\n \"\"\"This is a helper layer that can be used as the last layer in a network for testing purposes.\"\"\"\n\n def call(self, inputs):\n return math_ops.cast(inputs, dtypes.float32)\n\n def compute_output_shape(self, input_shape):\n return input_shape\n\n def get_config(self):\n base_config = super(Final, self).get_config()\n return dict(list(base_config.items()))\n\n\ndef get_input_dataset(in_data, out_data=None):\n batch_size = in_data.shape[0]\n if out_data is None:\n return dataset_ops.DatasetV2.from_tensor_slices(in_data).batch(batch_size)\n\n return dataset_ops.DatasetV2.from_tensor_slices(\n (in_data, out_data)).batch(batch_size)\n\n\n@keras_parameterized.run_with_all_model_types\n@keras_parameterized.run_all_keras_modes\nclass RaggedTensorsToDenseLayerTest(keras_parameterized.TestCase):\n\n def SKIP_test_ragged_input_default_padding(self):\n input_data = get_input_dataset(\n ragged_factory_ops.constant([[1, 2, 3, 4, 5], [2, 3]]))\n expected_output = np.array([[1, 2, 3, 4, 5], [2, 3, 0, 0, 0]])\n\n layers = [ToDense(), Final()]\n model = testing_utils.get_model_from_layers(\n layers,\n input_shape=(None,),\n input_ragged=True,\n input_dtype=dtypes.int32)\n model.compile(\n optimizer=\"sgd\",\n loss=\"mse\",\n metrics=[\"accuracy\"],\n run_eagerly=testing_utils.should_run_eagerly())\n output = model.predict(input_data)\n self.assertAllEqual(output, expected_output)\n\n def SKIP_test_ragged_input_with_padding(self):\n input_data = get_input_dataset(\n ragged_factory_ops.constant([[[1, 2, 3, 4, 5]], [[2], [3]]]))\n expected_output = np.array([[[1., 2., 3., 4., 5.],\n [-1., -1., -1., -1., -1.]],\n [[2., -1., -1., -1., -1.],\n [3., -1., -1., -1., -1.]]])\n\n layers = [ToDense(pad_value=-1), Final()]\n model = testing_utils.get_model_from_layers(\n layers,\n input_shape=(None, None),\n input_ragged=True,\n input_dtype=dtypes.int32)\n model.compile(\n optimizer=\"sgd\",\n loss=\"mse\",\n metrics=[\"accuracy\"],\n run_eagerly=testing_utils.should_run_eagerly())\n output = model.predict(input_data)\n self.assertAllEqual(output, expected_output)\n\n def test_ragged_input_pad_and_mask(self):\n input_data = ragged_factory_ops.constant([[1, 2, 3, 4, 5], []])\n expected_mask = np.array([True, False])\n\n output = ToDense(pad_value=-1, mask=True)(input_data)\n self.assertTrue(hasattr(output, \"_keras_mask\"))\n self.assertIsNot(output._keras_mask, None)\n self.assertAllEqual(K.get_value(output._keras_mask), expected_mask)\n\n def test_ragged_input_shape(self):\n input_data = get_input_dataset(\n ragged_factory_ops.constant([[1, 2, 3, 4, 5], [2, 3]]))\n expected_output = np.array([[1, 2, 3, 4, 5, 0, 0], [2, 3, 0, 0, 0, 0, 0]])\n\n layers = [ToDense(shape=[2, 7]), Final()]\n model = testing_utils.get_model_from_layers(\n layers,\n input_shape=(None,),\n input_ragged=True,\n input_dtype=dtypes.int32)\n model.compile(\n optimizer=\"sgd\",\n loss=\"mse\",\n metrics=[\"accuracy\"],\n run_eagerly=testing_utils.should_run_eagerly())\n output = model.predict(input_data)\n self.assertAllEqual(output, expected_output)\n\n @parameterized.named_parameters(\n *test_util.generate_combinations_with_testcase_name(layer=[\n rnn_v1.SimpleRNN, rnn_v1.GRU, rnn_v1.LSTM, rnn_v2.GRU, rnn_v2.LSTM\n ]))\n def SKIP_test_ragged_input_RNN_layer(self, layer):\n input_data = get_input_dataset(\n ragged_factory_ops.constant([[1, 2, 3, 4, 5], [5, 6]]))\n\n layers = [\n ToDense(pad_value=7, mask=True),\n keras.layers.Embedding(8, 16),\n layer(16),\n keras.layers.Dense(3, activation=\"softmax\"),\n keras.layers.Dense(1, activation=\"sigmoid\")\n ]\n model = testing_utils.get_model_from_layers(\n layers,\n input_shape=(None,),\n input_ragged=True,\n input_dtype=dtypes.int32)\n model.compile(\n optimizer=\"rmsprop\",\n loss=\"binary_crossentropy\",\n metrics=[\"accuracy\"],\n run_eagerly=testing_utils.should_run_eagerly())\n\n output = model.predict(input_data)\n self.assertAllEqual(np.zeros((2, 1)).shape, output.shape)\n\n\n@keras_parameterized.run_with_all_model_types\n@keras_parameterized.run_all_keras_modes\nclass SparseTensorsToDenseLayerTest(keras_parameterized.TestCase):\n\n def SKIP_test_sparse_input_default_padding(self):\n input_data = get_input_dataset(\n sparse_tensor.SparseTensor(\n indices=[[0, 0], [1, 2]], values=[1, 2], dense_shape=[3, 4]))\n\n expected_output = np.array([[1., 0., 0., 0.], [0., 0., 2., 0.],\n [0., 0., 0., 0.]])\n\n layers = [ToDense(), Final()]\n model = testing_utils.get_model_from_layers(\n layers,\n input_shape=(None,),\n input_sparse=True,\n input_dtype=dtypes.int32)\n model.compile(\n optimizer=\"sgd\",\n loss=\"mse\",\n metrics=[\"accuracy\"],\n run_eagerly=testing_utils.should_run_eagerly())\n output = model.predict(input_data)\n self.assertAllEqual(output, expected_output)\n\n def SKIP_test_sparse_input_with_padding(self):\n input_data = get_input_dataset(\n sparse_tensor.SparseTensor(\n indices=[[0, 0], [1, 2]], values=[1, 2], dense_shape=[3, 4]))\n\n expected_output = np.array([[1., -1., -1., -1.], [-1., -1., 2., -1.],\n [-1., -1., -1., -1.]])\n\n layers = [ToDense(pad_value=-1, trainable=False), Final()]\n model = testing_utils.get_model_from_layers(\n layers,\n input_shape=(None,),\n input_sparse=True,\n input_dtype=dtypes.int32)\n model.compile(\n optimizer=\"sgd\",\n loss=\"mse\",\n metrics=[\"accuracy\"],\n run_eagerly=testing_utils.should_run_eagerly())\n output = model.predict(input_data)\n self.assertAllEqual(output, expected_output)\n\n def test_sparse_input_pad_and_mask(self):\n input_data = sparse_tensor.SparseTensor(\n indices=[[0, 0], [1, 2]], values=[1, 2], dense_shape=[3, 4])\n\n expected_mask = np.array([True, True, False])\n\n output = ToDense(pad_value=-1, mask=True)(input_data)\n self.assertTrue(hasattr(output, \"_keras_mask\"))\n self.assertIsNot(output._keras_mask, None)\n self.assertAllEqual(K.get_value(output._keras_mask), expected_mask)\n\n def test_sparse_input_shape(self):\n input_data = get_input_dataset(\n sparse_tensor.SparseTensor(\n indices=[[0, 0], [1, 2]], values=[1, 2], dense_shape=[3, 4]))\n\n expected_output = np.array([[1., 0., 0., 0.], [0., 0., 2., 0.],\n [0., 0., 0., 0.]])\n\n layers = [ToDense(shape=[3, 4]), Final()]\n model = testing_utils.get_model_from_layers(\n layers,\n input_shape=(None,),\n input_sparse=True,\n input_dtype=dtypes.int32)\n model.compile(\n optimizer=\"sgd\",\n loss=\"mse\",\n metrics=[\"accuracy\"],\n run_eagerly=testing_utils.should_run_eagerly())\n output = model.predict(input_data)\n self.assertAllEqual(output, expected_output)\n\n\nif __name__ == \"__main__\":\n test.main()\n" ]
[ [ "tensorflow.python.ops.math_ops.minimum", "tensorflow.python.ops.math_ops.reduce_sum", "tensorflow.python.ops.array_ops.unstack", "tensorflow.python.ops.array_ops.ones_like", "tensorflow.python.ops.array_ops.expand_dims", "tensorflow.python.ops.math_ops.reduce_all", "tensorflow.python.ops.math_ops.cast", "tensorflow.python.ops.ragged.ragged_functional_ops.map_flat_values", "tensorflow.python.ops.array_ops.concat", "tensorflow.python.ops.array_ops.get_positive_axis", "tensorflow.python.ops.ragged.ragged_math_ops.range", "tensorflow.python.ops.array_ops.gather", "tensorflow.python.ops.gen_array_ops.tensor_scatter_update", "tensorflow.python.ops.ragged.ragged_array_ops.boolean_mask", "tensorflow.python.ops.ragged.ragged_tensor.RaggedTensorSpec", "tensorflow.python.ops.array_ops.zeros_like", "tensorflow.python.framework.ops.convert_to_tensor", "tensorflow.python.ops.array_ops.size", "tensorflow.python.ops.array_ops.shape", "tensorflow.python.ops.array_ops.reshape" ], [ "tensorflow.python.ops.math_ops.cast", "tensorflow.python.ops.math_ops.logical_and", "tensorflow.python.ops.array_ops.tensor_scatter_update", "tensorflow.python.ops.array_ops.batch_gather", "tensorflow.python.ops.array_ops.size", "tensorflow.python.ops.array_ops.expand_dims", "tensorflow.python.ops.ragged.ragged_tensor.convert_to_tensor_or_ragged_tensor", "tensorflow.python.ops.array_ops.shape", "tensorflow.python.ops.ragged.ragged_array_ops.boolean_mask", "tensorflow.python.framework.ops.control_dependencies", "tensorflow.python.ops.control_flow_ops.Assert" ], [ "numpy.array", "tensorflow.python.ops.math_ops.cast", "numpy.zeros", "tensorflow.python.keras.testing_utils.get_model_from_layers", "tensorflow.python.ops.ragged.ragged_factory_ops.constant", "tensorflow.python.keras.layers.Embedding", "tensorflow.python.keras.testing_utils.should_run_eagerly", "tensorflow.python.keras.backend.get_value", "tensorflow.python.keras.layers.Dense", "tensorflow.python.data.ops.dataset_ops.DatasetV2.from_tensor_slices", "tensorflow.python.platform.test.main", "tensorflow.python.framework.sparse_tensor.SparseTensor", "tensorflow.python.framework.test_util.generate_combinations_with_testcase_name" ] ]
nmearl/spectacle
[ "ae2d11a41dfae5430de392d54b06bf991003fd69" ]
[ "spectacle/utils/detection.py" ]
[ "import logging\n\nimport astropy.units as u\nimport numpy as np\nfrom astropy.convolution import convolve\n\nfrom spectacle.utils.misc import find_nearest\nfrom collections import OrderedDict\n\n__all__ = ['region_bounds']\n\n\ndef _make_data_diffs(y):\n kernel = [1, 0, -1]\n\n dY = convolve(y, kernel, 'extend', normalize_kernel=False) #np.diff(y)\n # dY_mask = np.greater(np.abs(dY), np.max(dY) * 0.1)\n # dY[~dY_mask] = 0\n ddY = convolve(dY, kernel, 'extend', normalize_kernel=False) #np.diff(dY)\n dddY = convolve(ddY, kernel, 'extend', normalize_kernel=False) #np.diff(ddY)\n\n return dY, ddY, dddY\n\n\ndef _make_sign_diffs(dY, ddY, dddY):\n kernel = [1, 0, -1]\n\n # Anywhere that dS >/< 0 is a line for absorption/emission.\n # Anywhere that ddS == 0\n dS = convolve(np.sign(dY), kernel, 'extend', normalize_kernel=False)\n ddS = convolve(np.sign(ddY), kernel, 'extend', normalize_kernel=False)\n dddS = convolve(np.sign(dddY), kernel, 'extend', normalize_kernel=False)\n\n return dS, ddS, dddS\n\n\ndef _generate_masks(y, threshold, dS, ddS, dddS, is_absorption):\n if is_absorption:\n new_y = np.max(y) - y\n thresh_mask = np.greater(new_y/np.max(new_y), threshold)\n else:\n thresh_mask = np.greater(y/np.max(y), threshold)\n\n # Mask areas that don't provide line information. The secondary\n # convolution should gives us the bounds of when we enter (upward slope,\n # for absorption) and exit (downward slope, for absorption) a feature.\n ddS_mask = ((ddS < 0) | (ddS > 0)) & thresh_mask\n\n # The tertiary convolution provides information on buried lines. If, in\n # absorption, there is a negative convolution value between the bounds\n # defined in the secondary convolution, then there is a buried line.\n # dddS_mask = ((dddS < 0) | (dddS > 0)) & thresh_mask\n\n if is_absorption:\n # Mask for lines in absorption. During convolution, the values of ds\n # that are < 0 represent downward-curved changes in the spectrum\n # (i.e. when the we a peak close to the continuum between peaks). So,\n # only grab the parts where we have a upward curve (i.e. when we've\n # hit the bottom of an absorption trough).\n dS_mask = (dS > 0) & thresh_mask\n dddS_mask = (dddS < 0) & thresh_mask\n else:\n # Mask for lines in emission\n dS_mask = (dS < 0) & thresh_mask\n dddS_mask = (dddS > 0) & thresh_mask\n\n return dS_mask, ddS_mask, dddS_mask\n\n\ndef _find_ternary_bounds(x, ddS_mask, dddS_mask, min_distance, is_absorption):\n ternary_regions = OrderedDict()\n\n # Find \"buried\" lines. Do this by taking the third difference of the\n # spectrum. Find the indices where the dddS_mask is true, retrieve only a\n # single index from the tuple by going in steps of 2. Each tind represents\n # the index of the centroid of the found buried line.\n for tind in np.where(dddS_mask)[0][::2]:\n # ddS contains bounds information. Find the lower bound index of the\n # dispersion.\n lower_ind = find_nearest(\n np.ma.array(x.value, mask=~ddS_mask | (x.value > x.value[tind])),\n x.value[tind])\n # ddS contains bounds information. Find the upper bound index of the\n # dispersion.\n upper_ind = find_nearest(\n np.ma.array(x.value, mask=~ddS_mask | (x.value < x.value[tind])),\n x.value[tind])\n\n # Retrieve the dispersion value for these indices and set the\n # dispersion value for the centroid.\n lower_x_ddS, upper_x_ddS = x.value[lower_ind], \\\n x.value[upper_ind]\n\n if lower_ind == 0 or upper_ind == x.size - 1:\n continue\n\n x_dddS = x[tind]\n\n # if is_absorption:\n # # This is truly a buried line if, for absorption, if the sign of\n # # the lower index in the bounds mask is greater than the upper.\n # cond = (dddS[lower_ind] > dddS[upper_ind])\n # else:\n # # This is truly a buried line if, for emission, if the sign of\n # # the lower index in the bounds mask is greater than the upper.\n # cond = (dddS[lower_ind] < dddS[upper_ind])\n\n # if True:\n # Ensure that this found peak value is not within the minimum\n # distance of any other found peak values.\n if np.all([np.abs(x - x_dddS) > min_distance\n for x, _, _, _ in ternary_regions.values()]):\n ternary_regions[(lower_ind, upper_ind)] = (\n x_dddS, (lower_x_ddS, upper_x_ddS), is_absorption, True)\n\n return ternary_regions\n\n\ndef _find_primary_bounds(x, dS_mask, ddS_mask, min_distance, is_absorption):\n prime_regions = OrderedDict()\n\n # Find obvious lines by peak values.\n for pind in np.where(dS_mask)[0][::2]:\n lower_ind = find_nearest(\n np.ma.array(x.value, mask=~ddS_mask | (x.value > x.value[pind])),\n x.value[pind])\n upper_ind = find_nearest(\n np.ma.array(x.value, mask=~ddS_mask | (x.value < x.value[pind])),\n x.value[pind])\n\n lower_x_ddS, upper_x_ddS = x.value[lower_ind], \\\n x.value[upper_ind]\n x_dS = x[pind]\n\n # if is_absorption:\n # cond = np.sign(ddS[lower_ind]) > np.sign(ddS[upper_ind])\n # else:\n # cond = np.sign(ddS[lower_ind]) < np.sign(ddS[upper_ind])\n\n # if cond:\n # Ensure that this found peak value is not within the minimum\n # distance of any other found peak values.\n if np.all([np.abs(x - x_dS) > min_distance\n for x, _, _, _ in prime_regions.values()]):\n prime_regions[(lower_ind, upper_ind)] = (\n x_dS, (lower_x_ddS, upper_x_ddS), is_absorption, False)\n\n return prime_regions\n\n\ndef profile_type(x, y):\n mid_y = min(y) + (max(y) - min(y)) * 0.5\n return 'absorption' if len(y[y > mid_y]) > len(y[y < mid_y]) else 'emission'\n\n\ndef region_bounds(x, y, threshold=0.001, min_distance=1):\n # Slice the y axis in half -- if more data elements exist in the \"top\"\n # half, assume the spectrum is absorption. Otherwise, assume emission.\n is_absorption = profile_type(x, y) == 'absorption'\n\n if not isinstance(min_distance, u.Quantity):\n min_distance *= x.unit\n\n dY, ddY, dddY = _make_data_diffs(y)\n dS, ddS, dddS = _make_sign_diffs(dY, ddY, dddY)\n\n dS_mask, ddS_mask, dddS_mask = _generate_masks(y, threshold, dS, ddS, dddS,\n is_absorption)\n\n ternary_regions = _find_ternary_bounds(x, ddS_mask, dddS_mask,\n min_distance, is_absorption)\n prime_regions = _find_primary_bounds(x, dS_mask, ddS_mask, min_distance,\n is_absorption)\n\n # Delete any information in ternary that shares the same bounds in primary\n for k in prime_regions:\n if k in ternary_regions:\n del ternary_regions[k]\n\n # For the ternary centroids closest to a prime centroid, use the bounds\n # information of the primary centroid\n for (t_low_ind, t_up_ind), (t_cent, bnds, is_absorb, buried) in ternary_regions.copy().items():\n p_cents = [pr[0] for pr in prime_regions.values()]\n p_bnds = [(lo, hi) for lo, hi in prime_regions]\n\n # Find closest index\n ind = find_nearest(np.array([c.value for c in p_cents]), t_cent.value)\n p_cent = p_cents[ind]\n p_bnd = p_bnds[ind]\n # p_ind = find_nearest(x.value, p_cent.value)\n\n new_t_up_ind = t_up_ind\n new_t_low_ind = t_low_ind\n\n # If the prime centroid is greater than the ternary centroid,\n # update the ternary upper bound.\n if p_cent > t_cent:\n new_t_up_ind = p_bnd[1] # p_ind\n else:\n new_t_low_ind = p_bnd[0] # p_ind\n\n del ternary_regions[(t_low_ind, t_up_ind)]\n\n ternary_regions[(new_t_low_ind, new_t_up_ind)] = (\n t_cent, (x.value[new_t_low_ind], x.value[new_t_up_ind]),\n is_absorb, buried)\n\n ternary_regions.update(prime_regions)\n\n return ternary_regions\n" ]
[ [ "numpy.max", "numpy.array", "numpy.sign", "numpy.where", "numpy.ma.array", "numpy.abs" ] ]
GenyaNobuhara/VRP_DRL_MHA
[ "44a0f70e927c715db478e9e1875fd0c7023a2644" ]
[ "PyTorch/decoder.py" ]
[ "import torch\nimport torch.nn as nn\n\nfrom layers import MultiHeadAttention, DotProductAttention\nfrom data import generate_data\nfrom decoder_utils import TopKSampler, CategoricalSampler, Env\n\nclass DecoderCell(nn.Module):\n\tdef __init__(self, embed_dim = 128, n_heads = 8, clip = 10., **kwargs):\n\t\tsuper().__init__(**kwargs)\n\t\t\n\t\tself.Wk1 = nn.Linear(embed_dim, embed_dim, bias = False)\n\t\tself.Wv = nn.Linear(embed_dim, embed_dim, bias = False)\n\t\tself.Wk2 = nn.Linear(embed_dim, embed_dim, bias = False)\n\t\tself.Wq_fixed = nn.Linear(embed_dim, embed_dim, bias = False)\n\t\tself.Wout = nn.Linear(embed_dim, embed_dim, bias = False)\n\t\tself.Wq_step = nn.Linear(embed_dim+2, embed_dim, bias = False)\n\t\t\n\t\tself.MHA = MultiHeadAttention(n_heads = n_heads, embed_dim = embed_dim, need_W = False)\n\t\tself.SHA = DotProductAttention(clip = clip, return_logits = True, head_depth = embed_dim)\n\t\t# SHA ==> Single Head Attention, because this layer n_heads = 1 which means no need to spilt heads\n\t\tself.env = Env\n\t\tself.device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n\n\tdef compute_static(self, node_embeddings, graph_embedding):\n\t\tself.Q_fixed = self.Wq_fixed(graph_embedding[:,None,:])\n\t\tself.K1 = self.Wk1(node_embeddings)\n\t\tself.V = self.Wv(node_embeddings)\n\t\tself.K2 = self.Wk2(node_embeddings)\n\t\t\n\tdef compute_dynamic(self, mask, step_context):\n\t\tQ_step = self.Wq_step(step_context)\n\t\tQ1 = self.Q_fixed + Q_step\n\t\tQ2 = self.MHA([Q1, self.K1, self.V], mask = mask)\n\t\tQ2 = self.Wout(Q2)\n\t\tlogits = self.SHA([Q2, self.K2, None], mask = mask)\n\t\treturn logits.squeeze(dim = 1)\n\n\tdef forward(self, x, encoder_output, return_pi = False, decode_type = 'sampling'):\n\t\tnode_embeddings, graph_embedding = encoder_output\n\t\tself.compute_static(node_embeddings, graph_embedding)\n\t\tenv = Env(x, node_embeddings)\n\t\tmask, step_context, D , T= env._create_t1()\n\n\t\tselecter = {'greedy': TopKSampler(), 'sampling': CategoricalSampler()}.get(decode_type, None)\n\t\tlog_ps, tours = [], []\n\t\tfirst_node = [[0]]*step_context.size()[0]\n\t\tnow_node = torch.tensor(first_node).to(self.device)\n\t\t#時間コストの計算\n\t\ttime_cost = torch.tensor(first_node,dtype=torch.float).to(self.device)\n\t\t#累積時間\n\t\t#CTime = torch.tensor(first_node,dtype = torch.float)\n\t\tfor i in range(env.n_nodes*2):\n\t\t\tlogits = self.compute_dynamic(mask, step_context)\n\t\t\tlog_p = torch.log_softmax(logits, dim = -1)\n\t\t\tnext_node = selecter(log_p)\n\t\t\t#距離を計算\n\t\t\trequired_time = env.get_cost_path(now_node,next_node) #[batchsize]\n\t\t\tT = T + required_time\n\t\t\ttime_cost += env.get_time_cost(next_node,T)\n\t\t\tT += 1/12\n\t\t\tmask, step_context, D, T = env._get_step(next_node, D, T)\n\t\t\ttours.append(next_node.squeeze(1))\n\t\t\tlog_ps.append(log_p)\n\t\t\tnow_node = next_node\n\t\t\tif env.visited_customer.all():\n\t\t\t\tbreak\n\n\t\tpi = torch.stack(tours, 1)\n\t\tcost = env.get_costs(pi)\n\t\tcost += time_cost.view(-1)\n\t\tll = env.get_log_likelihood(torch.stack(log_ps, 1), pi)\n\t\t\n\t\tif return_pi:\n\t\t\treturn cost, ll, pi, time_cost\n\t\treturn cost, ll, time_cost\n\nif __name__ == '__main__':\n\tbatch, n_nodes, embed_dim = 1, 11, 128\n\tdata = generate_data('cuda:0' if torch.cuda.is_available() else 'cpu',n_samples = batch, n_customer = n_nodes-1)\n\tdecoder = DecoderCell(embed_dim, n_heads = 8, clip = 10.)\n\tnode_embeddings = torch.rand((batch, n_nodes, embed_dim), dtype = torch.float)\n\tgraph_embedding = torch.rand((batch, embed_dim), dtype = torch.float)\n\tencoder_output = (node_embeddings, graph_embedding)\n\t# a = graph_embedding[:,None,:].expand(batch, 7, embed_dim)\n\t# a = graph_embedding[:,None,:].repeat(1, 7, 1)\n\t# print(a.size())\n\n\tdecoder.train()\n\tcost, ll, pi, time_cost = decoder(data, encoder_output, return_pi = True, decode_type = 'sampling')\n\tprint('\\ndata: ',data)\n\tprint('\\ncost: ', cost.size(), cost)\n\tprint('\\nll: ', ll.size(), ll)\n\tprint('\\npi: ', pi.size(), pi)\n\tprint('\\ntimecost:',time_cost.size(),time_cost)\n\n\t# ll.mean().backward()\n\t# print(decoder.Wk1.weight.grad)\n\t# https://discuss.pytorch.org/t/model-param-grad-is-none-how-to-debug/52634\t" ]
[ [ "torch.nn.Linear", "torch.rand", "torch.stack", "torch.log_softmax", "torch.cuda.is_available", "torch.tensor" ] ]
mathislucka/toxic-comment-collection
[ "70bdf35735c3b67a6ef09ce25e67e74d497279cf" ]
[ "src/toxic_comment_collection/datasets/wulczyn2017toxic.py" ]
[ "from . import dataset\nfrom . import helpers\nimport os\nimport pandas as pd\n\n\nclass Wulczyn2017toxic(dataset.Dataset):\n \n name = \"wulczyn2017toxic\"\n url = \"https://ndownloader.figshare.com/articles/4563973/versions/2\"\n hash = \"9e48068af1fbbe893af4df1b629ceebf924dc723a290c7bc473d2a8a8aac3529\"\n files = [\n {\n \"name\": \"wulczyn2017en_toxic.csv\",\n \"language\": \"en\",\n \"type\": \"training\",\n \"platform\": \"wikipedia\"\n }\n ]\n license = \"\"\" \"\"\"\n\n @classmethod\n def valid_hash(cls, file):\n \"\"\"do not check hash since it differs for each download\"\"\"\n return\n\n @classmethod\n def process(cls, tmp_file_path, dataset_folder, api_config):\n tmp_file_path = helpers.unzip_file(tmp_file_path)\n file1 = helpers.clean_csv(os.path.join(tmp_file_path, \"toxicity_annotated_comments.tsv\"), sep=\"\\t\")\n file2 = helpers.clean_csv(os.path.join(tmp_file_path, \"toxicity_annotations.tsv\"), sep=\"\\t\")\n \n df1 = pd.read_csv(file1)\n df1['comment'] = df1['comment'].apply(lambda x: x.replace(\"NEWLINE_TOKEN\", \" \"))\n df1['comment'] = df1['comment'].apply(lambda x: x.replace(\"TAB_TOKEN\", \" \"))\n df1.to_csv(file1 + \"_endings\", index=False)\n\n df2 = pd.read_csv(file2)\n labels = df2.groupby([\"rev_id\"]).mean() > 0.5\n labels.to_csv(file2 + \"_grouped\")\n\n tmp_file_path = helpers.join_csvs(file1 + \"_endings\", \"rev_id\", file2 + \"_grouped\", \"rev_id\")\n helpers.copy_file(tmp_file_path, os.path.join(dataset_folder, \"wulczyn2017en_toxic.csv\"))\n \n @classmethod\n def unify_row(cls, row):\n row[\"text\"] = row[\"comment\"]\n labels = []\n if row[\"toxicity\"]:\n labels.append(\"toxic\")\n else:\n labels.append(\"none\")\n row[\"labels\"] = labels\n row = row.drop([\"rev_id\",\"comment\",\"year\",\"logged_in\",\"ns\",\"sample\",\"split\",\"worker_id\",\"toxicity\",\"toxicity_score\"])\n return row\n " ]
[ [ "pandas.read_csv" ] ]
maria-kuruvilla/temp_collective_code
[ "11367dd6d70d924af0d1ea765fb95734b00253bb" ]
[ "trajectories_in_tank.py" ]
[ "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Aug 14 2020\n\n@author: Maria Kuruvilla\n\nGoal - Code to visualise trajectoies in the tank to know the dimensions of the tank\n\"\"\"\n\n\nimport sys, os\nimport pathlib\nfrom pprint import pprint\n\nimport numpy as np\nfrom scipy import stats\nfrom scipy.spatial import distance\nimport matplotlib.pyplot as plt\nfrom matplotlib.pyplot import figure\n\nimport trajectorytools as tt\nimport trajectorytools.plot as ttplot\nimport trajectorytools.socialcontext as ttsocial\nfrom trajectorytools.constants import dir_of_data\nimport pickle\nimport argparse\n\nparent_dir = '../../output/temp_collective/roi'\n\ndef track_tank(i,j,k):\n\n\n\tinput_dir = parent_dir + '/' + str(i) + '/' + str(j) + '/' \n\tinput_file = input_dir + str(k) + '.p'\n\tsigma_values = 1.5 #smoothing parameter\n\ttry:\n\t tr = pickle.load(open(input_file, 'rb')) # 'rb is for read binary\n\texcept FileNotFoundError:\n\t print(i,j,k)\n\t print('File not found')\n\t pass\n\n\tfig, ax_trajectories = plt.subplots(figsize=(5,5))\n\t#time_range= (0, 60) # SET HERE THE RANGE IN SECONDS FOR WHICH YOU WANT TO PLOT THE POSITIONS\n\tframe_range = range(tr.s.shape[0]) \n\n\tfor i in range(tr.number_of_individuals):\n\t\tax_trajectories.plot(tr.s[frame_range,i,0], tr.s[frame_range,i,1])\n\t\tax_trajectories.set_aspect('equal','box')\n\t\tax_trajectories.set_title('Trajectories',fontsize=24)\n\t\tax_trajectories.set_xlabel('X (BL)',fontsize=24)\n\t\tax_trajectories.set_ylabel('Y (BL)',fontsize=24)\n\tplt.show()\n\"\"\"\n#argparse\ndef boolean_string(s):\n # this function helps with getting Boolean input\n if s not in ['False', 'True']:\n raise ValueError('Not a valid boolean string')\n return s == 'True' # note use of ==\n\n# create the parser object\nparser = argparse.ArgumentParser()\n\n# NOTE: argparse will throw an error if:\n# - a flag is given with no value\n# - the value does not match the type\n# and if a flag is not given it will be filled with the default.\nparser.add_argument('-a', '--a_string', default='hi', type=str)\nparser.add_argument('-b1', '--integer_b1', default=29, type=int)\nparser.add_argument('-b2', '--integer_b2', default=16, type=int)\nparser.add_argument('-b3', '--integer_b3', default=3, type=int)\nparser.add_argument('-c', '--float_c', default=1.5, type=float)\nparser.add_argument('-v', '--verbose', default=True, type=boolean_string)\n# Note that you assign a short name and a long name to each argument.\n# You can use either when you call the program, but you have to use the\n# long name when getting the values back from \"args\".\n\n# get the arguments\nargs = parser.parse_args()\n\n\n\ninput_dir = parent_dir + '/' + str(args.integer_b1) + '/' + str(args.integer_b2) + '/' \ninput_file = input_dir + str(args.integer_b3) + '.p'\nsigma_values = 1.5 #smoothing parameter\ntry:\n tr = pickle.load(open(input_file, 'rb')) # 'rb is for read binary\nexcept FileNotFoundError:\n print(args.integer_b1,args.integer_b2,args.integer_b3)\n print('File not found')\n pass\ntrack_check(tr, args.integer_b1, args.integer_b2, args.integer_b3)\n#print(spikes_position(tr))\nplt.show()\n\"\"\"" ]
[ [ "matplotlib.pyplot.show", "matplotlib.pyplot.subplots" ] ]
asappresearch/interactive-classification
[ "58af3c9e95f2f3c14928bbb08534820e97ffc453" ]
[ "bdmodule/bd_simulator.py" ]
[ "import torch\nimport torch.nn as nn\nimport numpy as np\nfrom abc import ABC, abstractmethod\nimport pandas as pd\nimport json\nimport bdmodule.bd_utils as bd_utils\n#from module.data_loading_fromlocal import read_turkprob\n\n\nclass UserSimulator(ABC):\n @abstractmethod\n def answer(self ):\n pass\n\n\nclass NoisyUser(UserSimulator):\n def __init__(self, args):\n print('using oracle based user. ')\n self.uncertainty = args['user_uncertain']\n\n def answer(self, best_ft, batch, mode='test'):\n self.qr_fact = batch[1]\n answer = []\n for i in range(len(best_ft)):\n a = self.qr_fact[i, best_ft[i]]\n if np.random.binomial(1, self.uncertainty): \n #print('lying')\n a = 1 if np.random.binomial(1, 0.5) else 0\n answer.append(a)\n return answer\n\n\nclass Singleexample_User(UserSimulator):\n def __init__(self, args):\n print('using oracle based user. ')\n self.uncertainty = args['user_uncertain']\n\n label2att, att2label = bd_utils.att2label()\n\n if args['using_categorical']:\n binary_idx, categorical, tag_new2old, tag_old2new = bd_utils.parse_cat_binary()\n self.label2att = {lb:[tag_old2new[i] for i in label2att[lb]] for lb in label2att}\n self.att2label = [att2label[tag_new2old[new]] for new in tag_new2old]\n else:\n self.label2att, self.att2label = label2att, att2label\n\n self.labellist = list(self.label2att.keys())\n\n def answer_label(self, best_ft, batch, mode='test'):\n self.qr_fact = batch[1]\n answer = []\n answered_ft = []\n for i in range(len(best_ft)):\n ft = best_ft[i]\n if ft in self.qr_fact[i]:\n answer.append(1)\n answered_ft.append([ft])\n continue\n\n label = self.labellist[self.att2label[ft]]\n related_att = self.label2att[label]\n a=0\n for att in related_att :\n a += int( att in self.qr_fact[i]) \n if a==0: ## Nothing in the same category\n answer.append(-1)\n answered_ft.append(related_att)\n else: ## somthing in the category and the one asked is wrong\n answer.append(0)\n answered_ft.append([ft])\n return answer, answered_ft\n\n def answer_label_cat(self, best_ft, batch, aa, mode='test'):\n self.qr_fact = batch[1]\n self.tgts = batch[2].cpu().numpy()\n answer = []\n answered_ft = []\n for i in range(len(best_ft)):\n ft = best_ft[i]\n if ft < aa.nq_bi:\n if ft in self.qr_fact[i]:\n answer.append(1)\n answered_ft.append([ft])\n continue\n\n label = self.labellist[self.att2label[ft]]\n related_att = self.label2att[label]\n a=0\n for att in related_att :\n a += int( att in self.qr_fact[i]) \n if a==0: \n answer.append(-1)\n answered_ft.append(related_att)\n else:\n answer.append(0)\n answered_ft.append([ft])\n else:\n cat = aa.categorical[ ft-aa.nq_bi ]['idx']\n overlap = set(cat) & set(self.qr_fact[i])\n if len(overlap) ==0:\n a = -1\n else:\n a = np.random.choice(list(overlap))\n answer.append(a)\n answered_ft.append([ft])\n assert len(answer) == len(answered_ft)\n\n return answer, answered_ft\n\n def answer(self, best_ft, batch, mode='test'):\n\n self.qr_fact = batch[1]\n answer = []\n answered_ft = []\n for i in range(len(best_ft)):\n ft = best_ft[i]\n if ft in self.qr_fact[i]:\n a = 1\n else:\n a =0\n answer.append(a)\n return answer\n\n\n# class PersonaUser(UserSimulator):\n\n # def __init__(self, aa, args):\n # print('using persona based user. ')\n # self.args = args\n # self.lamda = 1 #args['user_lamda']\n # self.uncertainty = args['user_uncertain']\n # self.init_user_fromprob(aa)\n # #self.init_user_data(aa)\n\n\n\n # def init_user_fromprob(self, aa):\n\n # faq_probs = read_turkprob('full/')\n # #faq_probs = read_turkprob('sampled/sampled_')\n # prob_weight = [1, 1, 1, 1, 1]\n\n # query = aa.queryfile\n # datarecords= query.to_dict('records')\n # fq_tag_user = np.zeros(aa.gold_table.shape)\n \n # for i in range(len( datarecords)):\n # dr = datarecords[i]\n\n # tgttext = dr['faqtext'] if 'faqtext' in dr else dr['faq_original']\n # tgt_ids = aa.faqs.index(tgttext)\n # if i != tgt_ids:\n # print(i)\n # faqid = str(dr['faq_id'])\n \n \n # labeled = [int(faqid in fp) for fp in faq_probs]\n # if not 0 in labeled: \n # for i in range(len(faq_probs)):\n # probdict = faq_probs[i][faqid]\n # for tg in probdict.keys():\n # if tg in aa.tag_w2i:\n # fq_tag_user[tgt_ids, aa.tag_w2i[tg]] = probdict[tg]* prob_weight[i]\n # #fq_tag_user[tgt_ids, aa.tag_w2i[tg]] = int(probdict[tg] >=0.4)\n # else:\n # print('no data')\n # taglist = dr['taglist']\n # for tg in taglist:\n # if tg in aa.tag_w2i:\n # fq_tag_user[tgt_ids, aa.tag_w2i[tg]] = 1\n\n # goldtable = aa.gold_table\n # self.qtag_belief = self.lamda *fq_tag_user + (1- self.lamda )*goldtable\n\n\n\n # def answer(self, best_ft, batch, mode='test'):\n # self.tgts = batch[2].cpu().numpy()\n # answer = []\n # for i in range(len(best_ft)):\n # pa = min(1, self.qtag_belief[ self.tgts[i], best_ft[i]])\n \n # a = 1 if np.random.binomial(1, pa) else 0\n # '''\n # if mode == 'train':\n # a = int(pa >0.4)\n # else:\n # a = 1 if np.random.binomial(1, pa) else 0\n # '''\n # #if np.random.binomial(1, self.uncertainty): \n # # #print('lying')\n # # a = 1 if np.random.binomial(1, 0.5) else 0\n # answer.append(a)\n # return answer\n\n\n\n\n # # def readfold_cvs(self, path ):\n # # #fold = self.args['cv_n']\n # # #path = 'paf_anno_result/tag_anno_{}_result.csv'.format(fold)\n # # tagfile = pd.read_csv(path)\n # # tagfile = tagfile.drop(['HITId', 'HITTypeId', 'Title', 'Description', 'Keywords', 'Reward',\n # # 'CreationTime', 'MaxAssignments', 'RequesterAnnotation',\n # # 'AssignmentDurationInSeconds', 'AutoApprovalDelayInSeconds',\n # # 'Expiration', 'NumberOfSimilarHITs', 'LifetimeInSeconds',\n # # 'AssignmentId', 'WorkerId', 'AssignmentStatus', 'AcceptTime',\n # # 'SubmitTime', 'AutoApprovalTime', 'ApprovalTime', 'RejectionTime',\n # # 'RequesterFeedback', 'WorkTimeInSeconds', 'LifetimeApprovalRate',\n # # 'Last30DaysApprovalRate', 'Last7DaysApprovalRate', ], 1)\n # # tagfile['pos_tag'] = tagfile.apply(lambda x: [x['Input.'+key] if key!='na' else None for key in x['Answer.faq'].split('|')], 1) \n # # tags= tagfile.groupby(['Input.faq_id']).apply(lambda x: [tag for cnt in x['pos_tag'].tolist() for tag in cnt]).reset_index()\n # # tags.rename(columns = {0:'all_pos_tag'}, inplace = True)\n # # turk_cnt = tagfile.groupby(['Input.faq_id']).apply(lambda x: len(x)).reset_index()\n # # turk_cnt.rename(columns = {0:'turk_cnt'}, inplace = True)\n # # tags = tags.join(turk_cnt.set_index('Input.faq_id'), on='Input.faq_id', how='outer')\n # # tags = tags.rename(columns={'Input.faq_id':'faq_id'})\n # # return tags\n\n\n\n\n\n\n\n # # def init_user_data(self, aa):\n # # #================Reading and merging files ================\n # # alltags = []\n # # for i in range(5):\n # # path = 'paf_anno_result/tag_anno_{}_result.csv'.format(str(i))\n # # alltags.append(self.readfold(path))\n # # tags_0_5 = pd.concat(alltags)\n \n # # alltags = []\n # # for i in range(5):\n # # path = 'paf_anno_result/tag_from5_to15_file{}_result.csv'.format(str(i))\n # # #print(path)\n # # alltags.append(self.readfold(path))\n # # tags_5_15 = pd.concat(alltags)\n \n # # tag0_15 = tags_0_5.join(tags_5_15.set_index('faq_id'), on='faq_id',lsuffix='_5', rsuffix='_15', how='outer')\n # # tag0_15['all_pos_tag'] = tag0_15['all_pos_tag_5'] +tag0_15['all_pos_tag_15']\n # # tag0_15['turk_cnt'] = (tag0_15['turk_cnt_5'] +tag0_15['turk_cnt_15'])/2\n \n # # tags=tag0_15\n\n # # #================Build the belief table ================\n # # data_test = aa.queryfile\n # # test_tag = data_test.join(tags.set_index('faq_id'), on='faq_id', how='outer').replace(np.nan, 0, regex=True)\n # # test_tag_record = test_tag.to_dict('records')\n # # aa_to_user_idx={}\n # # fq_tag=[]\n # # tgt_in_aa = []\n # # for i in range(len( test_tag_record )):\n # # dr = test_tag_record[i]\n # # tgttext = dr['faqtext'] if 'faqtext' in dr else dr['faq_original']\n # # tgt_ids = aa.faqs.index(tgttext)\n # # tgt_in_aa.append(tgt_ids)\n # # aa_to_user_idx[tgt_ids] = i\n # # tag_cnt = [0]*len(aa.tag_w2i)\n\n # # turk_cnt = dr['turk_cnt']\n # # dr['all_pos_tag'] = [] if dr['all_pos_tag']== 0 else dr['all_pos_tag']\n # # while turk_cnt<3: \n # # dr['all_pos_tag'] += dr['taglist'] \n # # turk_cnt +=1\n # # print('for faq :{}, get tags from gold table {}'.format(dr['faq_id'], dr['taglist']))\n\n # # for tg in dr['all_pos_tag']:\n # # if tg in aa.tag_w2i:\n # # tag_cnt[ aa.tag_w2i[tg]] = min(3, tag_cnt[ aa.tag_w2i[tg]] +1)\n # # fq_tag.append(tag_cnt)\n # # fq_tag = np.array(fq_tag)/3\n # # goldtable = aa.gold_table[tgt_in_aa]\n\n\n # # self.aa_to_user_idx = aa_to_user_idx\n # # self.qtag_belief = self.lamda *fq_tag + (1- self.lamda )*goldtable\n\n\n" ]
[ [ "numpy.random.binomial" ] ]
harry418/mask-detection
[ "a1aca03c50329c60250ad70e0992398feb9a4ed5" ]
[ "mask_detection_train.py" ]
[ "# -*- coding: utf-8 -*-\n\"\"\"mask_detection.ipynb\n\nAutomatically generated by Colaboratory.\n\nOriginal file is located at\n https://colab.research.google.com/drive/1f4A35qAws13i5qKx86UPqL56rhzBPAOY\n\"\"\"\n\n# import the necessary packages\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.preprocessing.image import img_to_array\nfrom keras.preprocessing.image import load_img\nfrom keras.utils import to_categorical\nfrom sklearn.preprocessing import LabelBinarizer\nfrom sklearn.model_selection import train_test_split\nfrom keras.layers import Dense , Dropout ,Flatten , MaxPooling2D\nfrom imutils import paths\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\nfrom keras.models import Model\nimport random\n\n# importing MobileNet_v2 for higher accuracy\nfrom keras.applications import MobileNetV2\nmobile = MobileNetV2(input_shape=(224,224,3),include_top=False,weights='imagenet')\n\n#print(mobile.summary())\n\n# layer should not be change\nfor layer in mobile.layers:\n layer.trainable = False\n\n\n# Make output layer of mobilenet\nop_layer = mobile.output\nop_layer = MaxPooling2D(pool_size=(6,6))(op_layer)\nop_layer = Flatten()(op_layer)\nop_layer = Dense(128,activation='relu')(op_layer)\nop_layer = Dropout((0.5))(op_layer)\nop_layer = Dense(2,activation= 'softmax')(op_layer)\n\n# Define model input and output\nmodel = Model(inputs = mobile.input , outputs = op_layer)\n\n# compiling model\nmodel.compile(optimizer = 'adam', \n loss = 'binary_crossentropy', \n metrics = ['acc'])\n\n# save model for future use\nmodel.save('mask_model')\n\n# path to dataset\ndataset = 'dataset'\n\n# initialize the initial learning rate, number of epochs to train for,\n# and batch size\nEPOCHS = 50\nBS = 32\n\n# grab the list of images in our dataset directory, then initialize\n# the list of data (i.e., images) and class images\nprint(\"[INFO] loading images...\")\nimagePaths = list(paths.list_images(dataset))\nrandom.seed(42)\nrandom.shuffle(imagePaths)\ndata = []\nlabels = []\n# loop over the image paths\nfor imagePath in imagePaths:\n\n\t# extract the class label from the filename\n\tlabel = imagePath.split(os.path.sep)[-2]\n\t# load the input image (150x150) and preprocess it\n\timage = load_img(imagePath, target_size=(224, 224))\n\timage = img_to_array(image)/255.\n\t\n \n\t#image = preprocess_input(image)\n\n\t# update the data and labels lists, respectively\n\tdata.append(image)\n\tlabels.append(label)\n\n# convert the data and labels to NumPy arrays\ndata = np.array(data, dtype=\"float32\")\nlabels = np.array(labels)\n\n# perform one-hot encoding on the labels\nlb = LabelBinarizer()\nlabels = lb.fit_transform(labels)\nlabel_value = to_categorical(labels)\n\n# partition the data into training and testing splits using 75% of\n# the data for training and the remaining 25% for testing\n(trainX, testX, trainY, testY) = train_test_split(data, label_value,\n\ttest_size=0.20, stratify=labels, random_state=42,shuffle = True)\n\naug_train = ImageDataGenerator(rescale= 1.0/255.,\n\trotation_range=20,\n\tzoom_range=0.15,\n\twidth_shift_range=0.2,\n\theight_shift_range=0.2,\n\tshear_range=0.15,\n\thorizontal_flip=True,\n\tfill_mode=\"nearest\")\n\naug_test = ImageDataGenerator(rescale= 1.0/255.)\n\nhist = model.fit_generator(steps_per_epoch=len(trainX)//BS,\n generator=aug_train.flow(trainX, trainY, batch_size=BS),\n validation_data= (testX, testY),\n validation_steps=len(testX)//BS,\n epochs=EPOCHS)\n\n# print accuracy and loss graph\nimport matplotlib.pyplot as plt\nplt.plot(hist.history[\"acc\"])\nplt.plot(hist.history['val_acc'])\nplt.plot(hist.history['loss'])\nplt.plot(hist.history['val_loss'])\nplt.title(\"model accuracy\")\nplt.ylabel(\"Accuracy\")\nplt.xlabel(\"Epoch\")\nplt.legend([\"Accuracy\",\"Validation Accuracy\",\"loss\",\"Validation Loss\"])\nplt.show()\n\n# save model weights\nmodel.save_weights('/content/drive/My Drive/Colab Notebooks/mask_model_weights.h5')\n\n#from keras.models import load_model\n#model = load_model('/content/drive/My Drive/Colab Notebooks/mask_model',custom_objects=None, compile=True)\n\n# printing confusion matrix\nfrom sklearn.metrics import confusion_matrix\ny_pred = model.predict(testX)\ny_p = np.argmax(y_pred,axis=1)\ny_true = np.argmax(testY,axis=1)\nprint(confusion_matrix(y_true,y_p))\n\n" ]
[ [ "numpy.array", "sklearn.metrics.confusion_matrix", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.plot", "matplotlib.pyplot.title", "matplotlib.pyplot.legend", "numpy.argmax", "matplotlib.pyplot.ylabel", "sklearn.model_selection.train_test_split", "matplotlib.pyplot.show", "sklearn.preprocessing.LabelBinarizer" ] ]
bknaepen/scipy
[ "c5db5e291624c4d5ef4960ed7da3d4a413d8bcb1" ]
[ "scipy/linalg/basic.py" ]
[ "#\n# Author: Pearu Peterson, March 2002\n#\n# w/ additions by Travis Oliphant, March 2002\n# and Jake Vanderplas, August 2012\n\nfrom warnings import warn\nimport numpy as np\nfrom numpy import atleast_1d, atleast_2d\nfrom .flinalg import get_flinalg_funcs\nfrom .lapack import get_lapack_funcs, _compute_lwork\nfrom .misc import LinAlgError, _datacopied, LinAlgWarning\nfrom .decomp import _asarray_validated\nfrom . import decomp, decomp_svd\nfrom ._solve_toeplitz import levinson\n\n__all__ = ['solve', 'solve_triangular', 'solveh_banded', 'solve_banded',\n 'solve_toeplitz', 'solve_circulant', 'inv', 'det', 'lstsq',\n 'pinv', 'pinv2', 'pinvh', 'matrix_balance']\n\n\n# Linear equations\ndef _solve_check(n, info, lamch=None, rcond=None):\n \"\"\" Check arguments during the different steps of the solution phase \"\"\"\n if info < 0:\n raise ValueError('LAPACK reported an illegal value in {}-th argument'\n '.'.format(-info))\n elif 0 < info:\n raise LinAlgError('Matrix is singular.')\n\n if lamch is None:\n return\n E = lamch('E')\n if rcond < E:\n warn('Ill-conditioned matrix (rcond={:.6g}): '\n 'result may not be accurate.'.format(rcond),\n LinAlgWarning, stacklevel=3)\n\n\ndef solve(a, b, sym_pos=False, lower=False, overwrite_a=False,\n overwrite_b=False, debug=None, check_finite=True, assume_a='gen',\n transposed=False):\n \"\"\"\n Solves the linear equation set ``a * x = b`` for the unknown ``x``\n for square ``a`` matrix.\n\n If the data matrix is known to be a particular type then supplying the\n corresponding string to ``assume_a`` key chooses the dedicated solver.\n The available options are\n\n =================== ========\n generic matrix 'gen'\n symmetric 'sym'\n hermitian 'her'\n positive definite 'pos'\n =================== ========\n\n If omitted, ``'gen'`` is the default structure.\n\n The datatype of the arrays define which solver is called regardless\n of the values. In other words, even when the complex array entries have\n precisely zero imaginary parts, the complex solver will be called based\n on the data type of the array.\n\n Parameters\n ----------\n a : (N, N) array_like\n Square input data\n b : (N, NRHS) array_like\n Input data for the right hand side.\n sym_pos : bool, optional\n Assume `a` is symmetric and positive definite. This key is deprecated\n and assume_a = 'pos' keyword is recommended instead. The functionality\n is the same. It will be removed in the future.\n lower : bool, optional\n If True, only the data contained in the lower triangle of `a`. Default\n is to use upper triangle. (ignored for ``'gen'``)\n overwrite_a : bool, optional\n Allow overwriting data in `a` (may enhance performance).\n Default is False.\n overwrite_b : bool, optional\n Allow overwriting data in `b` (may enhance performance).\n Default is False.\n check_finite : bool, optional\n Whether to check that the input matrices contain only finite numbers.\n Disabling may give a performance gain, but may result in problems\n (crashes, non-termination) if the inputs do contain infinities or NaNs.\n assume_a : str, optional\n Valid entries are explained above.\n transposed: bool, optional\n If True, ``a^T x = b`` for real matrices, raises `NotImplementedError`\n for complex matrices (only for True).\n\n Returns\n -------\n x : (N, NRHS) ndarray\n The solution array.\n\n Raises\n ------\n ValueError\n If size mismatches detected or input a is not square.\n LinAlgError\n If the matrix is singular.\n LinAlgWarning\n If an ill-conditioned input a is detected.\n NotImplementedError\n If transposed is True and input a is a complex matrix.\n\n Examples\n --------\n Given `a` and `b`, solve for `x`:\n\n >>> a = np.array([[3, 2, 0], [1, -1, 0], [0, 5, 1]])\n >>> b = np.array([2, 4, -1])\n >>> from scipy import linalg\n >>> x = linalg.solve(a, b)\n >>> x\n array([ 2., -2., 9.])\n >>> np.dot(a, x) == b\n array([ True, True, True], dtype=bool)\n\n Notes\n -----\n If the input b matrix is a 1-D array with N elements, when supplied\n together with an NxN input a, it is assumed as a valid column vector\n despite the apparent size mismatch. This is compatible with the\n numpy.dot() behavior and the returned result is still 1-D array.\n\n The generic, symmetric, hermitian and positive definite solutions are\n obtained via calling ?GESV, ?SYSV, ?HESV, and ?POSV routines of\n LAPACK respectively.\n \"\"\"\n # Flags for 1-D or N-D right-hand side\n b_is_1D = False\n\n a1 = atleast_2d(_asarray_validated(a, check_finite=check_finite))\n b1 = atleast_1d(_asarray_validated(b, check_finite=check_finite))\n n = a1.shape[0]\n\n overwrite_a = overwrite_a or _datacopied(a1, a)\n overwrite_b = overwrite_b or _datacopied(b1, b)\n\n if a1.shape[0] != a1.shape[1]:\n raise ValueError('Input a needs to be a square matrix.')\n\n if n != b1.shape[0]:\n # Last chance to catch 1x1 scalar a and 1-D b arrays\n if not (n == 1 and b1.size != 0):\n raise ValueError('Input b has to have same number of rows as '\n 'input a')\n\n # accommodate empty arrays\n if b1.size == 0:\n return np.asfortranarray(b1.copy())\n\n # regularize 1-D b arrays to 2D\n if b1.ndim == 1:\n if n == 1:\n b1 = b1[None, :]\n else:\n b1 = b1[:, None]\n b_is_1D = True\n\n # Backwards compatibility - old keyword.\n if sym_pos:\n assume_a = 'pos'\n\n if assume_a not in ('gen', 'sym', 'her', 'pos'):\n raise ValueError('{} is not a recognized matrix structure'\n ''.format(assume_a))\n\n # Deprecate keyword \"debug\"\n if debug is not None:\n warn('Use of the \"debug\" keyword is deprecated '\n 'and this keyword will be removed in future '\n 'versions of SciPy.', DeprecationWarning, stacklevel=2)\n\n # Get the correct lamch function.\n # The LAMCH functions only exists for S and D\n # So for complex values we have to convert to real/double.\n if a1.dtype.char in 'fF': # single precision\n lamch = get_lapack_funcs('lamch', dtype='f')\n else:\n lamch = get_lapack_funcs('lamch', dtype='d')\n\n # Currently we do not have the other forms of the norm calculators\n # lansy, lanpo, lanhe.\n # However, in any case they only reduce computations slightly...\n lange = get_lapack_funcs('lange', (a1,))\n\n # Since the I-norm and 1-norm are the same for symmetric matrices\n # we can collect them all in this one call\n # Note however, that when issuing 'gen' and form!='none', then\n # the I-norm should be used\n if transposed:\n trans = 1\n norm = 'I'\n if np.iscomplexobj(a1):\n raise NotImplementedError('scipy.linalg.solve can currently '\n 'not solve a^T x = b or a^H x = b '\n 'for complex matrices.')\n else:\n trans = 0\n norm = '1'\n\n anorm = lange(norm, a1)\n\n # Generalized case 'gesv'\n if assume_a == 'gen':\n gecon, getrf, getrs = get_lapack_funcs(('gecon', 'getrf', 'getrs'),\n (a1, b1))\n lu, ipvt, info = getrf(a1, overwrite_a=overwrite_a)\n _solve_check(n, info)\n x, info = getrs(lu, ipvt, b1,\n trans=trans, overwrite_b=overwrite_b)\n _solve_check(n, info)\n rcond, info = gecon(lu, anorm, norm=norm)\n # Hermitian case 'hesv'\n elif assume_a == 'her':\n hecon, hesv, hesv_lw = get_lapack_funcs(('hecon', 'hesv',\n 'hesv_lwork'), (a1, b1))\n lwork = _compute_lwork(hesv_lw, n, lower)\n lu, ipvt, x, info = hesv(a1, b1, lwork=lwork,\n lower=lower,\n overwrite_a=overwrite_a,\n overwrite_b=overwrite_b)\n _solve_check(n, info)\n rcond, info = hecon(lu, ipvt, anorm)\n # Symmetric case 'sysv'\n elif assume_a == 'sym':\n sycon, sysv, sysv_lw = get_lapack_funcs(('sycon', 'sysv',\n 'sysv_lwork'), (a1, b1))\n lwork = _compute_lwork(sysv_lw, n, lower)\n lu, ipvt, x, info = sysv(a1, b1, lwork=lwork,\n lower=lower,\n overwrite_a=overwrite_a,\n overwrite_b=overwrite_b)\n _solve_check(n, info)\n rcond, info = sycon(lu, ipvt, anorm)\n # Positive definite case 'posv'\n else:\n pocon, posv = get_lapack_funcs(('pocon', 'posv'),\n (a1, b1))\n lu, x, info = posv(a1, b1, lower=lower,\n overwrite_a=overwrite_a,\n overwrite_b=overwrite_b)\n _solve_check(n, info)\n rcond, info = pocon(lu, anorm)\n\n _solve_check(n, info, lamch, rcond)\n\n if b_is_1D:\n x = x.ravel()\n\n return x\n\n\ndef solve_triangular(a, b, trans=0, lower=False, unit_diagonal=False,\n overwrite_b=False, debug=None, check_finite=True):\n \"\"\"\n Solve the equation `a x = b` for `x`, assuming a is a triangular matrix.\n\n Parameters\n ----------\n a : (M, M) array_like\n A triangular matrix\n b : (M,) or (M, N) array_like\n Right-hand side matrix in `a x = b`\n lower : bool, optional\n Use only data contained in the lower triangle of `a`.\n Default is to use upper triangle.\n trans : {0, 1, 2, 'N', 'T', 'C'}, optional\n Type of system to solve:\n\n ======== =========\n trans system\n ======== =========\n 0 or 'N' a x = b\n 1 or 'T' a^T x = b\n 2 or 'C' a^H x = b\n ======== =========\n unit_diagonal : bool, optional\n If True, diagonal elements of `a` are assumed to be 1 and\n will not be referenced.\n overwrite_b : bool, optional\n Allow overwriting data in `b` (may enhance performance)\n check_finite : bool, optional\n Whether to check that the input matrices contain only finite numbers.\n Disabling may give a performance gain, but may result in problems\n (crashes, non-termination) if the inputs do contain infinities or NaNs.\n\n Returns\n -------\n x : (M,) or (M, N) ndarray\n Solution to the system `a x = b`. Shape of return matches `b`.\n\n Raises\n ------\n LinAlgError\n If `a` is singular\n\n Notes\n -----\n .. versionadded:: 0.9.0\n\n Examples\n --------\n Solve the lower triangular system a x = b, where::\n\n [3 0 0 0] [4]\n a = [2 1 0 0] b = [2]\n [1 0 1 0] [4]\n [1 1 1 1] [2]\n\n >>> from scipy.linalg import solve_triangular\n >>> a = np.array([[3, 0, 0, 0], [2, 1, 0, 0], [1, 0, 1, 0], [1, 1, 1, 1]])\n >>> b = np.array([4, 2, 4, 2])\n >>> x = solve_triangular(a, b, lower=True)\n >>> x\n array([ 1.33333333, -0.66666667, 2.66666667, -1.33333333])\n >>> a.dot(x) # Check the result\n array([ 4., 2., 4., 2.])\n\n \"\"\"\n\n # Deprecate keyword \"debug\"\n if debug is not None:\n warn('Use of the \"debug\" keyword is deprecated '\n 'and this keyword will be removed in the future '\n 'versions of SciPy.', DeprecationWarning, stacklevel=2)\n\n a1 = _asarray_validated(a, check_finite=check_finite)\n b1 = _asarray_validated(b, check_finite=check_finite)\n if len(a1.shape) != 2 or a1.shape[0] != a1.shape[1]:\n raise ValueError('expected square matrix')\n if a1.shape[0] != b1.shape[0]:\n raise ValueError('shapes of a {} and b {} are incompatible'\n .format(a1.shape, b1.shape))\n overwrite_b = overwrite_b or _datacopied(b1, b)\n if debug:\n print('solve:overwrite_b=', overwrite_b)\n trans = {'N': 0, 'T': 1, 'C': 2}.get(trans, trans)\n trtrs, = get_lapack_funcs(('trtrs',), (a1, b1))\n if a1.flags.f_contiguous or trans == 2:\n x, info = trtrs(a1, b1, overwrite_b=overwrite_b, lower=lower,\n trans=trans, unitdiag=unit_diagonal)\n else:\n # transposed system is solved since trtrs expects Fortran ordering\n x, info = trtrs(a1.T, b1, overwrite_b=overwrite_b, lower=not lower,\n trans=not trans, unitdiag=unit_diagonal)\n\n if info == 0:\n return x\n if info > 0:\n raise LinAlgError(\"singular matrix: resolution failed at diagonal %d\" %\n (info-1))\n raise ValueError('illegal value in %dth argument of internal trtrs' %\n (-info))\n\n\ndef solve_banded(l_and_u, ab, b, overwrite_ab=False, overwrite_b=False,\n debug=None, check_finite=True):\n \"\"\"\n Solve the equation a x = b for x, assuming a is banded matrix.\n\n The matrix a is stored in `ab` using the matrix diagonal ordered form::\n\n ab[u + i - j, j] == a[i,j]\n\n Example of `ab` (shape of a is (6,6), `u` =1, `l` =2)::\n\n * a01 a12 a23 a34 a45\n a00 a11 a22 a33 a44 a55\n a10 a21 a32 a43 a54 *\n a20 a31 a42 a53 * *\n\n Parameters\n ----------\n (l, u) : (integer, integer)\n Number of non-zero lower and upper diagonals\n ab : (`l` + `u` + 1, M) array_like\n Banded matrix\n b : (M,) or (M, K) array_like\n Right-hand side\n overwrite_ab : bool, optional\n Discard data in `ab` (may enhance performance)\n overwrite_b : bool, optional\n Discard data in `b` (may enhance performance)\n check_finite : bool, optional\n Whether to check that the input matrices contain only finite numbers.\n Disabling may give a performance gain, but may result in problems\n (crashes, non-termination) if the inputs do contain infinities or NaNs.\n\n Returns\n -------\n x : (M,) or (M, K) ndarray\n The solution to the system a x = b. Returned shape depends on the\n shape of `b`.\n\n Examples\n --------\n Solve the banded system a x = b, where::\n\n [5 2 -1 0 0] [0]\n [1 4 2 -1 0] [1]\n a = [0 1 3 2 -1] b = [2]\n [0 0 1 2 2] [2]\n [0 0 0 1 1] [3]\n\n There is one nonzero diagonal below the main diagonal (l = 1), and\n two above (u = 2). The diagonal banded form of the matrix is::\n\n [* * -1 -1 -1]\n ab = [* 2 2 2 2]\n [5 4 3 2 1]\n [1 1 1 1 *]\n\n >>> from scipy.linalg import solve_banded\n >>> ab = np.array([[0, 0, -1, -1, -1],\n ... [0, 2, 2, 2, 2],\n ... [5, 4, 3, 2, 1],\n ... [1, 1, 1, 1, 0]])\n >>> b = np.array([0, 1, 2, 2, 3])\n >>> x = solve_banded((1, 2), ab, b)\n >>> x\n array([-2.37288136, 3.93220339, -4. , 4.3559322 , -1.3559322 ])\n\n \"\"\"\n\n # Deprecate keyword \"debug\"\n if debug is not None:\n warn('Use of the \"debug\" keyword is deprecated '\n 'and this keyword will be removed in the future '\n 'versions of SciPy.', DeprecationWarning, stacklevel=2)\n\n a1 = _asarray_validated(ab, check_finite=check_finite, as_inexact=True)\n b1 = _asarray_validated(b, check_finite=check_finite, as_inexact=True)\n # Validate shapes.\n if a1.shape[-1] != b1.shape[0]:\n raise ValueError(\"shapes of ab and b are not compatible.\")\n (nlower, nupper) = l_and_u\n if nlower + nupper + 1 != a1.shape[0]:\n raise ValueError(\"invalid values for the number of lower and upper \"\n \"diagonals: l+u+1 (%d) does not equal ab.shape[0] \"\n \"(%d)\" % (nlower + nupper + 1, ab.shape[0]))\n\n overwrite_b = overwrite_b or _datacopied(b1, b)\n if a1.shape[-1] == 1:\n b2 = np.array(b1, copy=(not overwrite_b))\n b2 /= a1[1, 0]\n return b2\n if nlower == nupper == 1:\n overwrite_ab = overwrite_ab or _datacopied(a1, ab)\n gtsv, = get_lapack_funcs(('gtsv',), (a1, b1))\n du = a1[0, 1:]\n d = a1[1, :]\n dl = a1[2, :-1]\n du2, d, du, x, info = gtsv(dl, d, du, b1, overwrite_ab, overwrite_ab,\n overwrite_ab, overwrite_b)\n else:\n gbsv, = get_lapack_funcs(('gbsv',), (a1, b1))\n a2 = np.zeros((2*nlower + nupper + 1, a1.shape[1]), dtype=gbsv.dtype)\n a2[nlower:, :] = a1\n lu, piv, x, info = gbsv(nlower, nupper, a2, b1, overwrite_ab=True,\n overwrite_b=overwrite_b)\n if info == 0:\n return x\n if info > 0:\n raise LinAlgError(\"singular matrix\")\n raise ValueError('illegal value in %d-th argument of internal '\n 'gbsv/gtsv' % -info)\n\n\ndef solveh_banded(ab, b, overwrite_ab=False, overwrite_b=False, lower=False,\n check_finite=True):\n \"\"\"\n Solve equation a x = b. a is Hermitian positive-definite banded matrix.\n\n The matrix a is stored in `ab` either in lower diagonal or upper\n diagonal ordered form:\n\n ab[u + i - j, j] == a[i,j] (if upper form; i <= j)\n ab[ i - j, j] == a[i,j] (if lower form; i >= j)\n\n Example of `ab` (shape of a is (6, 6), `u` =2)::\n\n upper form:\n * * a02 a13 a24 a35\n * a01 a12 a23 a34 a45\n a00 a11 a22 a33 a44 a55\n\n lower form:\n a00 a11 a22 a33 a44 a55\n a10 a21 a32 a43 a54 *\n a20 a31 a42 a53 * *\n\n Cells marked with * are not used.\n\n Parameters\n ----------\n ab : (`u` + 1, M) array_like\n Banded matrix\n b : (M,) or (M, K) array_like\n Right-hand side\n overwrite_ab : bool, optional\n Discard data in `ab` (may enhance performance)\n overwrite_b : bool, optional\n Discard data in `b` (may enhance performance)\n lower : bool, optional\n Is the matrix in the lower form. (Default is upper form)\n check_finite : bool, optional\n Whether to check that the input matrices contain only finite numbers.\n Disabling may give a performance gain, but may result in problems\n (crashes, non-termination) if the inputs do contain infinities or NaNs.\n\n Returns\n -------\n x : (M,) or (M, K) ndarray\n The solution to the system a x = b. Shape of return matches shape\n of `b`.\n\n Examples\n --------\n Solve the banded system A x = b, where::\n\n [ 4 2 -1 0 0 0] [1]\n [ 2 5 2 -1 0 0] [2]\n A = [-1 2 6 2 -1 0] b = [2]\n [ 0 -1 2 7 2 -1] [3]\n [ 0 0 -1 2 8 2] [3]\n [ 0 0 0 -1 2 9] [3]\n\n >>> from scipy.linalg import solveh_banded\n\n `ab` contains the main diagonal and the nonzero diagonals below the\n main diagonal. That is, we use the lower form:\n\n >>> ab = np.array([[ 4, 5, 6, 7, 8, 9],\n ... [ 2, 2, 2, 2, 2, 0],\n ... [-1, -1, -1, -1, 0, 0]])\n >>> b = np.array([1, 2, 2, 3, 3, 3])\n >>> x = solveh_banded(ab, b, lower=True)\n >>> x\n array([ 0.03431373, 0.45938375, 0.05602241, 0.47759104, 0.17577031,\n 0.34733894])\n\n\n Solve the Hermitian banded system H x = b, where::\n\n [ 8 2-1j 0 0 ] [ 1 ]\n H = [2+1j 5 1j 0 ] b = [1+1j]\n [ 0 -1j 9 -2-1j] [1-2j]\n [ 0 0 -2+1j 6 ] [ 0 ]\n\n In this example, we put the upper diagonals in the array `hb`:\n\n >>> hb = np.array([[0, 2-1j, 1j, -2-1j],\n ... [8, 5, 9, 6 ]])\n >>> b = np.array([1, 1+1j, 1-2j, 0])\n >>> x = solveh_banded(hb, b)\n >>> x\n array([ 0.07318536-0.02939412j, 0.11877624+0.17696461j,\n 0.10077984-0.23035393j, -0.00479904-0.09358128j])\n\n \"\"\"\n a1 = _asarray_validated(ab, check_finite=check_finite)\n b1 = _asarray_validated(b, check_finite=check_finite)\n # Validate shapes.\n if a1.shape[-1] != b1.shape[0]:\n raise ValueError(\"shapes of ab and b are not compatible.\")\n\n overwrite_b = overwrite_b or _datacopied(b1, b)\n overwrite_ab = overwrite_ab or _datacopied(a1, ab)\n\n if a1.shape[0] == 2:\n ptsv, = get_lapack_funcs(('ptsv',), (a1, b1))\n if lower:\n d = a1[0, :].real\n e = a1[1, :-1]\n else:\n d = a1[1, :].real\n e = a1[0, 1:].conj()\n d, du, x, info = ptsv(d, e, b1, overwrite_ab, overwrite_ab,\n overwrite_b)\n else:\n pbsv, = get_lapack_funcs(('pbsv',), (a1, b1))\n c, x, info = pbsv(a1, b1, lower=lower, overwrite_ab=overwrite_ab,\n overwrite_b=overwrite_b)\n if info > 0:\n raise LinAlgError(\"%dth leading minor not positive definite\" % info)\n if info < 0:\n raise ValueError('illegal value in %dth argument of internal '\n 'pbsv' % -info)\n return x\n\n\ndef solve_toeplitz(c_or_cr, b, check_finite=True):\n \"\"\"Solve a Toeplitz system using Levinson Recursion\n\n The Toeplitz matrix has constant diagonals, with c as its first column\n and r as its first row. If r is not given, ``r == conjugate(c)`` is\n assumed.\n\n Parameters\n ----------\n c_or_cr : array_like or tuple of (array_like, array_like)\n The vector ``c``, or a tuple of arrays (``c``, ``r``). Whatever the\n actual shape of ``c``, it will be converted to a 1-D array. If not\n supplied, ``r = conjugate(c)`` is assumed; in this case, if c[0] is\n real, the Toeplitz matrix is Hermitian. r[0] is ignored; the first row\n of the Toeplitz matrix is ``[c[0], r[1:]]``. Whatever the actual shape\n of ``r``, it will be converted to a 1-D array.\n b : (M,) or (M, K) array_like\n Right-hand side in ``T x = b``.\n check_finite : bool, optional\n Whether to check that the input matrices contain only finite numbers.\n Disabling may give a performance gain, but may result in problems\n (result entirely NaNs) if the inputs do contain infinities or NaNs.\n\n Returns\n -------\n x : (M,) or (M, K) ndarray\n The solution to the system ``T x = b``. Shape of return matches shape\n of `b`.\n\n See Also\n --------\n toeplitz : Toeplitz matrix\n\n Notes\n -----\n The solution is computed using Levinson-Durbin recursion, which is faster\n than generic least-squares methods, but can be less numerically stable.\n\n Examples\n --------\n Solve the Toeplitz system T x = b, where::\n\n [ 1 -1 -2 -3] [1]\n T = [ 3 1 -1 -2] b = [2]\n [ 6 3 1 -1] [2]\n [10 6 3 1] [5]\n\n To specify the Toeplitz matrix, only the first column and the first\n row are needed.\n\n >>> c = np.array([1, 3, 6, 10]) # First column of T\n >>> r = np.array([1, -1, -2, -3]) # First row of T\n >>> b = np.array([1, 2, 2, 5])\n\n >>> from scipy.linalg import solve_toeplitz, toeplitz\n >>> x = solve_toeplitz((c, r), b)\n >>> x\n array([ 1.66666667, -1. , -2.66666667, 2.33333333])\n\n Check the result by creating the full Toeplitz matrix and\n multiplying it by `x`. We should get `b`.\n\n >>> T = toeplitz(c, r)\n >>> T.dot(x)\n array([ 1., 2., 2., 5.])\n\n \"\"\"\n # If numerical stability of this algorithm is a problem, a future\n # developer might consider implementing other O(N^2) Toeplitz solvers,\n # such as GKO (https://www.jstor.org/stable/2153371) or Bareiss.\n if isinstance(c_or_cr, tuple):\n c, r = c_or_cr\n c = _asarray_validated(c, check_finite=check_finite).ravel()\n r = _asarray_validated(r, check_finite=check_finite).ravel()\n else:\n c = _asarray_validated(c_or_cr, check_finite=check_finite).ravel()\n r = c.conjugate()\n\n # Form a 1-D array of values to be used in the matrix, containing a reversed\n # copy of r[1:], followed by c.\n vals = np.concatenate((r[-1:0:-1], c))\n if b is None:\n raise ValueError('illegal value, `b` is a required argument')\n\n b = _asarray_validated(b)\n if vals.shape[0] != (2*b.shape[0] - 1):\n raise ValueError('incompatible dimensions')\n if np.iscomplexobj(vals) or np.iscomplexobj(b):\n vals = np.asarray(vals, dtype=np.complex128, order='c')\n b = np.asarray(b, dtype=np.complex128)\n else:\n vals = np.asarray(vals, dtype=np.double, order='c')\n b = np.asarray(b, dtype=np.double)\n\n if b.ndim == 1:\n x, _ = levinson(vals, np.ascontiguousarray(b))\n else:\n b_shape = b.shape\n b = b.reshape(b.shape[0], -1)\n x = np.column_stack([levinson(vals, np.ascontiguousarray(b[:, i]))[0]\n for i in range(b.shape[1])])\n x = x.reshape(*b_shape)\n\n return x\n\n\ndef _get_axis_len(aname, a, axis):\n ax = axis\n if ax < 0:\n ax += a.ndim\n if 0 <= ax < a.ndim:\n return a.shape[ax]\n raise ValueError(\"'%saxis' entry is out of bounds\" % (aname,))\n\n\ndef solve_circulant(c, b, singular='raise', tol=None,\n caxis=-1, baxis=0, outaxis=0):\n \"\"\"Solve C x = b for x, where C is a circulant matrix.\n\n `C` is the circulant matrix associated with the vector `c`.\n\n The system is solved by doing division in Fourier space. The\n calculation is::\n\n x = ifft(fft(b) / fft(c))\n\n where `fft` and `ifft` are the fast Fourier transform and its inverse,\n respectively. For a large vector `c`, this is *much* faster than\n solving the system with the full circulant matrix.\n\n Parameters\n ----------\n c : array_like\n The coefficients of the circulant matrix.\n b : array_like\n Right-hand side matrix in ``a x = b``.\n singular : str, optional\n This argument controls how a near singular circulant matrix is\n handled. If `singular` is \"raise\" and the circulant matrix is\n near singular, a `LinAlgError` is raised. If `singular` is\n \"lstsq\", the least squares solution is returned. Default is \"raise\".\n tol : float, optional\n If any eigenvalue of the circulant matrix has an absolute value\n that is less than or equal to `tol`, the matrix is considered to be\n near singular. If not given, `tol` is set to::\n\n tol = abs_eigs.max() * abs_eigs.size * np.finfo(np.float64).eps\n\n where `abs_eigs` is the array of absolute values of the eigenvalues\n of the circulant matrix.\n caxis : int\n When `c` has dimension greater than 1, it is viewed as a collection\n of circulant vectors. In this case, `caxis` is the axis of `c` that\n holds the vectors of circulant coefficients.\n baxis : int\n When `b` has dimension greater than 1, it is viewed as a collection\n of vectors. In this case, `baxis` is the axis of `b` that holds the\n right-hand side vectors.\n outaxis : int\n When `c` or `b` are multidimensional, the value returned by\n `solve_circulant` is multidimensional. In this case, `outaxis` is\n the axis of the result that holds the solution vectors.\n\n Returns\n -------\n x : ndarray\n Solution to the system ``C x = b``.\n\n Raises\n ------\n LinAlgError\n If the circulant matrix associated with `c` is near singular.\n\n See Also\n --------\n circulant : circulant matrix\n\n Notes\n -----\n For a 1-D vector `c` with length `m`, and an array `b`\n with shape ``(m, ...)``,\n\n solve_circulant(c, b)\n\n returns the same result as\n\n solve(circulant(c), b)\n\n where `solve` and `circulant` are from `scipy.linalg`.\n\n .. versionadded:: 0.16.0\n\n Examples\n --------\n >>> from scipy.linalg import solve_circulant, solve, circulant, lstsq\n\n >>> c = np.array([2, 2, 4])\n >>> b = np.array([1, 2, 3])\n >>> solve_circulant(c, b)\n array([ 0.75, -0.25, 0.25])\n\n Compare that result to solving the system with `scipy.linalg.solve`:\n\n >>> solve(circulant(c), b)\n array([ 0.75, -0.25, 0.25])\n\n A singular example:\n\n >>> c = np.array([1, 1, 0, 0])\n >>> b = np.array([1, 2, 3, 4])\n\n Calling ``solve_circulant(c, b)`` will raise a `LinAlgError`. For the\n least square solution, use the option ``singular='lstsq'``:\n\n >>> solve_circulant(c, b, singular='lstsq')\n array([ 0.25, 1.25, 2.25, 1.25])\n\n Compare to `scipy.linalg.lstsq`:\n\n >>> x, resid, rnk, s = lstsq(circulant(c), b)\n >>> x\n array([ 0.25, 1.25, 2.25, 1.25])\n\n A broadcasting example:\n\n Suppose we have the vectors of two circulant matrices stored in an array\n with shape (2, 5), and three `b` vectors stored in an array with shape\n (3, 5). For example,\n\n >>> c = np.array([[1.5, 2, 3, 0, 0], [1, 1, 4, 3, 2]])\n >>> b = np.arange(15).reshape(-1, 5)\n\n We want to solve all combinations of circulant matrices and `b` vectors,\n with the result stored in an array with shape (2, 3, 5). When we\n disregard the axes of `c` and `b` that hold the vectors of coefficients,\n the shapes of the collections are (2,) and (3,), respectively, which are\n not compatible for broadcasting. To have a broadcast result with shape\n (2, 3), we add a trivial dimension to `c`: ``c[:, np.newaxis, :]`` has\n shape (2, 1, 5). The last dimension holds the coefficients of the\n circulant matrices, so when we call `solve_circulant`, we can use the\n default ``caxis=-1``. The coefficients of the `b` vectors are in the last\n dimension of the array `b`, so we use ``baxis=-1``. If we use the\n default `outaxis`, the result will have shape (5, 2, 3), so we'll use\n ``outaxis=-1`` to put the solution vectors in the last dimension.\n\n >>> x = solve_circulant(c[:, np.newaxis, :], b, baxis=-1, outaxis=-1)\n >>> x.shape\n (2, 3, 5)\n >>> np.set_printoptions(precision=3) # For compact output of numbers.\n >>> x\n array([[[-0.118, 0.22 , 1.277, -0.142, 0.302],\n [ 0.651, 0.989, 2.046, 0.627, 1.072],\n [ 1.42 , 1.758, 2.816, 1.396, 1.841]],\n [[ 0.401, 0.304, 0.694, -0.867, 0.377],\n [ 0.856, 0.758, 1.149, -0.412, 0.831],\n [ 1.31 , 1.213, 1.603, 0.042, 1.286]]])\n\n Check by solving one pair of `c` and `b` vectors (cf. ``x[1, 1, :]``):\n\n >>> solve_circulant(c[1], b[1, :])\n array([ 0.856, 0.758, 1.149, -0.412, 0.831])\n\n \"\"\"\n c = np.atleast_1d(c)\n nc = _get_axis_len(\"c\", c, caxis)\n b = np.atleast_1d(b)\n nb = _get_axis_len(\"b\", b, baxis)\n if nc != nb:\n raise ValueError('Shapes of c {} and b {} are incompatible'\n .format(c.shape, b.shape))\n\n fc = np.fft.fft(np.rollaxis(c, caxis, c.ndim), axis=-1)\n abs_fc = np.abs(fc)\n if tol is None:\n # This is the same tolerance as used in np.linalg.matrix_rank.\n tol = abs_fc.max(axis=-1) * nc * np.finfo(np.float64).eps\n if tol.shape != ():\n tol.shape = tol.shape + (1,)\n else:\n tol = np.atleast_1d(tol)\n\n near_zeros = abs_fc <= tol\n is_near_singular = np.any(near_zeros)\n if is_near_singular:\n if singular == 'raise':\n raise LinAlgError(\"near singular circulant matrix.\")\n else:\n # Replace the small values with 1 to avoid errors in the\n # division fb/fc below.\n fc[near_zeros] = 1\n\n fb = np.fft.fft(np.rollaxis(b, baxis, b.ndim), axis=-1)\n\n q = fb / fc\n\n if is_near_singular:\n # `near_zeros` is a boolean array, same shape as `c`, that is\n # True where `fc` is (near) zero. `q` is the broadcasted result\n # of fb / fc, so to set the values of `q` to 0 where `fc` is near\n # zero, we use a mask that is the broadcast result of an array\n # of True values shaped like `b` with `near_zeros`.\n mask = np.ones_like(b, dtype=bool) & near_zeros\n q[mask] = 0\n\n x = np.fft.ifft(q, axis=-1)\n if not (np.iscomplexobj(c) or np.iscomplexobj(b)):\n x = x.real\n if outaxis != -1:\n x = np.rollaxis(x, -1, outaxis)\n return x\n\n\n# matrix inversion\ndef inv(a, overwrite_a=False, check_finite=True):\n \"\"\"\n Compute the inverse of a matrix.\n\n Parameters\n ----------\n a : array_like\n Square matrix to be inverted.\n overwrite_a : bool, optional\n Discard data in `a` (may improve performance). Default is False.\n check_finite : bool, optional\n Whether to check that the input matrix contains only finite numbers.\n Disabling may give a performance gain, but may result in problems\n (crashes, non-termination) if the inputs do contain infinities or NaNs.\n\n Returns\n -------\n ainv : ndarray\n Inverse of the matrix `a`.\n\n Raises\n ------\n LinAlgError\n If `a` is singular.\n ValueError\n If `a` is not square, or not 2D.\n\n Examples\n --------\n >>> from scipy import linalg\n >>> a = np.array([[1., 2.], [3., 4.]])\n >>> linalg.inv(a)\n array([[-2. , 1. ],\n [ 1.5, -0.5]])\n >>> np.dot(a, linalg.inv(a))\n array([[ 1., 0.],\n [ 0., 1.]])\n\n \"\"\"\n a1 = _asarray_validated(a, check_finite=check_finite)\n if len(a1.shape) != 2 or a1.shape[0] != a1.shape[1]:\n raise ValueError('expected square matrix')\n overwrite_a = overwrite_a or _datacopied(a1, a)\n # XXX: I found no advantage or disadvantage of using finv.\n# finv, = get_flinalg_funcs(('inv',),(a1,))\n# if finv is not None:\n# a_inv,info = finv(a1,overwrite_a=overwrite_a)\n# if info==0:\n# return a_inv\n# if info>0: raise LinAlgError, \"singular matrix\"\n# if info<0: raise ValueError('illegal value in %d-th argument of '\n# 'internal inv.getrf|getri'%(-info))\n getrf, getri, getri_lwork = get_lapack_funcs(('getrf', 'getri',\n 'getri_lwork'),\n (a1,))\n lu, piv, info = getrf(a1, overwrite_a=overwrite_a)\n if info == 0:\n lwork = _compute_lwork(getri_lwork, a1.shape[0])\n\n # XXX: the following line fixes curious SEGFAULT when\n # benchmarking 500x500 matrix inverse. This seems to\n # be a bug in LAPACK ?getri routine because if lwork is\n # minimal (when using lwork[0] instead of lwork[1]) then\n # all tests pass. Further investigation is required if\n # more such SEGFAULTs occur.\n lwork = int(1.01 * lwork)\n inv_a, info = getri(lu, piv, lwork=lwork, overwrite_lu=1)\n if info > 0:\n raise LinAlgError(\"singular matrix\")\n if info < 0:\n raise ValueError('illegal value in %d-th argument of internal '\n 'getrf|getri' % -info)\n return inv_a\n\n\n# Determinant\n\ndef det(a, overwrite_a=False, check_finite=True):\n \"\"\"\n Compute the determinant of a matrix\n\n The determinant of a square matrix is a value derived arithmetically\n from the coefficients of the matrix.\n\n The determinant for a 3x3 matrix, for example, is computed as follows::\n\n a b c\n d e f = A\n g h i\n\n det(A) = a*e*i + b*f*g + c*d*h - c*e*g - b*d*i - a*f*h\n\n Parameters\n ----------\n a : (M, M) array_like\n A square matrix.\n overwrite_a : bool, optional\n Allow overwriting data in a (may enhance performance).\n check_finite : bool, optional\n Whether to check that the input matrix contains only finite numbers.\n Disabling may give a performance gain, but may result in problems\n (crashes, non-termination) if the inputs do contain infinities or NaNs.\n\n Returns\n -------\n det : float or complex\n Determinant of `a`.\n\n Notes\n -----\n The determinant is computed via LU factorization, LAPACK routine z/dgetrf.\n\n Examples\n --------\n >>> from scipy import linalg\n >>> a = np.array([[1,2,3], [4,5,6], [7,8,9]])\n >>> linalg.det(a)\n 0.0\n >>> a = np.array([[0,2,3], [4,5,6], [7,8,9]])\n >>> linalg.det(a)\n 3.0\n\n \"\"\"\n a1 = _asarray_validated(a, check_finite=check_finite)\n if len(a1.shape) != 2 or a1.shape[0] != a1.shape[1]:\n raise ValueError('expected square matrix')\n overwrite_a = overwrite_a or _datacopied(a1, a)\n fdet, = get_flinalg_funcs(('det',), (a1,))\n a_det, info = fdet(a1, overwrite_a=overwrite_a)\n if info < 0:\n raise ValueError('illegal value in %d-th argument of internal '\n 'det.getrf' % -info)\n return a_det\n\n\n# Linear Least Squares\ndef lstsq(a, b, cond=None, overwrite_a=False, overwrite_b=False,\n check_finite=True, lapack_driver=None):\n \"\"\"\n Compute least-squares solution to equation Ax = b.\n\n Compute a vector x such that the 2-norm ``|b - A x|`` is minimized.\n\n Parameters\n ----------\n a : (M, N) array_like\n Left-hand side array\n b : (M,) or (M, K) array_like\n Right hand side array\n cond : float, optional\n Cutoff for 'small' singular values; used to determine effective\n rank of a. Singular values smaller than\n ``rcond * largest_singular_value`` are considered zero.\n overwrite_a : bool, optional\n Discard data in `a` (may enhance performance). Default is False.\n overwrite_b : bool, optional\n Discard data in `b` (may enhance performance). Default is False.\n check_finite : bool, optional\n Whether to check that the input matrices contain only finite numbers.\n Disabling may give a performance gain, but may result in problems\n (crashes, non-termination) if the inputs do contain infinities or NaNs.\n lapack_driver : str, optional\n Which LAPACK driver is used to solve the least-squares problem.\n Options are ``'gelsd'``, ``'gelsy'``, ``'gelss'``. Default\n (``'gelsd'``) is a good choice. However, ``'gelsy'`` can be slightly\n faster on many problems. ``'gelss'`` was used historically. It is\n generally slow but uses less memory.\n\n .. versionadded:: 0.17.0\n\n Returns\n -------\n x : (N,) or (N, K) ndarray\n Least-squares solution. Return shape matches shape of `b`.\n residues : (K,) ndarray or float\n Square of the 2-norm for each column in ``b - a x``, if ``M > N`` and\n ``ndim(A) == n`` (returns a scalar if b is 1-D). Otherwise a\n (0,)-shaped array is returned.\n rank : int\n Effective rank of `a`.\n s : (min(M, N),) ndarray or None\n Singular values of `a`. The condition number of a is\n ``abs(s[0] / s[-1])``.\n\n Raises\n ------\n LinAlgError\n If computation does not converge.\n\n ValueError\n When parameters are not compatible.\n\n See Also\n --------\n scipy.optimize.nnls : linear least squares with non-negativity constraint\n\n Notes\n -----\n When ``'gelsy'`` is used as a driver, `residues` is set to a (0,)-shaped\n array and `s` is always ``None``.\n\n Examples\n --------\n >>> from scipy.linalg import lstsq\n >>> import matplotlib.pyplot as plt\n\n Suppose we have the following data:\n\n >>> x = np.array([1, 2.5, 3.5, 4, 5, 7, 8.5])\n >>> y = np.array([0.3, 1.1, 1.5, 2.0, 3.2, 6.6, 8.6])\n\n We want to fit a quadratic polynomial of the form ``y = a + b*x**2``\n to this data. We first form the \"design matrix\" M, with a constant\n column of 1s and a column containing ``x**2``:\n\n >>> M = x[:, np.newaxis]**[0, 2]\n >>> M\n array([[ 1. , 1. ],\n [ 1. , 6.25],\n [ 1. , 12.25],\n [ 1. , 16. ],\n [ 1. , 25. ],\n [ 1. , 49. ],\n [ 1. , 72.25]])\n\n We want to find the least-squares solution to ``M.dot(p) = y``,\n where ``p`` is a vector with length 2 that holds the parameters\n ``a`` and ``b``.\n\n >>> p, res, rnk, s = lstsq(M, y)\n >>> p\n array([ 0.20925829, 0.12013861])\n\n Plot the data and the fitted curve.\n\n >>> plt.plot(x, y, 'o', label='data')\n >>> xx = np.linspace(0, 9, 101)\n >>> yy = p[0] + p[1]*xx**2\n >>> plt.plot(xx, yy, label='least squares fit, $y = a + bx^2$')\n >>> plt.xlabel('x')\n >>> plt.ylabel('y')\n >>> plt.legend(framealpha=1, shadow=True)\n >>> plt.grid(alpha=0.25)\n >>> plt.show()\n\n \"\"\"\n a1 = _asarray_validated(a, check_finite=check_finite)\n b1 = _asarray_validated(b, check_finite=check_finite)\n if len(a1.shape) != 2:\n raise ValueError('Input array a should be 2D')\n m, n = a1.shape\n if len(b1.shape) == 2:\n nrhs = b1.shape[1]\n else:\n nrhs = 1\n if m != b1.shape[0]:\n raise ValueError('Shape mismatch: a and b should have the same number'\n ' of rows ({} != {}).'.format(m, b1.shape[0]))\n if m == 0 or n == 0: # Zero-sized problem, confuses LAPACK\n x = np.zeros((n,) + b1.shape[1:], dtype=np.common_type(a1, b1))\n if n == 0:\n residues = np.linalg.norm(b1, axis=0)**2\n else:\n residues = np.empty((0,))\n return x, residues, 0, np.empty((0,))\n\n driver = lapack_driver\n if driver is None:\n driver = lstsq.default_lapack_driver\n if driver not in ('gelsd', 'gelsy', 'gelss'):\n raise ValueError('LAPACK driver \"%s\" is not found' % driver)\n\n lapack_func, lapack_lwork = get_lapack_funcs((driver,\n '%s_lwork' % driver),\n (a1, b1))\n real_data = True if (lapack_func.dtype.kind == 'f') else False\n\n if m < n:\n # need to extend b matrix as it will be filled with\n # a larger solution matrix\n if len(b1.shape) == 2:\n b2 = np.zeros((n, nrhs), dtype=lapack_func.dtype)\n b2[:m, :] = b1\n else:\n b2 = np.zeros(n, dtype=lapack_func.dtype)\n b2[:m] = b1\n b1 = b2\n\n overwrite_a = overwrite_a or _datacopied(a1, a)\n overwrite_b = overwrite_b or _datacopied(b1, b)\n\n if cond is None:\n cond = np.finfo(lapack_func.dtype).eps\n\n if driver in ('gelss', 'gelsd'):\n if driver == 'gelss':\n lwork = _compute_lwork(lapack_lwork, m, n, nrhs, cond)\n v, x, s, rank, work, info = lapack_func(a1, b1, cond, lwork,\n overwrite_a=overwrite_a,\n overwrite_b=overwrite_b)\n\n elif driver == 'gelsd':\n if real_data:\n lwork, iwork = _compute_lwork(lapack_lwork, m, n, nrhs, cond)\n x, s, rank, info = lapack_func(a1, b1, lwork,\n iwork, cond, False, False)\n else: # complex data\n lwork, rwork, iwork = _compute_lwork(lapack_lwork, m, n,\n nrhs, cond)\n x, s, rank, info = lapack_func(a1, b1, lwork, rwork, iwork,\n cond, False, False)\n if info > 0:\n raise LinAlgError(\"SVD did not converge in Linear Least Squares\")\n if info < 0:\n raise ValueError('illegal value in %d-th argument of internal %s'\n % (-info, lapack_driver))\n resids = np.asarray([], dtype=x.dtype)\n if m > n:\n x1 = x[:n]\n if rank == n:\n resids = np.sum(np.abs(x[n:])**2, axis=0)\n x = x1\n return x, resids, rank, s\n\n elif driver == 'gelsy':\n lwork = _compute_lwork(lapack_lwork, m, n, nrhs, cond)\n jptv = np.zeros((a1.shape[1], 1), dtype=np.int32)\n v, x, j, rank, info = lapack_func(a1, b1, jptv, cond,\n lwork, False, False)\n if info < 0:\n raise ValueError(\"illegal value in %d-th argument of internal \"\n \"gelsy\" % -info)\n if m > n:\n x1 = x[:n]\n x = x1\n return x, np.array([], x.dtype), rank, None\n\n\nlstsq.default_lapack_driver = 'gelsd'\n\n\ndef pinv(a, cond=None, rcond=None, return_rank=False, check_finite=True):\n \"\"\"\n Compute the (Moore-Penrose) pseudo-inverse of a matrix.\n\n Calculate a generalized inverse of a matrix using a least-squares\n solver.\n\n Parameters\n ----------\n a : (M, N) array_like\n Matrix to be pseudo-inverted.\n cond, rcond : float, optional\n Cutoff factor for 'small' singular values. In `lstsq`,\n singular values less than ``cond*largest_singular_value`` will be\n considered as zero. If both are omitted, the default value\n ``max(M, N) * eps`` is passed to `lstsq` where ``eps`` is the\n corresponding machine precision value of the datatype of ``a``.\n\n .. versionchanged:: 1.3.0\n Previously the default cutoff value was just `eps` without the\n factor ``max(M, N)``.\n\n return_rank : bool, optional\n if True, return the effective rank of the matrix\n check_finite : bool, optional\n Whether to check that the input matrix contains only finite numbers.\n Disabling may give a performance gain, but may result in problems\n (crashes, non-termination) if the inputs do contain infinities or NaNs.\n\n Returns\n -------\n B : (N, M) ndarray\n The pseudo-inverse of matrix `a`.\n rank : int\n The effective rank of the matrix. Returned if return_rank == True\n\n Raises\n ------\n LinAlgError\n If computation does not converge.\n\n Examples\n --------\n >>> from scipy import linalg\n >>> a = np.random.randn(9, 6)\n >>> B = linalg.pinv(a)\n >>> np.allclose(a, np.dot(a, np.dot(B, a)))\n True\n >>> np.allclose(B, np.dot(B, np.dot(a, B)))\n True\n\n \"\"\"\n a = _asarray_validated(a, check_finite=check_finite)\n b = np.identity(a.shape[0], dtype=a.dtype)\n\n if rcond is not None:\n cond = rcond\n\n if cond is None:\n cond = max(a.shape) * np.spacing(a.real.dtype.type(1))\n\n x, resids, rank, s = lstsq(a, b, cond=cond, check_finite=False)\n\n if return_rank:\n return x, rank\n else:\n return x\n\n\ndef pinv2(a, cond=None, rcond=None, return_rank=False, check_finite=True):\n \"\"\"\n Compute the (Moore-Penrose) pseudo-inverse of a matrix.\n\n Calculate a generalized inverse of a matrix using its\n singular-value decomposition and including all 'large' singular\n values.\n\n Parameters\n ----------\n a : (M, N) array_like\n Matrix to be pseudo-inverted.\n cond, rcond : float or None\n Cutoff for 'small' singular values; singular values smaller than this\n value are considered as zero. If both are omitted, the default value\n ``max(M,N)*largest_singular_value*eps`` is used where ``eps`` is the\n machine precision value of the datatype of ``a``.\n\n .. versionchanged:: 1.3.0\n Previously the default cutoff value was just ``eps*f`` where ``f``\n was ``1e3`` for single precision and ``1e6`` for double precision.\n\n return_rank : bool, optional\n If True, return the effective rank of the matrix.\n check_finite : bool, optional\n Whether to check that the input matrix contains only finite numbers.\n Disabling may give a performance gain, but may result in problems\n (crashes, non-termination) if the inputs do contain infinities or NaNs.\n\n Returns\n -------\n B : (N, M) ndarray\n The pseudo-inverse of matrix `a`.\n rank : int\n The effective rank of the matrix. Returned if `return_rank` is True.\n\n Raises\n ------\n LinAlgError\n If SVD computation does not converge.\n\n Examples\n --------\n >>> from scipy import linalg\n >>> a = np.random.randn(9, 6)\n >>> B = linalg.pinv2(a)\n >>> np.allclose(a, np.dot(a, np.dot(B, a)))\n True\n >>> np.allclose(B, np.dot(B, np.dot(a, B)))\n True\n\n \"\"\"\n a = _asarray_validated(a, check_finite=check_finite)\n u, s, vh = decomp_svd.svd(a, full_matrices=False, check_finite=False)\n\n if rcond is not None:\n cond = rcond\n if cond in [None, -1]:\n t = u.dtype.char.lower()\n cond = np.max(s) * max(a.shape) * np.finfo(t).eps\n\n rank = np.sum(s > cond)\n\n u = u[:, :rank]\n u /= s[:rank]\n B = np.transpose(np.conjugate(np.dot(u, vh[:rank])))\n\n if return_rank:\n return B, rank\n else:\n return B\n\n\ndef pinvh(a, cond=None, rcond=None, lower=True, return_rank=False,\n check_finite=True):\n \"\"\"\n Compute the (Moore-Penrose) pseudo-inverse of a Hermitian matrix.\n\n Calculate a generalized inverse of a Hermitian or real symmetric matrix\n using its eigenvalue decomposition and including all eigenvalues with\n 'large' absolute value.\n\n Parameters\n ----------\n a : (N, N) array_like\n Real symmetric or complex hermetian matrix to be pseudo-inverted\n cond, rcond : float or None\n Cutoff for 'small' singular values; singular values smaller than this\n value are considered as zero. If both are omitted, the default\n ``max(M,N)*largest_eigenvalue*eps`` is used where ``eps`` is the\n machine precision value of the datatype of ``a``.\n\n .. versionchanged:: 1.3.0\n Previously the default cutoff value was just ``eps*f`` where ``f``\n was ``1e3`` for single precision and ``1e6`` for double precision.\n\n lower : bool, optional\n Whether the pertinent array data is taken from the lower or upper\n triangle of `a`. (Default: lower)\n return_rank : bool, optional\n If True, return the effective rank of the matrix.\n check_finite : bool, optional\n Whether to check that the input matrix contains only finite numbers.\n Disabling may give a performance gain, but may result in problems\n (crashes, non-termination) if the inputs do contain infinities or NaNs.\n\n Returns\n -------\n B : (N, N) ndarray\n The pseudo-inverse of matrix `a`.\n rank : int\n The effective rank of the matrix. Returned if `return_rank` is True.\n\n Raises\n ------\n LinAlgError\n If eigenvalue does not converge\n\n Examples\n --------\n >>> from scipy.linalg import pinvh\n >>> a = np.random.randn(9, 6)\n >>> a = np.dot(a, a.T)\n >>> B = pinvh(a)\n >>> np.allclose(a, np.dot(a, np.dot(B, a)))\n True\n >>> np.allclose(B, np.dot(B, np.dot(a, B)))\n True\n\n \"\"\"\n a = _asarray_validated(a, check_finite=check_finite)\n s, u = decomp.eigh(a, lower=lower, check_finite=False)\n\n if rcond is not None:\n cond = rcond\n if cond in [None, -1]:\n t = u.dtype.char.lower()\n cond = np.max(np.abs(s)) * max(a.shape) * np.finfo(t).eps\n\n # For Hermitian matrices, singular values equal abs(eigenvalues)\n above_cutoff = (abs(s) > cond)\n psigma_diag = 1.0 / s[above_cutoff]\n u = u[:, above_cutoff]\n\n B = np.dot(u * psigma_diag, np.conjugate(u).T)\n\n if return_rank:\n return B, len(psigma_diag)\n else:\n return B\n\n\ndef matrix_balance(A, permute=True, scale=True, separate=False,\n overwrite_a=False):\n \"\"\"\n Compute a diagonal similarity transformation for row/column balancing.\n\n The balancing tries to equalize the row and column 1-norms by applying\n a similarity transformation such that the magnitude variation of the\n matrix entries is reflected to the scaling matrices.\n\n Moreover, if enabled, the matrix is first permuted to isolate the upper\n triangular parts of the matrix and, again if scaling is also enabled,\n only the remaining subblocks are subjected to scaling.\n\n The balanced matrix satisfies the following equality\n\n .. math::\n\n B = T^{-1} A T\n\n The scaling coefficients are approximated to the nearest power of 2\n to avoid round-off errors.\n\n Parameters\n ----------\n A : (n, n) array_like\n Square data matrix for the balancing.\n permute : bool, optional\n The selector to define whether permutation of A is also performed\n prior to scaling.\n scale : bool, optional\n The selector to turn on and off the scaling. If False, the matrix\n will not be scaled.\n separate : bool, optional\n This switches from returning a full matrix of the transformation\n to a tuple of two separate 1-D permutation and scaling arrays.\n overwrite_a : bool, optional\n This is passed to xGEBAL directly. Essentially, overwrites the result\n to the data. It might increase the space efficiency. See LAPACK manual\n for details. This is False by default.\n\n Returns\n -------\n B : (n, n) ndarray\n Balanced matrix\n T : (n, n) ndarray\n A possibly permuted diagonal matrix whose nonzero entries are\n integer powers of 2 to avoid numerical truncation errors.\n scale, perm : (n,) ndarray\n If ``separate`` keyword is set to True then instead of the array\n ``T`` above, the scaling and the permutation vectors are given\n separately as a tuple without allocating the full array ``T``.\n\n Notes\n -----\n\n This algorithm is particularly useful for eigenvalue and matrix\n decompositions and in many cases it is already called by various\n LAPACK routines.\n\n The algorithm is based on the well-known technique of [1]_ and has\n been modified to account for special cases. See [2]_ for details\n which have been implemented since LAPACK v3.5.0. Before this version\n there are corner cases where balancing can actually worsen the\n conditioning. See [3]_ for such examples.\n\n The code is a wrapper around LAPACK's xGEBAL routine family for matrix\n balancing.\n\n .. versionadded:: 0.19.0\n\n Examples\n --------\n >>> from scipy import linalg\n >>> x = np.array([[1,2,0], [9,1,0.01], [1,2,10*np.pi]])\n\n >>> y, permscale = linalg.matrix_balance(x)\n >>> np.abs(x).sum(axis=0) / np.abs(x).sum(axis=1)\n array([ 3.66666667, 0.4995005 , 0.91312162])\n\n >>> np.abs(y).sum(axis=0) / np.abs(y).sum(axis=1)\n array([ 1.2 , 1.27041742, 0.92658316]) # may vary\n\n >>> permscale # only powers of 2 (0.5 == 2^(-1))\n array([[ 0.5, 0. , 0. ], # may vary\n [ 0. , 1. , 0. ],\n [ 0. , 0. , 1. ]])\n\n References\n ----------\n .. [1] : B.N. Parlett and C. Reinsch, \"Balancing a Matrix for\n Calculation of Eigenvalues and Eigenvectors\", Numerische Mathematik,\n Vol.13(4), 1969, DOI:10.1007/BF02165404\n\n .. [2] : R. James, J. Langou, B.R. Lowery, \"On matrix balancing and\n eigenvector computation\", 2014, Available online:\n https://arxiv.org/abs/1401.5766\n\n .. [3] : D.S. Watkins. A case where balancing is harmful.\n Electron. Trans. Numer. Anal, Vol.23, 2006.\n\n \"\"\"\n\n A = np.atleast_2d(_asarray_validated(A, check_finite=True))\n\n if not np.equal(*A.shape):\n raise ValueError('The data matrix for balancing should be square.')\n\n gebal = get_lapack_funcs(('gebal'), (A,))\n B, lo, hi, ps, info = gebal(A, scale=scale, permute=permute,\n overwrite_a=overwrite_a)\n\n if info < 0:\n raise ValueError('xGEBAL exited with the internal error '\n '\"illegal value in argument number {}.\". See '\n 'LAPACK documentation for the xGEBAL error codes.'\n ''.format(-info))\n\n # Separate the permutations from the scalings and then convert to int\n scaling = np.ones_like(ps, dtype=float)\n scaling[lo:hi+1] = ps[lo:hi+1]\n\n # gebal uses 1-indexing\n ps = ps.astype(int, copy=False) - 1\n n = A.shape[0]\n perm = np.arange(n)\n\n # LAPACK permutes with the ordering n --> hi, then 0--> lo\n if hi < n:\n for ind, x in enumerate(ps[hi+1:][::-1], 1):\n if n-ind == x:\n continue\n perm[[x, n-ind]] = perm[[n-ind, x]]\n\n if lo > 0:\n for ind, x in enumerate(ps[:lo]):\n if ind == x:\n continue\n perm[[x, ind]] = perm[[ind, x]]\n\n if separate:\n return B, (scaling, perm)\n\n # get the inverse permutation\n iperm = np.empty_like(perm)\n iperm[perm] = np.arange(n)\n\n return B, np.diag(scaling)[iperm, :]\n" ]
[ [ "numpy.ones_like", "numpy.dot", "numpy.rollaxis", "numpy.finfo", "numpy.iscomplexobj", "numpy.conjugate", "numpy.concatenate", "numpy.max", "numpy.linalg.norm", "numpy.empty", "numpy.common_type", "numpy.arange", "numpy.empty_like", "numpy.equal", "numpy.array", "numpy.zeros", "numpy.identity", "numpy.fft.ifft", "numpy.asarray", "numpy.ascontiguousarray", "numpy.sum", "numpy.any", "numpy.atleast_1d", "numpy.abs", "numpy.diag" ] ]
Taoudi/DataAugmentation
[ "84691bee5b203e06356838fa8e0ac8d3830538be" ]
[ "src/DataLoader.py" ]
[ "# Summarize the Credit Card Fraud dataset\nimport numpy as np \nfrom pandas import read_csv\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\n\nclass DataLoader:\n\tdef __init__(self, datafile='creditcard.csv'):\n\t\tscaler = StandardScaler()\n\n\t\t#Convert to numpy arrays for tensorflow\n\t\t#self.X = scaler.fit_transform(X_train,y_train)\n\t\t#self.testX = scaler.transform(X_test)\n\n\n\t\tpath = 'data/' + datafile\n\t\tdataframe = read_csv(path)\n\t\tvalues = dataframe.values\n\t\tself.X, self.Y = values[:, :-1], values[:, -1]\n\t\tmean = np.mean(self.X)\n\t\tvar = np.var(self.X)\n\t\tself.min = np.max(self.X)\n\t\tself.max = np.min(self.X)\n\t\t#self.X = (self.X-self.min)/(self.max-self.min)\n\t\t#print(np.std(self.X,axis=0))\n\n\t\tself.X, self.testX, self.Y, self.testY = train_test_split(self.X,self.Y, test_size=0.15)\n\t\tself.X, self.valX, self.Y, self.valY = train_test_split(self.X,self.Y, test_size=0.1)\n\t\tself.X = scaler.fit_transform(self.X,self.Y)\n\t\tself.valX = scaler.fit_transform(self.valX,self.valY)\n\n\t\tself.testX = scaler.transform(self.testX)\n\t\tprint(np.std(self.X,axis=0)) #Check that the column standard deviations are all 1\n\n\t\tself.classes = np.unique(self.Y)\n\t\tself.n_classes = len(self.classes)\n\n\tdef normalize(self):\n\t\tself.X = (self.X-self.min)/(self.max-self.min)\n\t\tself.valX = (self.valX-self.min)/(self.max-self.min)\n\t\tself.testX = (self.testX-self.min)/(self.max-self.min)\n\t\t\n\n\tdef summarize(self,test=False):\n\t\tif test:\n\t\t\tX = self.testX\n\t\t\tY = self.testY\n\t\telse:\n\t\t\tX = self.X\n\t\t\tY = self.Y\n\t\tn_rows = self.X.shape[0]\n\t\tn_cols = self.X.shape[1]\n\t\tclasses = np.unique(Y)\n\t\tn_classes = len(classes)\n\t\t# summarize\n\t\tprint('N Classes: %d' % n_classes)\n\t\tprint('Classes: %s' % classes)\n\t\tprint('Class Breakdown:')\n\t\t# class breakdown\n\t\tbreakdown = ''\n\t\tfor c in classes:\n\t\t\ttotal = len(Y[Y == c])\n\t\t\tratio = (total / float(len(Y))) * 100\n\t\t\tprint(' - Class %s: %d (%.5f%%)' % (str(c), total, ratio))" ]
[ [ "numpy.max", "sklearn.preprocessing.StandardScaler", "numpy.min", "numpy.mean", "numpy.std", "numpy.unique", "sklearn.model_selection.train_test_split", "pandas.read_csv", "numpy.var" ] ]
eyeshoe/mhcflurry
[ "b87aac3cf1a782cb1235f9b724388bbdd933d9fb" ]
[ "test/test_speed.py" ]
[ "\"\"\"\nProfile prediction speed\n\n\"\"\"\nimport numpy\nnumpy.random.seed(0)\nimport time\nimport cProfile\nimport pstats\nimport collections\nimport argparse\nimport sys\n\nimport pandas\n\nfrom mhcflurry import Class1AffinityPredictor\nfrom mhcflurry.encodable_sequences import EncodableSequences\nfrom mhcflurry.common import random_peptides\nfrom mhcflurry.downloads import get_path\n\nfrom mhcflurry.testing_utils import cleanup, startup\n\n\nALLELE_SPECIFIC_PREDICTOR = None\nPAN_ALLELE_PREDICTOR = None\n\n\ndef setup():\n global ALLELE_SPECIFIC_PREDICTOR, PAN_ALLELE_PREDICTOR\n startup()\n ALLELE_SPECIFIC_PREDICTOR = Class1AffinityPredictor.load(\n get_path(\"models_class1\", \"models\"))\n\n PAN_ALLELE_PREDICTOR = Class1AffinityPredictor.load(\n get_path(\"models_class1_pan\", \"models.with_mass_spec\"))\n\n\ndef teardown():\n global ALLELE_SPECIFIC_PREDICTOR, PAN_ALLELE_PREDICTOR\n ALLELE_SPECIFIC_PREDICTOR = None\n PAN_ALLELE_PREDICTOR = None\n cleanup()\n\n\nDEFAULT_NUM_PREDICTIONS = 10000\n\n\ndef test_speed_allele_specific(profile=False, num=DEFAULT_NUM_PREDICTIONS):\n global ALLELE_SPECIFIC_PREDICTOR\n starts = collections.OrderedDict()\n timings = collections.OrderedDict()\n profilers = collections.OrderedDict()\n\n predictor = ALLELE_SPECIFIC_PREDICTOR\n\n def start(name):\n starts[name] = time.time()\n if profile:\n profilers[name] = cProfile.Profile()\n profilers[name].enable()\n\n def end(name):\n timings[name] = time.time() - starts[name]\n if profile:\n profilers[name].disable()\n\n start(\"first\")\n predictor.predict([\"SIINFEKL\"], allele=\"HLA-A*02:01\")\n end(\"first\")\n\n peptides = random_peptides(num)\n start(\"pred_%d\" % num)\n predictor.predict(peptides, allele=\"HLA-A*02:01\")\n end(\"pred_%d\" % num)\n\n NUM2 = 10000\n peptides = EncodableSequences.create(random_peptides(NUM2, length=13))\n start(\"encode_blosum_%d\" % NUM2)\n peptides.variable_length_to_fixed_length_vector_encoding(\"BLOSUM62\")\n end(\"encode_blosum_%d\" % NUM2)\n\n start(\"pred_already_encoded_%d\" % NUM2)\n predictor.predict(peptides, allele=\"HLA-A*02:01\")\n end(\"pred_already_encoded_%d\" % NUM2)\n\n NUM_REPEATS = 100\n start(\"pred_already_encoded_%d_%d_times\" % (NUM2, NUM_REPEATS))\n for _ in range(NUM_REPEATS):\n predictor.predict(peptides, allele=\"HLA-A*02:01\")\n end(\"pred_already_encoded_%d_%d_times\" % (NUM2, NUM_REPEATS))\n\n print(\"SPEED BENCHMARK\")\n print(\"Results:\\n%s\" % str(pandas.Series(timings)))\n\n return dict(\n (key, pstats.Stats(value)) for (key, value) in profilers.items())\n\n\ndef test_speed_pan_allele(profile=False, num=DEFAULT_NUM_PREDICTIONS):\n global PAN_ALLELE_PREDICTOR\n starts = collections.OrderedDict()\n timings = collections.OrderedDict()\n profilers = collections.OrderedDict()\n\n predictor = PAN_ALLELE_PREDICTOR\n\n def start(name):\n starts[name] = time.time()\n if profile:\n profilers[name] = cProfile.Profile()\n profilers[name].enable()\n\n def end(name):\n timings[name] = time.time() - starts[name]\n if profile:\n profilers[name].disable()\n\n start(\"first\")\n predictor.predict([\"SIINFEKL\"], allele=\"HLA-A*02:01\")\n end(\"first\")\n\n peptides = random_peptides(num)\n start(\"pred_%d\" % num)\n predictor.predict(peptides, allele=\"HLA-A*02:01\")\n end(\"pred_%d\" % num)\n\n print(\"SPEED BENCHMARK\")\n print(\"Results:\\n%s\" % str(pandas.Series(timings)))\n\n return dict(\n (key, pstats.Stats(value)) for (key, value) in profilers.items())\n\n\nparser = argparse.ArgumentParser(usage=__doc__)\nparser.add_argument(\n \"--predictor\",\n nargs=\"+\",\n choices=[\"allele-specific\", \"pan-allele\"],\n default=[\"allele-specific\", \"pan-allele\"],\n help=\"Which predictors to run\")\n\nparser.add_argument(\n \"--num-predictions\",\n type=int,\n default=DEFAULT_NUM_PREDICTIONS,\n help=\"Number of predictions to run\")\n\nif __name__ == '__main__':\n # If run directly from python, do profiling and leave the user in a shell\n # to explore results.\n\n args = parser.parse_args(sys.argv[1:])\n setup()\n\n if \"allele-specific\" in args.predictor:\n print(\"Running allele-specific test\")\n result = test_speed_allele_specific(\n profile=True, num=args.num_predictions)\n result[\n \"pred_%d\" % args.num_predictions\n ].sort_stats(\"cumtime\").reverse_order().print_stats()\n\n if \"pan-allele\" in args.predictor:\n print(\"Running pan-allele test\")\n result = test_speed_pan_allele(\n profile=True, num=args.num_predictions)\n result[\n \"pred_%d\" % args.num_predictions\n ].sort_stats(\"cumtime\").reverse_order().print_stats()\n\n # Leave in ipython\n locals().update(result)\n import ipdb # pylint: disable=import-error\n ipdb.set_trace()\n" ]
[ [ "numpy.random.seed", "pandas.Series" ] ]