repo
stringlengths
2
99
file
stringlengths
13
225
code
stringlengths
0
18.3M
file_length
int64
0
18.3M
avg_line_length
float64
0
1.36M
max_line_length
int64
0
4.26M
extension_type
stringclasses
1 value
clx-branch-23.04
clx-branch-23.04/python/clx/analytics/sequence_classifier.py
import logging import os import cudf from cudf.core.subword_tokenizer import SubwordTokenizer import cupy import torch from clx.utils.data.dataloader import DataLoader from clx.utils.data.dataset import Dataset from torch.utils.dlpack import to_dlpack from tqdm import trange from torch.optim import AdamW from abc import ABC, abstractmethod log = logging.getLogger(__name__) class SequenceClassifier(ABC): """ Sequence Classifier using BERT. This class provides methods for training/loading BERT models, evaluation and prediction. """ def __init__(self): self._device = None self._model = None self._optimizer = None self._hashpath = self._get_hash_table_path() @abstractmethod def predict(self, input_data, max_seq_len=128, batch_size=32, threshold=0.5): pass def train_model( self, train_data, labels, learning_rate=3e-5, max_seq_len=128, batch_size=32, epochs=5, ): """ Train the classifier :param train_data: text data for training :type train_data: cudf.Series :param labels: labels for each element in train_data :type labels: cudf.Series :param learning_rate: learning rate :type learning_rate: float :param max_seq_len: Limits the length of the sequence returned by tokenizer. If tokenized sentence is shorter than max_seq_len, output will be padded with 0s. If the tokenized sentence is longer than max_seq_len it will be truncated to max_seq_len. :type max_seq_len: int :param batch_size: batch size :type batch_size: int :param epoch: epoch, default is 5 :type epoch: int Examples -------- >>> from cuml.preprocessing.model_selection import train_test_split >>> emails_train, emails_test, labels_train, labels_test = train_test_split(train_emails_df, 'label', train_size=0.8) >>> sc.train_model(emails_train, labels_train) """ train_gdf = cudf.DataFrame() train_gdf["text"] = train_data train_gdf["label"] = labels train_dataset = Dataset(train_gdf) train_dataloader = DataLoader(train_dataset, batchsize=batch_size) self._config_optimizer(learning_rate) self._model.train() # Enable training mode self._tokenizer = SubwordTokenizer(self._hashpath, do_lower_case=True) for _ in trange(epochs, desc="Epoch"): tr_loss = 0 # Tracking variables nb_tr_examples, nb_tr_steps = 0, 0 for df in train_dataloader.get_chunks(): b_input_ids, b_input_mask = self._bert_uncased_tokenize(df["text"], max_seq_len) b_labels = torch.tensor(df["label"].to_numpy()) self._optimizer.zero_grad() # Clear out the gradients loss = self._model(b_input_ids, token_type_ids=None, attention_mask=b_input_mask, labels=b_labels)[0] # forwardpass loss.sum().backward() self._optimizer.step() # update parameters tr_loss += loss.sum().item() # get a numeric value nb_tr_examples += b_input_ids.size(0) nb_tr_steps += 1 print("Train loss: {}".format(tr_loss / nb_tr_steps)) def evaluate_model(self, test_data, labels, max_seq_len=128, batch_size=32): """ Evaluate trained model :param test_data: test data to evaluate model :type test_data: cudf.Series :param labels: labels for each element in test_data :type labels: cudf.Series :param max_seq_len: Limits the length of the sequence returned by tokenizer. If tokenized sentence is shorter than max_seq_len, output will be padded with 0s. If the tokenized sentence is longer than max_seq_len it will be truncated to max_seq_len. :type max_seq_len: int :param batch_size: batch size :type batch_size: int Examples -------- >>> from cuml.preprocessing.model_selection import train_test_split >>> emails_train, emails_test, labels_train, labels_test = train_test_split(train_emails_df, 'label', train_size=0.8) >>> sc.evaluate_model(emails_test, labels_test) """ self._model.eval() test_gdf = cudf.DataFrame() test_gdf["text"] = test_data test_gdf["label"] = labels test_dataset = Dataset(test_gdf) test_dataloader = DataLoader(test_dataset, batchsize=batch_size) eval_accuracy = 0 nb_eval_steps = 0 for df in test_dataloader.get_chunks(): b_input_ids, b_input_mask = self._bert_uncased_tokenize(df["text"], max_seq_len) b_labels = torch.tensor(df["label"].to_numpy()) with torch.no_grad(): logits = self._model( b_input_ids, token_type_ids=None, attention_mask=b_input_mask )[0] logits = logits.type(torch.DoubleTensor).to(self._device) logits = cupy.fromDlpack(to_dlpack(logits)) label_ids = b_labels.type(torch.IntTensor).to(self._device) label_ids = cupy.fromDlpack(to_dlpack(label_ids)) temp_eval_accuracy = self._flatten_accuracy(logits, label_ids) eval_accuracy += temp_eval_accuracy nb_eval_steps += 1 accuracy = eval_accuracy / nb_eval_steps return float(accuracy) def save_model(self, save_to_path="."): """ Save trained model :param save_to_path: directory path to save model, default is current directory :type save_to_path: str Examples -------- >>> from cuml.preprocessing.model_selection import train_test_split >>> emails_train, emails_test, labels_train, labels_test = train_test_split(train_emails_df, 'label', train_size=0.8) >>> sc.train_model(emails_train, labels_train) >>> sc.save_model() """ self._model.module.save_pretrained(save_to_path) def save_checkpoint(self, file_path): """ Save model checkpoint :param file_path: file path to save checkpoint :type file_path: str Examples -------- >>> sc.init_model("bert-base-uncased") # huggingface pre-trained model >>> sc.train_model(train_data, train_labels) >>> sc.save_checkpoint(PATH) """ checkpoint = { "state_dict": self._model.module.state_dict() } torch.save(checkpoint, file_path) def load_checkpoint(self, file_path): """ Load model checkpoint :param file_path: file path to load checkpoint :type file_path: str Examples -------- >>> sc.init_model("bert-base-uncased") # huggingface pre-trained model >>> sc.load_checkpoint(PATH) """ model_dict = torch.load(file_path) self._model.module.load_state_dict(model_dict["state_dict"]) def _get_hash_table_path(self): hash_table_path = "%s/resources/bert-base-uncased-hash.txt" % os.path.dirname( os.path.realpath(__file__) ) return hash_table_path def _config_optimizer(self, learning_rate): param_optimizer = list(self._model.named_parameters()) no_decay = ["bias", "gamma", "beta"] optimizer_grouped_parameters = [ { "params": [ p for n, p in param_optimizer if not any(nd in n for nd in no_decay) ], "weight_decay_rate": 0.01, }, { "params": [ p for n, p in param_optimizer if any(nd in n for nd in no_decay) ], "weight_decay_rate": 0.0, }, ] self._optimizer = AdamW(optimizer_grouped_parameters, learning_rate) def _flatten_accuracy(self, preds, labels): pred_flat = cupy.argmax(preds, axis=1).flatten() labels_flat = labels.flatten() return cupy.sum(pred_flat == labels_flat) / len(labels_flat) def _bert_uncased_tokenize(self, strings, max_length): """ converts cudf.Series of strings to two torch tensors- token ids and attention mask with padding """ output = self._tokenizer(strings, max_length=max_length, max_num_rows=len(strings), truncation=True, add_special_tokens=True, return_tensors="pt") return output['input_ids'].type(torch.long), output['attention_mask'].type(torch.long)
8,757
35.953586
256
py
clx-branch-23.04
clx-branch-23.04/python/clx/analytics/stats.py
# Copyright (c) 2019, NVIDIA CORPORATION. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import math log = logging.getLogger(__name__) def rzscore(series, window): """ Calculates rolling z-score Parameters ---------- series : cudf.Series Series for which to calculate rolling z-score window : int Window size Returns ------- cudf.Series Series with rolling z-score values Examples -------- >>> import clx.analytics.stats >>> import cudf >>> sequence = [3,4,5,6,1,10,34,2,1,11,45,34,2,9,19,43,24,13,23,10,98,84,10] >>> series = cudf.Series(sequence) >>> zscores_df = cudf.DataFrame() >>> zscores_df['zscore'] = clx.analytics.stats.rzscore(series, 7) >>> zscores_df zscore 0 null 1 null 2 null 3 null 4 null 5 null 6 2.374423424 7 -0.645941275 8 -0.683973734 9 0.158832461 10 1.847751909 11 0.880026019 12 -0.950835449 13 -0.360593742 14 0.111407599 15 1.228914145 16 -0.074966331 17 -0.570321249 18 0.327849973 19 -0.934372308 20 2.296828498 21 1.282966989 22 -0.795223674 """ rolling = series.rolling(window=window) mean = rolling.mean() std = rolling.apply(__std_func) zscore = (series - mean) / std return zscore def __std_func(A): """ Current implementation assumes ddof = 0 """ sum_of_elem = 0 sum_of_square_elem = 0 for a in A: sum_of_elem += a sum_of_square_elem += a * a s = (sum_of_square_elem - ((sum_of_elem * sum_of_elem) / len(A))) / len(A) return math.sqrt(s)
2,265
23.630435
80
py
clx-branch-23.04
clx-branch-23.04/python/clx/analytics/periodicity_detection.py
import cupy as cp def to_periodogram(signal): """ Returns periodogram of signal for finding frequencies that have high energy. :param signal: signal (time domain) :type signal: cudf.Series :return: CuPy array representing periodogram :rtype: cupy.ndarray """ # convert cudf series to cupy array signal_cp = cp.fromDlpack(signal.to_dlpack()) # standardize the signal signal_cp_std = (signal_cp - cp.mean(signal_cp)) / cp.std(signal_cp) # take fourier transform of signal FFT_data = cp.fft.fft(signal_cp_std) # create periodogram prdg = (1 / len(signal)) * ((cp.absolute(FFT_data)) ** 2) return prdg def filter_periodogram(prdg, p_value): """ Select important frequencies by filtering periodogram by p-value. Filtered out frequencies are set to zero. :param prdg: periodogram to be filtered :type signal: cudf.Series :param p_value: p-value to filter by :type signal: float :return: CuPy array representing periodogram :rtype: cupy.ndarray """ filtered_prdg = cp.copy(prdg) filtered_prdg[filtered_prdg < (cp.mean(filtered_prdg) * (-1) * (cp.log(p_value)))] = 0 return filtered_prdg def to_time_domain(prdg): """ Convert the signal back to time domain. :param prdg: periodogram (frequency domain) :type prdg: cupy.ndarray :return: CuPy array representing reconstructed signal :rtype: cupy.ndarray """ acf = cp.abs(cp.fft.ifft(prdg)) return acf
1,507
24.133333
111
py
clx-branch-23.04
clx-branch-23.04/python/clx/analytics/cybert.py
# Copyright (c) 2020, NVIDIA CORPORATION. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import json import logging import os from collections import defaultdict import numpy as np import pandas as pd import torch import torch.nn as nn from torch.nn import functional as F from torch.utils.data import DataLoader, TensorDataset from transformers import ( BertForTokenClassification, DistilBertForTokenClassification, ElectraForTokenClassification, ) from cudf.core.subword_tokenizer import SubwordTokenizer log = logging.getLogger(__name__) ARCH_MAPPING = { "BertForTokenClassification": BertForTokenClassification, "DistilBertForTokenClassification": DistilBertForTokenClassification, "ElectraForTokenClassification": ElectraForTokenClassification, } MODEL_MAPPING = { "BertForTokenClassification": "bert-base-cased", "DistilBertForTokenClassification": "distilbert-base-cased", "ElectraForTokenClassification": "rapids/electra-small-discriminator", } class Cybert: """ Cyber log parsing using BERT, DistilBERT, or ELECTRA. This class provides methods for loading models, prediction, and postprocessing. """ def __init__(self): self._model = None self._label_map = {} resources_dir = "%s/resources" % os.path.dirname(os.path.realpath(__file__)) vocabpath = "%s/bert-base-cased-vocab.txt" % resources_dir self._vocab_lookup = {} with open(vocabpath) as f: for index, line in enumerate(f): self._vocab_lookup[index] = line.split()[0] self._hashpath = "%s/bert-base-cased-hash.txt" % resources_dir self.tokenizer = SubwordTokenizer(self._hashpath, do_lower_case=False) def load_model(self, model_filepath, config_filepath): """ Load cybert model. :param model_filepath: Filepath of the model (.pth or .bin) to be loaded :type model_filepath: str :param config_filepath: Config file (.json) to be used :type config_filepath: str Examples -------- >>> from clx.analytics.cybert import Cybert >>> cyparse = Cybert() >>> cyparse.load_model('/path/to/model.bin', '/path/to/config.json') """ with open(config_filepath) as f: config = json.load(f) model_arch = config["architectures"][0] self._label_map = {int(k): v for k, v in config["id2label"].items()} self._model = ARCH_MAPPING[model_arch].from_pretrained( model_filepath, config=config_filepath, ) self._model.cuda() self._model.eval() self._model = nn.DataParallel(self._model) def preprocess(self, raw_data_col, stride_len=116, max_seq_len=128): """ Preprocess and tokenize data for cybert model inference. :param raw_data_col: logs to be processed :type raw_data_col: cudf.Series :param stride_len: Max stride length for processing, default is 116 :type stride_len: int :param max_seq_len: Max sequence length for processing, default is 128 :type max_seq_len: int Examples -------- >>> import cudf >>> from clx.analytics.cybert import Cybert >>> cyparse = Cybert() >>> cyparse.load_model('/path/to/model.pth', '/path/to/config.json') >>> raw_df = cudf.Series(['Log event 1', 'Log event 2']) >>> input_ids, attention_masks, meta_data = cyparse.preprocess(raw_df) """ raw_data_col = raw_data_col.str.replace('"', "") raw_data_col = raw_data_col.str.replace("\\r", " ") raw_data_col = raw_data_col.str.replace("\\t", " ") raw_data_col = raw_data_col.str.replace("=", "= ") raw_data_col = raw_data_col.str.replace("\\n", " ") output = self.tokenizer( raw_data_col, max_length=128, stride=12, max_num_rows=len(raw_data_col), truncation=False, add_special_tokens=False, return_tensors="pt", ) input_ids = output["input_ids"].type(torch.long) attention_masks = output["attention_mask"].type(torch.long) meta_data = output["metadata"] return input_ids, attention_masks, meta_data def inference(self, raw_data_col, batch_size=160): """ Cybert inference and postprocessing on dataset :param raw_data_col: logs to be processed :type raw_data_col: cudf.Series :param batch_size: Log data is processed in batches using a Pytorch dataloader. The batch size parameter refers to the batch size indicated in torch.utils.data.DataLoader. :type batch_size: int :return: parsed_df :rtype: pandas.DataFrame :return: confidence_df :rtype: pandas.DataFrame Examples -------- >>> import cudf >>> from clx.analytics.cybert import Cybert >>> cyparse = Cybert() >>> cyparse.load_model('/path/to/model.pth', '/path/to/config.json') >>> raw_data_col = cudf.Series(['Log event 1', 'Log event 2']) >>> processed_df, confidence_df = cy.inference(raw_data_col) """ input_ids, attention_masks, meta_data = self.preprocess(raw_data_col) dataset = TensorDataset(input_ids, attention_masks) dataloader = DataLoader(dataset=dataset, shuffle=False, batch_size=batch_size) confidences_list = [] labels_list = [] for step, batch in enumerate(dataloader): in_ids, att_masks = batch with torch.no_grad(): logits = self._model(in_ids, att_masks)[0] logits = F.softmax(logits, dim=2) confidences, labels = torch.max(logits, 2) confidences_list.extend(confidences.detach().cpu().numpy().tolist()) labels_list.extend(labels.detach().cpu().numpy().tolist()) infer_pdf = pd.DataFrame(meta_data.cpu()).astype(int) infer_pdf.columns = ["doc", "start", "stop"] infer_pdf["confidences"] = confidences_list infer_pdf["labels"] = labels_list infer_pdf["token_ids"] = input_ids.detach().cpu().numpy().tolist() del dataset del dataloader del logits del confidences del labels del confidences_list del labels_list parsed_df, confidence_df = self.__postprocess(infer_pdf) return parsed_df, confidence_df def __postprocess(self, infer_pdf): # cut overlapping edges infer_pdf["confidences"] = infer_pdf.apply( lambda row: row["confidences"][row["start"]:row["stop"]], axis=1 ) infer_pdf["labels"] = infer_pdf.apply( lambda row: row["labels"][row["start"]:row["stop"]], axis=1 ) infer_pdf["token_ids"] = infer_pdf.apply( lambda row: row["token_ids"][row["start"]:row["stop"]], axis=1 ) # aggregated logs infer_pdf = infer_pdf.groupby("doc").agg( {"token_ids": "sum", "confidences": "sum", "labels": "sum"} ) # parse_by_label parsed_dfs = infer_pdf.apply( lambda row: self.__get_label_dicts(row), axis=1, result_type="expand" ) parsed_df = pd.DataFrame(parsed_dfs[0].tolist()) confidence_df = pd.DataFrame(parsed_dfs[1].tolist()) if "X" in confidence_df.columns: confidence_df = confidence_df.drop(["X"], axis=1) confidence_df = confidence_df.applymap(np.mean) # decode cleanup parsed_df = self.__decode_cleanup(parsed_df) return parsed_df, confidence_df def __get_label_dicts(self, row): token_dict = defaultdict(str) confidence_dict = defaultdict(list) for label, confidence, token_id in zip( row["labels"], row["confidences"], row["token_ids"] ): text_token = self._vocab_lookup[token_id] if text_token[:2] != "##": # if not a subword use the current label, else use previous new_label = label new_confidence = confidence if self._label_map[new_label] in token_dict: token_dict[self._label_map[new_label]] = ( token_dict[self._label_map[new_label]] + " " + text_token ) else: token_dict[self._label_map[new_label]] = text_token confidence_dict[self._label_map[label]].append(new_confidence) return token_dict, confidence_dict def __decode_cleanup(self, df): return ( df.replace(" ##", "", regex=True) .replace(" : ", ":", regex=True) .replace("\[ ", "[", regex=True) .replace(" ]", "]", regex=True) .replace(" /", "/", regex=True) .replace("/ ", "/", regex=True) .replace(" - ", "-", regex=True) .replace(" \( ", " (", regex=True) .replace(" \) ", ") ", regex=True) .replace("\+ ", "+", regex=True) .replace(" . ", ".", regex=True) )
9,636
36.644531
99
py
clx-branch-23.04
clx-branch-23.04/python/clx/analytics/detector.py
import logging import torch import torch.nn as nn from abc import ABC, abstractmethod log = logging.getLogger(__name__) GPU_COUNT = torch.cuda.device_count() class Detector(ABC): def __init__(self, lr=0.001): self.lr = lr self._model = None self._optimizer = None self._criterion = nn.CrossEntropyLoss() @property def model(self): return self._model @property def optimizer(self): return self._optimizer @property def criterion(self): return self._criterion @abstractmethod def init_model(self, char_vocab, hidden_size, n_domain_type, n_layers): pass @abstractmethod def train_model(self, training_data, labels, batch_size=1000, epochs=1, train_size=0.7): pass @abstractmethod def predict(self, epoch, train_dataset): pass def load_model(self, file_path): """ This function load already saved model and sets cuda parameters. :param file_path: File path of a model to be loaded. :type file_path: string """ model = torch.load(file_path) model.eval() self._model = model self._set_model2cuda() self._set_optimizer() def save_model(self, file_path): """ This function saves model to a given location. :param file_path: File path of a model to be saved. :type file_path: string """ torch.save(self.model, file_path) def _save_checkpoint(self, checkpoint, file_path): torch.save(checkpoint, file_path) log.info("Pretrained model checkpoint saved to location: '{}'".format(file_path)) def _set_parallelism(self): if GPU_COUNT > 1: log.info("CUDA device count: {}".format(GPU_COUNT)) self._model = nn.DataParallel(self.model) self._set_model2cuda() else: self._set_model2cuda() def _set_optimizer(self): self._optimizer = torch.optim.RMSprop( self.model.parameters(), self.lr, weight_decay=0.0 ) def _set_model2cuda(self): if torch.cuda.is_available(): log.info("Found GPU's now setting up cuda for the model") self.model.cuda() def leverage_model(self, model): """This function leverages model by setting parallelism parameters. :param model: Model instance. :type model: RNNClassifier """ model.eval() self._model = model self._set_parallelism() self._set_optimizer() def _get_unwrapped_model(self): if GPU_COUNT > 1: model = self.model.module else: model = self.model return model
2,728
25.495146
92
py
clx-branch-23.04
clx-branch-23.04/python/clx/analytics/perfect_hash.py
import numpy as np import argparse np.random.seed(1243342) PRIME = np.uint64(281474976710677) # Coefficients ranges for inner hash - This are important to set to be # large so that we have randomness in the bottom bits when modding A_SECOND_LEVEL_POW = np.uint8(48) B_SECOND_LEVEL_POW = np.uint8(7) A_LBOUND_SECOND_LEVEL_HASH = 2**16 A_HBOUND_SECOND_LEVEL_HASH = 2**A_SECOND_LEVEL_POW B_LBOUND_SECOND_LEVEL_HASH = 0 B_HBOUND_SECOND_LEVEL_HASH = 2**B_SECOND_LEVEL_POW # Extremely generous and should not ever happen. This limit is imposed # To ensure we can bit pack all the information needed for the bin hash # functions - a, b and table size MAX_SIZE_FOR_INITIAL_BIN = 2**8 - 1 #Shifts for bit packing A_SECOND_LEVEL_SHIFT_AMT = np.uint8(64 - A_SECOND_LEVEL_POW) B_SECOND_LEVEL_SHIFT_AMT = np.uint8(64 - A_SECOND_LEVEL_POW - B_SECOND_LEVEL_POW) BITS_FOR_INNER_TABLE_SIZE = np.uint8(8) NOT_FOUND = -1 def sdbm_hash(string): hv = 0 mask = (1 << 48) - 1 for c in string: hv = ord(c) + (hv << 6) + (hv << 16) - hv hv &= mask return hv def hash_func(k, a, b, size): k = np.uint64(k) a = np.uint64(a) b = np.uint64(b) size = np.uint64(size) return ((a*k + b) % PRIME) % size def longest_bin_length(bins): return len(max(bins, key=len)) def make_bins(data, num_bins, a, b): h = lambda k: hash_func(k, a, b, num_bins) bins = [[] for i in range(num_bins)] for item in data: bins[h(item)].append(item) return bins def new_bin_length(orig_length, compact): return int(orig_length) if compact else orig_length**2 def get_space_util(bins, init_bins, compact): return sum(new_bin_length(len(b), compact) for b in bins) + 2*init_bins def pick_initial_a_b(data, max_constant, init_bins, compact): while True: a = np.random.randint(2**12, 2 ** 15) b = np.random.randint(2**12, 2 ** 15) bins = make_bins(data, init_bins, a, b) score = get_space_util(bins, init_bins, compact) / len(data) longest = new_bin_length(longest_bin_length(bins), compact) if score <= max_constant and longest <= MAX_SIZE_FOR_INITIAL_BIN: print("Attempting to build table using {:.6f}n space".format(score)) print("Longest bin was {}".format(longest)) break return bins, a, b def find_hash_for_internal(hash_bin, compact): if not hash_bin: return [[], 0, 0] new_length = new_bin_length(len(hash_bin), compact) while True: a = np.random.randint(A_LBOUND_SECOND_LEVEL_HASH, A_HBOUND_SECOND_LEVEL_HASH) b = np.random.randint(B_LBOUND_SECOND_LEVEL_HASH, B_HBOUND_SECOND_LEVEL_HASH) bins = make_bins(hash_bin, new_length, a, b) max_length = len(max(bins, key=len)) if max_length == 1: bins = [b[0] if b else 0 for b in bins] return bins, a, b def perfect_hash(integers, max_constant, compact): num_top_level_bins = len(integers)//4 init_bins, init_a, init_b = pick_initial_a_b(integers, max_constant, num_top_level_bins, compact) flattened_bins = [] internal_table_coeffs = np.zeros(shape=[num_top_level_bins], dtype=np.uint64) offset_into_flattened_table = np.zeros(shape=[num_top_level_bins + 1], dtype=np.uint64) max_bin_length = 0 for i, b in enumerate(init_bins): print("Processing bin", i, "size", len(b)) internal_table, coeff_a, coeff_b = find_hash_for_internal(b, compact) bin_length = len(internal_table) max_bin_length = max(bin_length, max_bin_length) internal_table_coeffs[i] = coeff_a << A_SECOND_LEVEL_SHIFT_AMT | coeff_b << B_SECOND_LEVEL_SHIFT_AMT | bin_length offset_into_flattened_table[i + 1] = offset_into_flattened_table[i] + bin_length flattened_bins.extend(internal_table) print("Final table size {} elements compared to {} for original". format(len(flattened_bins), len(integers))) print("Max bin length was", max_bin_length) return init_a, init_b, num_top_level_bins, flattened_bins, internal_table_coeffs, offset_into_flattened_table def pack_keys_and_values(flattened_hash_table, original_dict): for i in range(len(flattened_hash_table)): if flattened_hash_table[i] in original_dict: value = original_dict[flattened_hash_table[i]] flattened_hash_table[i] <<= 16 flattened_hash_table[i] |= value def load_vocab_dict(path): vocab = {} with open(path, mode="r") as f: counter = 0 for line in f: vocab[line.strip()] = counter counter += 1 return vocab def hash_vocab(path, store_path, compact, unk_tok="[UNK]", first_token="[CLS]", sep_token="[SEP]"): vocab = load_vocab_dict(path) keys = list(map(sdbm_hash, vocab.keys())) hashed_vocab = {sdbm_hash(key) : value for key, value in vocab.items()} assert len(hashed_vocab) == len(vocab), "Collision occurred and only sdbm token hash current supported :(. \ Can be extended to use random hashes if needed" outer_a, outer_b, num_outer_bins, hash_table, inner_table_coeffs, offsets_into_ht = perfect_hash(keys, 10, compact) pack_keys_and_values(hash_table, hashed_vocab) store_func(store_path, outer_a, outer_b, num_outer_bins, hash_table, inner_table_coeffs, offsets_into_ht, vocab[unk_tok], vocab[first_token], vocab[sep_token]) for key, value in hashed_vocab.items(): val = retrieve(key, outer_a, outer_b, num_outer_bins, hash_table, inner_table_coeffs, offsets_into_ht) assert val == value, "Incorrect value found. Got {} expected {}".format(val, value) print("All present tokens return correct value.") def store_func(out_name, outer_a, outer_b, num_outer_bins, hash_table, inner_table_coeffs, offsets_into_ht, unk_tok_id, first_token_id, sep_token_id): with open(out_name, mode="w+") as f: f.write("{}\n".format(outer_a)) f.write("{}\n".format(outer_b)) f.write("{}\n".format(num_outer_bins)) f.writelines("{} {}\n".format(coeff, offset) for coeff, offset in zip(inner_table_coeffs, offsets_into_ht)) f.write("{}\n".format(len(hash_table))) f.writelines("{}\n".format(kv) for kv in hash_table) f.writelines("{}\n".format(tok_id) for tok_id in [unk_tok_id, first_token_id, sep_token_id]) def retrieve(k, outer_a, outer_b, num_outer_bins, hash_table, inner_table_coeffs, offsets_into_ht): bin_hash = hash_func(k, outer_a, outer_b, num_outer_bins) start_offset_in_ht = offsets_into_ht[bin_hash] inner_table_values = inner_table_coeffs[bin_hash] one = np.uint64(1) inner_a = inner_table_values >> A_SECOND_LEVEL_SHIFT_AMT inner_b = (inner_table_values >> B_SECOND_LEVEL_SHIFT_AMT) & ((one << B_SECOND_LEVEL_POW) - one) size = inner_table_values & ((one << BITS_FOR_INNER_TABLE_SIZE) - one) inner_offset = hash_func(k, inner_a, inner_b, size) kv = hash_table[start_offset_in_ht + inner_offset] key, value = kv >> 16, kv & ((1 << 16) - 1) indicator = key == k return indicator*value + (not indicator)*NOT_FOUND def sdbm_pop(h, last_val): mod_inverse = 24320495251391 mask = (1 << 48) - 1 return ( ((mod_inverse * h) & mask) - ((mod_inverse * last_val) & mask) & mask ) if __name__ == "__main__": parser = argparse.ArgumentParser(description="Construct a perfect hash table for the given vocabulary file") parser.add_argument("--vocab", "-v", required=True, dest="vocab", type=str, help="The path to the bert vocabulary file. Normally called vocab.txt") parser.add_argument("--output", "-o", required=True, dest="output", type=str, help="The location to store the output") parser.add_argument("--compact", action="store_true", dest="compact", help="If set, minimizes space at the expense of longer preprocessing.") parser.set_defaults(compact=False) ns = parser.parse_args() hash_vocab(ns.vocab, ns.output, ns.compact)
7,731
34.145455
149
py
clx-branch-23.04
clx-branch-23.04/python/clx/analytics/anomaly_detection.py
import cudf import cuml def dbscan(feature_dataframe, min_samples=3, eps=0.3): """ Pass a feature dataframe to this function to detect anomalies in your feature dataframe. This function uses ``cuML`` DBSCAN to detect anomalies and outputs associated labels 0,1,-1. Parameters ---------- :param feature_dataframe: Feature dataframe to be used for clustering :type feature_dataframe: cudf.DataFrame :param min_samples: Minimum samples to use for dbscan :type min_samples: int :param eps: Max distance to use for dbscan :type eps: float Examples -------- >>> import cudf >>> import clx.features >>> import clx.analytics.anomaly_detection >>> df = cudf.DataFrame( >>> { >>> "time": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14], >>> "user": ["u1","u1","u1","u1","u1","u1","u1","u1","u1","u1","u5","u4","u2","u3"], >>> "computer": ["c1","c2","c3","c1","c2","c3","c1","c1","c2","c3","c1","c1","c5","c6"], >>> } >>> ) >>> feature_df = clx.features.frequency(df, entity_id="user", feature_id="computer") >>> labels = clx.analytics.anomaly_detection.dbscan(feature_df, min_samples=2, eps=0.5) >>> labels 0 -1 1 -1 2 -1 dtype: int32 """ dbscan = cuml.cluster.DBSCAN(eps=eps, min_samples=min_samples) dbscan.fit(feature_dataframe) # return anomalies only labels = cudf.Series(dbscan.labels_) anomalies = labels[labels == -1] return anomalies
1,563
33.755556
147
py
clx-branch-23.04
clx-branch-23.04/python/clx/analytics/__init__.py
0
0
0
py
clx-branch-23.04
clx-branch-23.04/python/clx/analytics/loda.py
import cupy as cp class Loda: """ Anomaly detection using Lightweight Online Detector of Anomalies (LODA). LODA detects anomalies in a dataset by computing the likelihood of data points using an ensemble of one-dimensional histograms. :param n_bins: Number of bins for each histogram. If None a heuristic is used to compute the number of bins. :type n_bins: int :param n_random_cuts: Number of projection to use. :type n_random_cuts: int """ def __init__(self, n_bins=None, n_random_cuts=100): self._n_bins = n_bins self._n_random_cuts = n_random_cuts self._weights = cp.ones(n_random_cuts) / n_random_cuts self._projections = None self._histograms = None self._limits = None def fit(self, train_data): """ Fit training data and construct histograms. :param train_data: NxD training sample :type train_data: cupy.ndarray Examples -------- >>> from clx.analytics.loda import Loda >>> import cupy as cp >>> x = cp.random.randn(100,5) # 5-D multivariate synthetic dataset >>> loda_ad = Loda(n_bins=None, n_random_cuts=100) >>> loda_ad.fit(x) """ nrows, n_components = train_data.shape if not self._n_bins: self._n_bins = int(1 * (nrows ** 1) * (cp.log(nrows) ** -1)) n_nonzero_components = cp.sqrt(n_components) n_zero_components = n_components - cp.int(n_nonzero_components) self._projections = cp.random.randn(self._n_random_cuts, n_components) self._histograms = cp.zeros([self._n_random_cuts, self._n_bins]) self._limits = cp.zeros((self._n_random_cuts, self._n_bins + 1)) for i in range(self._n_random_cuts): rands = cp.random.permutation(n_components)[:n_zero_components] self._projections[i, rands] = 0. projected_data = self._projections[i, :].dot(train_data.T) self._histograms[i, :], self._limits[i, :] = cp.histogram( projected_data, bins=self._n_bins, density=False) self._histograms[i, :] += 1e-12 self._histograms[i, :] /= cp.sum(self._histograms[i, :]) def score(self, input_data): """ Calculate anomaly scores using negative likelihood across n_random_cuts histograms. :param input_data: NxD training sample :type input_data: cupy.ndarray Examples -------- >>> from clx.analytics.loda import Loda >>> import cupy as cp >>> x = cp.random.randn(100,5) # 5-D multivariate synthetic dataset >>> loda_ad = Loda(n_bins=None, n_random_cuts=100) >>> loda_ad.fit(x) >>> loda_ad.score(x) array([0.04295848, 0.02853553, 0.04587308, 0.03750692, 0.05050418, 0.02671958, 0.03538646, 0.05606504, 0.03418612, 0.04040502, 0.03542846, 0.02801463, 0.04884918, 0.02943411, 0.02741364, 0.02702433, 0.03064191, 0.02575712, 0.03957355, 0.02729784, ... 0.03943715, 0.02701243, 0.02880341, 0.04086408, 0.04365477]) """ if cp.ndim(input_data) < 2: input_data = input_data.reshape(1, -1) pred_scores = cp.zeros([input_data.shape[0], 1]) for i in range(self._n_random_cuts): projected_data = self._projections[i, :].dot(input_data.T) inds = cp.searchsorted(self._limits[i, :self._n_bins - 1], projected_data, side='left') pred_scores[:, 0] += -self._weights[i] * cp.log( self._histograms[i, inds]) pred_scores /= self._n_random_cuts return pred_scores.ravel() def explain(self, anomaly, scaled=True): """ Explain anomaly based on contributions (t-scores) of each feature across histograms. :param anomaly: selected anomaly from input dataset :type anomaly: cupy.ndarray :param scaled: set to scale output feature importance scores :type scaled: boolean Examples -------- >>> loda_ad.explain(x[5]) # x[5] is found anomaly array([[1. ], [0. ], [0.69850349], [0.91081035], [0.78774349]]) """ if cp.ndim(anomaly) < 2: anomaly = anomaly.reshape(1, -1) ranked_feature_importance = cp.zeros([anomaly.shape[1], 1]) for feature in range(anomaly.shape[1]): # find all projections without the feature j and with feature j index_selected_feature = cp.where( self._projections[:, feature] != 0)[0] index_not_selected_feature = cp.where( self._projections[:, feature] == 0)[0] scores_with_feature = self._instance_score( anomaly, index_selected_feature) scores_without_feature = self._instance_score( anomaly, index_not_selected_feature) ranked_feature_importance[feature, 0] = self._t_test( scores_with_feature, scores_without_feature) if scaled: assert cp.max(ranked_feature_importance) != cp.min( ranked_feature_importance) normalized_score = (ranked_feature_importance - cp.min( ranked_feature_importance)) / ( cp.max(ranked_feature_importance) - cp.min( ranked_feature_importance)) return normalized_score else: return ranked_feature_importance def _instance_score(self, x, projection_index): """ Return scores from selected projection index. x (cupy.ndarray) : D x 1 feature instance. """ if cp.ndim(x) < 2: x = x.reshape(1, -1) pred_scores = cp.zeros([x.shape[0], len(projection_index)]) for i in projection_index: projected_data = self._projections[i, :].dot(x.T) inds = cp.searchsorted(self._limits[i, :self._n_bins - 1], projected_data, side='left') pred_scores[:, i] = -self._weights[i] * cp.log( self._histograms[i, inds]) return pred_scores def _t_test(self, with_sample, without_sample): """ compute one-tailed two-sample t-test with a test statistics according to t_j: \frac{\mu_j - \bar{\mu_j}}{\sqrt{\frac{s^2_j}{\norm{I_j}} + \frac{\bar{s^2_j}}{\norm{\bar{I_j}}}}} """ return (cp.mean(with_sample) - cp.mean(without_sample)) /\ cp.sqrt(cp.var(with_sample)**2 / len(with_sample) + cp.var(without_sample)**2 / len(without_sample)) def save_model(self, file_path): """ This function save model to given location. :param file_path: File path to save model. :type file_path: string """ cp.savez_compressed(file_path, histograms=self._histograms, limits=self._limits, projections=self._projections) @classmethod def load_model(cls, file_path): """ This function load already saved model and sets cuda parameters. :param file_path: File path of a model to load. :type filel_path: string """ model = cp.load(file_path) histograms = model['histograms'] projections = model['projections'] limits = model['limits'] n_random_cuts = histograms.shape[0] n_bins = histograms.shape[1] loda = Loda(n_random_cuts=n_random_cuts, n_bins=n_bins) loda._histograms = histograms loda._limits = limits loda._projections = projections return loda
7,680
39.856383
112
py
clx-branch-23.04
clx-branch-23.04/python/clx/analytics/dga_detector.py
import cudf import torch import logging from tqdm import trange from torch.utils.dlpack import from_dlpack from clx.utils.data import utils from clx.analytics.detector import Detector from clx.utils.data.dataloader import DataLoader from clx.analytics.dga_dataset import DGADataset from clx.analytics.model.rnn_classifier import RNNClassifier from cuml.model_selection import train_test_split log = logging.getLogger(__name__) class DGADetector(Detector): """ This class provides multiple functionalities such as build, train and evaluate the RNNClassifier model to distinguish legitimate and DGA domain names. """ def init_model(self, char_vocab=128, hidden_size=100, n_domain_type=2, n_layers=3): """This function instantiates RNNClassifier model to train. And also optimizes to scale it and keep running on parallelism. :param char_vocab: Vocabulary size is set to 128 ASCII characters. :type char_vocab: int :param hidden_size: Hidden size of the network. :type hidden_size: int :param n_domain_type: Number of domain types. :type n_domain_type: int :param n_layers: Number of network layers. :type n_layers: int """ if self.model is None: model = RNNClassifier(char_vocab, hidden_size, n_domain_type, n_layers) self.leverage_model(model) def load_checkpoint(self, file_path): """ This function load already saved model checkpoint and sets cuda parameters. :param file_path: File path of a model checkpoint to be loaded. :type file_path: string """ checkpoint = torch.load(file_path) model = RNNClassifier( checkpoint["input_size"], checkpoint["hidden_size"], checkpoint["output_size"], checkpoint["n_layers"], ) model.load_state_dict(checkpoint["state_dict"]) super().leverage_model(model) def save_checkpoint(self, file_path): """ This function saves model checkpoint to given location. :param file_path: File path to save model checkpoint. :type file_path: string """ model = self._get_unwrapped_model() checkpoint = { "state_dict": model.state_dict(), "input_size": model.input_size, "hidden_size": model.hidden_size, "n_layers": model.n_layers, "output_size": model.output_size, } super()._save_checkpoint(checkpoint, file_path) def train_model( self, train_data, labels, batch_size=1000, epochs=5, train_size=0.7, truncate=100 ): """This function is used for training RNNClassifier model with a given training dataset. It returns total loss to determine model prediction accuracy. :param train_data: Training data :type train_data: cudf.Series :param labels: labels data :type labels: cudf.Series :param batch_size: batch size :type batch_size: int :param epochs: Number of epochs for training :type epochs: int :param train_size: Training size for splitting training and test data :type train_size: int :param truncate: Truncate string to n number of characters. :type truncate: int Examples -------- >>> from clx.analytics.dga_detector import DGADetector >>> dd = DGADetector() >>> dd.init_model() >>> dd.train_model(train_data, labels) 1.5728906989097595 """ log.info("Initiating model training ...") log.info('Truncate domains to width: {}'.format(truncate)) self.model.train() train_dataloader, test_dataloader = self._preprocess_data( train_data, labels, batch_size, train_size, truncate ) for _ in trange(epochs, desc="Epoch"): total_loss = 0 i = 0 for df in train_dataloader.get_chunks(): domains_len = df.shape[0] if domains_len > 0: types_tensor = self._create_types_tensor(df["type"]) df = df.drop(["type", "domain"], axis=1) input, seq_lengths = self._create_variables(df) model_result = self.model(input, seq_lengths) loss = self._get_loss(model_result, types_tensor) total_loss += loss i = i + 1 if i % 10 == 0: log.info( "[{}/{} ({:.0f}%)]\tLoss: {:.2f}".format( i * domains_len, train_dataloader.dataset_len, 100.0 * i * domains_len / train_dataloader.dataset_len, total_loss / i * domains_len, ) ) self.evaluate_model(test_dataloader) def predict(self, domains, probability=False, truncate=100): """This function accepts cudf series of domains as an argument to classify domain names as benign/malicious and returns the learned label for each object in the form of cudf series. :param domains: List of domains. :type domains: cudf.Series :return: Predicted results with respect to given domains. :rtype: cudf.Series :param truncate: Truncate string to n number of characters. :type truncate: int Examples -------- >>> dd.predict(['nvidia.com', 'dgadomain']) 0 0.010 1 0.924 Name: dga_probability, dtype: decimal """ log.debug("Initiating model inference ...") self.model.eval() df = cudf.DataFrame({"domain": domains}) log.debug('Truncate domains to width: {}'.format(truncate)) df['domain'] = df['domain'].str.slice_replace(truncate, repl='') temp_df = utils.str2ascii(df, 'domain') # Assigning sorted domains index to return learned labels as per the given input order. df.index = temp_df.index df["domain"] = temp_df["domain"] temp_df = temp_df.drop("domain", axis=1) input, seq_lengths = self._create_variables(temp_df) del temp_df model_result = self.model(input, seq_lengths) if probability: model_result = model_result[:, 0] preds = torch.sigmoid(model_result) preds = preds.view(-1).tolist() df["preds"] = preds else: preds = model_result.data.max(1, keepdim=True)[1] preds = preds.view(-1).tolist() df["preds"] = preds df = df.sort_index() return df["preds"] def _create_types_tensor(self, type_series): """Create types tensor variable in the same order of sequence tensor""" types = type_series.values_host types_tensor = torch.LongTensor(types) if torch.cuda.is_available(): types_tensor = self._set_var2cuda(types_tensor) return types_tensor def _create_variables(self, df): """ Creates vectorized sequence for given domains and wraps around cuda for parallel processing. """ seq_len_arr = df["len"].values_host df = df.drop("len", axis=1) seq_len_tensor = torch.LongTensor(seq_len_arr) seq_tensor = self._df2tensor(df) # Return variables # DataParallel requires everything to be a Variable if torch.cuda.is_available(): seq_tensor = self._set_var2cuda(seq_tensor) seq_len_tensor = self._set_var2cuda(seq_len_tensor) return seq_tensor, seq_len_tensor def _df2tensor(self, ascii_df): """ Converts gdf -> dlpack tensor -> torch tensor """ dlpack_ascii_tensor = ascii_df.to_dlpack() seq_tensor = from_dlpack(dlpack_ascii_tensor).long() return seq_tensor def evaluate_model(self, dataloader): """This function evaluates the trained model to verify it's accuracy. :param dataloader: Instance holds preprocessed data. :type dataloader: DataLoader :return: Model accuracy :rtype: decimal Examples -------- >>> dd = DGADetector() >>> dd.init_model() >>> dd.evaluate_model(dataloader) Evaluating trained model ... Test set accuracy: 3/4 (0.75) """ log.info("Evaluating trained model ...") correct = 0 for df in dataloader.get_chunks(): target = self._create_types_tensor(df["type"]) df = df.drop(["type", "domain"], axis=1) input, seq_lengths = self._create_variables(df) output = self.model(input, seq_lengths) pred = output.data.max(1, keepdim=True)[1] correct += pred.eq(target.data.view_as(pred)).cpu().sum() accuracy = float(correct) / dataloader.dataset_len log.info( "Test set accuracy: {}/{} ({})\n".format( correct, dataloader.dataset_len, accuracy ) ) return accuracy def _get_loss(self, model_result, types_tensor): loss = self.criterion(model_result, types_tensor) self.model.zero_grad() loss.backward() self.optimizer.step() return loss.item() def _set_var2cuda(self, tensor): """ Set variable to cuda. """ return tensor.cuda() def _preprocess_data(self, train_data, labels, batch_size, train_size, truncate): train_gdf = cudf.DataFrame() train_gdf["domain"] = train_data train_gdf["type"] = labels domain_train, domain_test, type_train, type_test = train_test_split( train_gdf, "type", train_size=train_size ) test_df = self._create_df(domain_test, type_test) train_df = self._create_df(domain_train, type_train) test_dataset = DGADataset(test_df, truncate) train_dataset = DGADataset(train_df, truncate) test_dataloader = DataLoader(test_dataset, batchsize=batch_size) train_dataloader = DataLoader(train_dataset, batchsize=batch_size) return train_dataloader, test_dataloader def _create_df(self, domain_df, type_series): df = cudf.DataFrame() df["domain"] = domain_df["domain"].reset_index(drop=True) df["type"] = type_series.reset_index(drop=True) return df
10,504
38.197761
189
py
clx-branch-23.04
clx-branch-23.04/python/clx/analytics/multiclass_sequence_classifier.py
import logging import cudf from cudf.core.subword_tokenizer import SubwordTokenizer import cupy import torch import torch.nn as nn from torch.utils.dlpack import to_dlpack from clx.analytics.sequence_classifier import SequenceClassifier from clx.utils.data.dataloader import DataLoader from clx.utils.data.dataset import Dataset from transformers import AutoModelForSequenceClassification log = logging.getLogger(__name__) class MulticlassSequenceClassifier(SequenceClassifier): """ Sequence Classifier using BERT. This class provides methods for training/loading BERT models, evaluation and prediction. """ def init_model(self, model_or_path, num_labels): """ Load model from huggingface or locally saved model. :param model_or_path: huggingface pretrained model name or directory path to model :type model_or_path: str :param num_labels: number of labels used only for multiclass classification :type num_labels: int Examples -------- >>> from clx.analytics.multiclass_sequence_classifier import MulticlassSequenceClassifier >>> sc = MulticlassSequenceClassifier() >>> sc.init_model("bert-base-uncased", num_labels=4) # huggingface pre-trained model >>> sc.init_model(model_path, num_labels=4) # locally saved model """ self._model = AutoModelForSequenceClassification.from_pretrained(model_or_path, num_labels=num_labels) if torch.cuda.is_available(): self._device = torch.device("cuda") self._model.cuda() self._model = nn.DataParallel(self._model) else: self._device = torch.device("cpu") self._tokenizer = SubwordTokenizer(self._hashpath, do_lower_case=True) def predict(self, input_data, max_seq_len=128, batch_size=32): """ Predict the class with the trained model :param input_data: input text data for prediction :type input_data: cudf.Series :param max_seq_len: Limits the length of the sequence returned by tokenizer. If tokenized sentence is shorter than max_seq_len, output will be padded with 0s. If the tokenized sentence is longer than max_seq_len it will be truncated to max_seq_len. :type max_seq_len: int :param batch_size: batch size :type batch_size: int :param threshold: results with probabilities higher than this will be labeled as positive :type threshold: float :return: predictions, probabilities: predictions are labels (0 or 1) based on minimum threshold :rtype: cudf.Series, cudf.Series Examples -------- >>> from cuml.preprocessing.model_selection import train_test_split >>> emails_train, emails_test, labels_train, labels_test = train_test_split(train_emails_df, 'label', train_size=0.8) >>> sc.train_model(emails_train, labels_train) >>> predictions = sc.predict(emails_test) """ predict_gdf = cudf.DataFrame() predict_gdf["text"] = input_data predict_dataset = Dataset(predict_gdf) predict_dataloader = DataLoader(predict_dataset, batchsize=batch_size) preds = cudf.Series() self._model.eval() for df in predict_dataloader.get_chunks(): b_input_ids, b_input_mask = self._bert_uncased_tokenize(df["text"], max_seq_len) with torch.no_grad(): logits = self._model( b_input_ids, token_type_ids=None, attention_mask=b_input_mask )[0] logits = logits.type(torch.DoubleTensor).to(self._device) logits = cupy.fromDlpack(to_dlpack(logits)) b_preds = cupy.argmax(logits, axis=1).flatten() b_preds = cudf.Series(b_preds) preds = preds.append(b_preds) return preds
3,867
38.876289
256
py
clx-branch-23.04
clx-branch-23.04/python/clx/analytics/model/rnn_classifier.py
# Original code at https://github.com/spro/practical-pytorch import torch import torch.nn as nn from torch.nn.utils.rnn import pack_padded_sequence DROPOUT = 0.0 class RNNClassifier(nn.Module): def __init__( self, input_size, hidden_size, output_size, n_layers, bidirectional=True ): super(RNNClassifier, self).__init__() self.input_size = input_size self.hidden_size = hidden_size self.output_size = output_size self.n_layers = n_layers self.n_directions = int(bidirectional) + 1 self.embedding = nn.Embedding(input_size, hidden_size) self.gru = nn.GRU( hidden_size, hidden_size, n_layers, dropout=DROPOUT, bidirectional=bidirectional, ) self.fc = nn.Linear(hidden_size, output_size) def forward(self, input, seq_lengths): # Note: we run this all at once (over the whole input sequence) # input shape: B x S (input size) # transpose to make S(sequence) x B (batch) input = input.t() batch_size = input.size(1) # Make a hidden hidden = self._init_hidden(batch_size) # Embedding S x B -> S x B x I (embedding size) embedded = self.embedding(input) # Pack them up nicely gru_input = pack_padded_sequence(embedded, seq_lengths.data.cpu().numpy()) # To compact weights again call flatten_parameters(). self.gru.flatten_parameters() output, hidden = self.gru(gru_input, hidden) # output = self.dropout(output) # Use the last layer output as FC's input # No need to unpack, since we are going to use hidden fc_output = self.fc(hidden[-1]) return fc_output def _init_hidden(self, batch_size): hidden = torch.zeros( self.n_layers * self.n_directions, batch_size, self.hidden_size ) # creating variable if torch.cuda.is_available(): return hidden.cuda() else: return hidden
2,067
31.3125
82
py
clx-branch-23.04
clx-branch-23.04/python/clx/analytics/model/__init__.py
0
0
0
py
clx-branch-23.04
clx-branch-23.04/python/clx/analytics/model/tabular_model.py
# Original code at https://github.com/spro/practical-pytorch import torch import torch.nn as nn class TabularModel(nn.Module): "Basic model for tabular data" def __init__(self, emb_szs, n_cont, out_sz, layers, drops, emb_drop, use_bn, is_reg, is_multi): super().__init__() self.embeds = nn.ModuleList([nn.Embedding(ni, nf) for ni, nf in emb_szs]) self.emb_drop = nn.Dropout(emb_drop) self.bn_cont = nn.BatchNorm1d(n_cont) n_emb = sum(e.embedding_dim for e in self.embeds) self.n_emb, self.n_cont = n_emb, n_cont sizes = [n_emb + n_cont] + layers + [out_sz] actns = [nn.ReLU(inplace=True)] * (len(sizes) - 2) + [None] layers = [] for i, (n_in, n_out, dp, act) in enumerate(zip(sizes[:-1], sizes[1:], [0.] + drops, actns)): layers += self._bn_drop_lin(n_in, n_out, bn=use_bn and i != 0, p=dp, actn=act) self.layers = nn.Sequential(*layers) def forward(self, x_cat, x_cont): if self.n_emb != 0: x = [e(x_cat[:, i]) for i, e in enumerate(self.embeds)] x = torch.cat(x, 1) x = self.emb_drop(x) if self.n_cont != 0: if self.n_cont == 1: x_cont = x_cont.unsqueeze(1) x_cont = self.bn_cont(x_cont) x = torch.cat([x, x_cont], 1) if self.n_emb != 0 else x_cont x = self.layers(x) return x.squeeze() def _bn_drop_lin(self, n_in, n_out, bn, p, actn): "Sequence of batchnorm (if `bn`), dropout (with `p`) and linear (`n_in`,`n_out`) layers followed by `actn`." layers = [nn.BatchNorm1d(n_in)] if bn else [] if p != 0: layers.append(nn.Dropout(p)) layers.append(nn.Linear(n_in, n_out)) if actn is not None: layers.append(actn) return layers
1,858
38.553191
116
py
clx-branch-23.04
clx-branch-23.04/python/clx/utils/__init__.py
0
0
0
py
clx-branch-23.04
clx-branch-23.04/python/clx/utils/data/dataloader.py
# Copyright (c) 2020, NVIDIA CORPORATION. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging log = logging.getLogger(__name__) class DataLoader(object): """ Wrapper class is used to return dataframe partitions based on batchsize. """ def __init__(self, dataset, batchsize=1000): """Constructor to create dataframe partitions. :param df: Input dataframe. :type df: cudf.DataFrame :param batch_size: Number of records in the dataframe. :type batch_size: int """ self.__dataset = dataset self.__batchsize = batchsize @property def dataset_len(self): return self.__dataset.length @property def dataset(self): return self.__dataset def get_chunks(self): """ A generator function that yields each chunk of original input dataframe based on batchsize :return: Partitioned dataframe. :rtype: cudf.DataFrame """ prev_chunk_offset = 0 while prev_chunk_offset < self.__dataset.length: curr_chunk_offset = prev_chunk_offset + self.__batchsize chunk = self.__dataset.data[prev_chunk_offset:curr_chunk_offset:1] prev_chunk_offset = curr_chunk_offset yield chunk
1,779
31.363636
102
py
clx-branch-23.04
clx-branch-23.04/python/clx/utils/data/utils.py
# Copyright (c) 2020, NVIDIA CORPORATION. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import cudf import logging log = logging.getLogger(__name__) def str2ascii(df, col_name): """ This function sorts domain name entries in desc order based on the length of domain and converts domain name to ascii characters. :param df: Domains which requires conversion. :type df: cudf.DataFrame :param col_name: Name of the column that needs to be transformed. :type col_name: str :return: Ascii character converted information. :rtype: cudf.DataFrame """ df["len"] = df[col_name].str.len() df = df.sort_values("len", ascending=False) split_ser = df[col_name].str.findall("[\w\W\d\D\s\S]") split_df = split_ser.to_frame() split_df = cudf.DataFrame(split_df[col_name].to_arrow().to_pylist()) columns_cnt = len(split_df.columns) # Replace null's with ^. split_df = split_df.fillna("^") temp_df = cudf.DataFrame() for col in range(0, columns_cnt): temp_df[col] = split_df[col].str.code_points() del split_df # Replace ^ ascii value 94 with 0. temp_df = temp_df.replace(94, 0) temp_df.index = df.index temp_df["len"] = df["len"] if "type" in df.columns: temp_df["type"] = df["type"] temp_df[col_name] = df[col_name] return temp_df
1,846
33.203704
133
py
clx-branch-23.04
clx-branch-23.04/python/clx/utils/data/dataset.py
# Copyright (c) 2020, NVIDIA CORPORATION. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class Dataset(object): def __init__(self, df): self._df = df.reset_index(drop=True) self._dataset_len = self._df.shape[0] @property def length(self): """ Returns dataframe length """ return self._dataset_len @property def data(self): """ Retruns dataframe """ return self._df
968
27.5
74
py
clx-branch-23.04
clx-branch-23.04/python/clx/utils/data/__init__.py
0
0
0
py
clx-branch-23.04
clx-branch-23.04/python/clx/heuristics/ports.py
# Copyright (c) 2019, NVIDIA CORPORATION. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import cudf import os class Resources: _instance = None @staticmethod def get_instance(): if Resources._instance is None: Resources() return Resources._instance def __init__(self): if Resources._instance is not None: raise Exception("This is a singleton class") else: Resources._instance = self Resources._instance._iana_lookup_df = self._load_iana_lookup_df() @property def iana_lookup_df(self): return self._iana_lookup_df def _load_iana_lookup_df(self): iana_path = "%s/resources/iana_port_lookup.csv" % os.path.dirname( os.path.realpath(__file__) ) colNames = ["port", "service"] colTypes = ["int64", "str"] iana_lookup_df = cudf.read_csv( iana_path, delimiter=',', names=colNames, dtype=colTypes, skiprows=1 ) iana_lookup_df = iana_lookup_df.dropna() iana_lookup_df = iana_lookup_df.groupby(["port"]).min().reset_index() return iana_lookup_df def major_ports(addr_col, port_col, min_conns=1, eph_min=10000): """Find major ports for each address. This is done by computing the mean number of connections across all ports for each address and then filters out all ports that don't cross this threshold. Also adds column for IANA service name correspondingto each port. :param addr_col: Column of addresses as strings :type addr_col: cudf.Series :param port_col: Column of corresponding port numbers as ints :type port_col: cudf.Series :param min_conns: Filter out ip:port rows that don't have at least this number of connections (default: 1) :type min_conns: int :param eph_min: Ports greater than or equal to this will be labeled as an ephemeral service (default: 10000) :type eph_min: int :return: DataFrame with columns for address, port, IANA service corresponding to port, and number of connections :rtype: cudf.DataFrame Examples -------- >>> import clx.heuristics.ports as ports >>> import cudf >>> input_addr_col = cudf.Series(["10.0.75.1","10.0.75.1","10.0.75.1","10.0.75.255","10.110.104.107", "10.110.104.107"]) >>> input_port_col = cudf.Series([137,137,7680,137,7680, 7680]) >>> ports.major_ports(input_addr_col, input_port_col, min_conns=2, eph_min=7000) addr port service conns 0 10.0.75.1 137 netbios-ns 2 1 10.110.104.107 7680 ephemeral 2 """ # Count the number of connections across each src ip-port pair gdf = cudf.DataFrame({"addr": addr_col, "port": port_col}) gdf["conns"] = 1.0 gdf = gdf.groupby(["addr", "port"], as_index=False).count() # Calculate average number of connections across all ports for each ip cnt_avg_gdf = gdf[["addr", "conns"]] cnt_avg_gdf = cnt_avg_gdf.groupby(["addr"], as_index=False).mean() cnt_avg_gdf = cnt_avg_gdf.rename(columns={"conns": "avg"}) # Merge averages to dataframe gdf = gdf.merge(cnt_avg_gdf, on=['addr'], how='left') # Filter out all ip-port pairs below average gdf = gdf[gdf.conns >= gdf.avg] if min_conns > 1: gdf = gdf[gdf.conns >= min_conns] gdf = gdf.drop(['avg'], axis=1) resources = Resources.get_instance() iana_lookup_df = resources.iana_lookup_df # Add IANA service names to node lists gdf = gdf.merge(iana_lookup_df, on=['port'], how='left') gdf.loc[gdf["port"] >= eph_min, "service"] = "ephemeral" gdf = gdf.groupby(["addr", "port", "service"], dropna=False, as_index=False, sort=True).sum() return gdf
4,278
34.957983
124
py
clx-branch-23.04
clx-branch-23.04/python/clx/heuristics/__init__.py
0
0
0
py
clx-branch-23.04
clx-branch-23.04/python/clx/workflow/splunk_alert_workflow.py
# Copyright (c) 2019, NVIDIA CORPORATION. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import clx import clx.analytics.stats import cudf from clx.workflow.workflow import Workflow from clx.parsers.splunk_notable_parser import SplunkNotableParser log = logging.getLogger(__name__) class SplunkAlertWorkflow(Workflow): def __init__( self, name, source=None, destination=None, interval="day", threshold=2.5, window=7, raw_data_col_name="_raw", ): self.interval = interval self._threshold = threshold self._window = window self._snp = SplunkNotableParser() self._raw_data_col_name = raw_data_col_name Workflow.__init__(self, name, source, destination) @property def interval(self): """Interval can be set to day or hour by which z score will be calculated""" return self._interval @interval.setter def interval(self, interval): if interval != "day" and interval != "hour": raise Exception( "interval='" + interval + "': interval must be set to 'day' or 'hour'" ) else: self._interval = interval @property def threshold(self): """Threshold by which to flag z score. Threshold will be flagged for scores >threshold or <-threshold""" return self._threshold @property def window(self): """Window by which to calculate rolling z score""" return self._window @property def raw_data_col_name(self): """Dataframe column name containing raw splunk alert data""" return self._raw_data_col_name def workflow(self, dataframe): log.debug("Processing splunk alert workflow data...") parsed_df = self._snp.parse(dataframe, self._raw_data_col_name) interval = self._interval threshold = float(self._threshold) # Create alerts dataframe alerts_gdf = parsed_df alerts_gdf["time"] = alerts_gdf["time"].astype("int") alerts_gdf = alerts_gdf.rename(columns={"search_name": "rule"}) if interval == "day": alerts_gdf[interval] = alerts_gdf.time.apply(self.__round2day) else: # hour alerts_gdf[interval] = alerts_gdf.time.apply(self.__round2hour) # Group alerts by interval and pivot table day_rule_df = ( alerts_gdf[["rule", interval, "time"]] .groupby(["rule", interval]) .count() .reset_index() ) day_rule_df.columns = ["rule", interval, "count"] day_rule_piv = self.__pivot_table( day_rule_df, interval, "rule", "count" ).fillna(0) # Calculate rolling zscore r_zscores = cudf.DataFrame() for rule in day_rule_piv.columns: x = day_rule_piv[rule] r_zscores[rule] = clx.analytics.stats.rzscore(x, self._window) # Flag z score anomalies output = self.__flag_anamolies(r_zscores, threshold) log.debug(output) return output def __flag_anamolies(self, zc_df, threshold): output_df = cudf.DataFrame() for col in zc_df.columns: if col != self._interval: temp_df = cudf.DataFrame() temp_df['time'] = zc_df.index[zc_df[col].abs() > threshold] temp_df['rule'] = col output_df = cudf.concat([output_df, temp_df]) output_df = output_df.reset_index(drop=True) return output_df # cuDF Feature request: https://github.com/rapidsai/cudf/issues/1214 def __pivot_table(self, gdf, index_col, piv_col, v_col): index_list = gdf[index_col].unique() piv_gdf = cudf.DataFrame({index_col: list(range(len(index_list)))}) piv_gdf[index_col] = index_list piv_groups = gdf[piv_col].unique() for i in range(len(piv_groups)): temp_df = gdf[gdf[piv_col] == piv_groups[i]] temp_df = temp_df[[index_col, v_col]] temp_df.columns = [index_col, piv_groups[i]] piv_gdf = piv_gdf.merge(temp_df, on=[index_col], how="left") piv_gdf = piv_gdf.set_index(index_col) piv_gdf = piv_gdf.sort_index() return piv_gdf def __round2day(self, epoch_time): return int(epoch_time / 86400) * 86400 def __round2hour(self, epoch_time): return int(epoch_time / 3600) * 3600
4,970
34.007042
112
py
clx-branch-23.04
clx-branch-23.04/python/clx/workflow/__init__.py
0
0
0
py
clx-branch-23.04
clx-branch-23.04/python/clx/workflow/netflow_workflow.py
# Copyright (c) 2019, NVIDIA CORPORATION. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging from clx.workflow.workflow import Workflow log = logging.getLogger(__name__) class NetflowWorkflow(Workflow): def workflow(self, dataframe): """TODO: Implement netflow dataframe enrichment""" log.debug("Processing netflow workflow data...") dataframe["netflow_enriched"] = "netflow_enriched" return dataframe
952
34.296296
74
py
clx-branch-23.04
clx-branch-23.04/python/clx/workflow/workflow.py
# Copyright (c) 2019, NVIDIA CORPORATION. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import functools import logging import os import time import yaml from yaml import Loader from clx.io.factory.factory import Factory from abc import ABC, abstractmethod log = logging.getLogger(__name__) class Workflow(ABC): DEFAULT_CONFIG_PATH = "/.config/clx" BACKUP_CONFIG_PATH = "/etc/clx/" CONFIG_FILE_NAME = "workflow.yaml" DEFAULT_PARAMS = ["name", "destination", "source"] def benchmark(function): """ Decorator used to capture a benchmark for a given function """ @functools.wraps(function) def wrapper(self, *args, **kwargs): start = time.time() ret = function(self, *args, **kwargs) end = time.time() runtime = end - start log.info( f"Workflow benchmark for function {function.__name__!r}: {runtime:.4f} seconds" ) return ret return wrapper def __init__(self, name, source=None, destination=None): # Initialize properties self._source = None self._destination = None self._name = name # Check to see if workflow yaml file exists. If so, set workflow configurations from file. default_filepath = self._get_default_filepath(name) backup_filepath = self._get_backup_filepath(name) if os.path.exists(default_filepath): log.info("Config file detected: {0}".format(default_filepath)) self._set_workflow_config(default_filepath) elif os.path.exists(backup_filepath): log.info("Config file detected: {0}".format(backup_filepath)) self._set_workflow_config(backup_filepath) else: log.info("No config file detected.") # If source or destination are passed in as parameters, update source and dest configurations. if source: self._source = source self._io_reader = Factory.get_reader(self._source["type"], self._source) if destination: self._destination = destination self._io_writer = Factory.get_writer( self._destination["type"], self._destination ) def _get_default_filepath(self, workflow_name): home_dir = os.getenv("HOME") default_filepath = "{home_dir}/{default_sub_dir}/{workflow_name}/{filename}".format( home_dir=home_dir, default_sub_dir=self.DEFAULT_CONFIG_PATH, workflow_name=workflow_name, filename=self.CONFIG_FILE_NAME, ) log.info("default filepath:" + default_filepath) return default_filepath def _get_backup_filepath(self, workflow_name): backup_filepath = "{backup_dir}/{workflow_name}/{filename}".format( backup_dir=self.BACKUP_CONFIG_PATH, workflow_name=workflow_name, filename=self.CONFIG_FILE_NAME, ) log.info("backup filepath:" + backup_filepath) return backup_filepath def _set_workflow_config(self, yaml_file): # Receives a yaml file path with Workflow configurations and sets appropriate values for properties in this class log.info("Setting configurations from config file {0}".format(yaml_file)) try: config = None with open(yaml_file, "r") as ymlfile: config = yaml.load(ymlfile, Loader=Loader) self._source = config["source"] self._destination = config["destination"] self._io_reader = Factory.get_reader(self._source["type"], self._source) self._io_writer = Factory.get_writer( self._destination["type"], self._destination ) # Set attributes for custom workflow properties for key in config.keys(): if key not in self.DEFAULT_PARAMS: setattr(self, key, config[key]) except Exception: log.error( "Error creating I/O reader and writer. Please check configurations in workflow config file at {0}".format( yaml_file ) ) raise @property def name(self): """Name of the workflow for logging purposes.""" return self._name @property def source(self): """ Dictionary of configuration parameters for the data source (reader) """ return self._source def set_source(self, source): """ Set source. :param source: dict of configuration parameters for data source (reader) """ self._source = source self._io_reader = Factory.get_reader(self.source["type"], self.source) @property def destination(self): """ Dictionary of configuration parameters for the data destination (writer) """ return self._destination def set_destination(self, destination): """ Set destination. :param destination: dict of configuration parameters for the destination (writer) """ self._destination = destination self._io_writer = Factory.get_writer( self.source["destination"], self.destination ) def _get_parser(self, parser_config): """TODO: Private helper function that fetches a specific parser based upon configuration""" pass def run_workflow(self): """ Run workflow. Reader (source) fetches data. Workflow implementation is executed. Workflow output is written to destination. """ log.info("Running workflow {0}.".format(self.name)) try: while ( self._io_reader.has_data ): dataframe = ( self._io_reader.fetch_data() ) enriched_dataframe = self.workflow(dataframe) if enriched_dataframe and not enriched_dataframe.empty: self._io_writer.write_data(enriched_dataframe) else: log.info("Dataframe is empty. Workflow processing skipped.") except KeyboardInterrupt: logging.info("User aborted workflow") self.stop_workflow() def stop_workflow(self): """ Close workflow. This includes calling close() method on reader (source) and writer (destination) """ log.info("Closing workflow...") self._io_reader.close() self._io_writer.close() log.info("Workflow {0} stopped.".format(self.name)) @abstractmethod def workflow(self, dataframe): """The pipeline function performs the data enrichment on the data. Subclasses must define this function. This function will return a gpu dataframe with enriched data.""" pass
7,402
35.112195
122
py
clx-branch-23.04
clx-branch-23.04/python/clx/parsers/event_parser.py
# Copyright (c) 2019, NVIDIA CORPORATION. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import cudf import logging import yaml from abc import ABC, abstractmethod log = logging.getLogger(__name__) class EventParser(ABC): """This is an abstract class for all event log parsers. :param columns: Event column names. :type columns: set(string) :param event_name: Event name :type event_name: string """ def __init__(self, columns, event_name): """Constructor method """ self._columns = columns self._event_name = event_name @property def columns(self): """List of columns that are being processed. :return: Event column names. :rtype: set(string) """ return self._columns @property def event_name(self): """Event name define type of logs that are being processed. :return: Event name :rtype: string """ return self._event_name @abstractmethod def parse(self, dataframe, raw_column): """Abstract method 'parse' triggers the parsing functionality. Subclasses are required to implement and execute any parsing pre-processing steps.""" log.info("Begin parsing of dataframe") pass def parse_raw_event(self, dataframe, raw_column, event_regex): """Processes parsing of a specific type of raw event records received as a dataframe. :param dataframe: Raw events to be parsed. :type dataframe: cudf.DataFrame :param raw_column: Raw data contained column name. :type raw_column: string :param event_regex: Required regular expressions for a given event type. :type event_regex: dict :return: parsed information. :rtype: cudf.DataFrame """ log.debug("Parsing raw events. Event type: " + self.event_name + " DataFrame shape: " + str(dataframe.shape)) parsed_gdf = cudf.DataFrame({col: [""] for col in self.columns}) parsed_gdf = parsed_gdf[:0] event_specific_columns = event_regex.keys() # Applies regex pattern for each expected output column to raw data for col in event_specific_columns: regex_pattern = event_regex.get(col) extracted_gdf = dataframe[raw_column].str.extract(regex_pattern) if not extracted_gdf.empty: parsed_gdf[col] = extracted_gdf[0] remaining_columns = list(self.columns - event_specific_columns) # Fill remaining columns with empty. for col in remaining_columns: parsed_gdf[col] = "" return parsed_gdf def filter_by_pattern(self, df, column, pattern): """Retrieve events only which satisfies given regex pattern. :param df: Raw events to be filtered. :type df: cudf.DataFrame :param column: Raw data contained column name. :type column: string :param pattern: Regex pattern to retrieve events that are required. :type pattern: string :return: filtered dataframe. :rtype: cudf.DataFrame """ df["present"] = df[column].str.contains(pattern) return df[df.present] def _load_regex_yaml(self, yaml_file): """Returns a dictionary of the regex contained in the given yaml file""" with open(yaml_file) as yaml_file: regex_dict = yaml.safe_load(yaml_file) return regex_dict
3,949
33.649123
156
py
clx-branch-23.04
clx-branch-23.04/python/clx/parsers/windows_event_parser.py
# Copyright (c) 2019, NVIDIA CORPORATION. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import os import cudf from clx.parsers.event_parser import EventParser log = logging.getLogger(__name__) class WindowsEventParser(EventParser): """This is class parses windows event logs. :param interested_eventcodes: This parameter provides flexibility to parse only interested eventcodes. :type interested_eventcodes: set(int) """ REGEX_FILE = "resources/windows_event_regex.yaml" EVENT_NAME = "windows event" def __init__(self, interested_eventcodes=None): regex_filepath = ( os.path.dirname(os.path.abspath(__file__)) + "/" + self.REGEX_FILE ) self.interested_eventcodes = interested_eventcodes self.event_regex = self._load_regex_yaml(regex_filepath) EventParser.__init__(self, self.get_columns(), self.EVENT_NAME) def parse(self, dataframe, raw_column): """Parses the Windows raw event. :param dataframe: Raw events to be parsed. :type dataframe: cudf.DataFrame :param raw_column: Raw data contained column name. :type raw_column: string :return: Parsed information. :rtype: cudf.DataFrame """ # Clean raw data to be consistent. dataframe = self.clean_raw_data(dataframe, raw_column) output_chunks = [] for eventcode in self.event_regex.keys(): pattern = "eventcode=%s" % (eventcode) input_chunk = self.filter_by_pattern(dataframe, raw_column, pattern) if not input_chunk.empty: temp = self.parse_raw_event( input_chunk, raw_column, self.event_regex[eventcode] ) if not temp.empty: output_chunks.append(temp) parsed_dataframe = cudf.concat(output_chunks) # Replace null values with empty. parsed_dataframe = parsed_dataframe.fillna("") return parsed_dataframe def clean_raw_data(self, dataframe, raw_column): """Lower casing and replacing escape characters. :param dataframe: Raw events to be parsed. :type dataframe: cudf.DataFrame :param raw_column: Raw data contained column name. :type raw_column: string :return: Clean raw information. :rtype: cudf.DataFrame """ dataframe[raw_column] = ( dataframe[raw_column] .str.lower() .str.replace("\\\\t", "") .str.replace("\\\\r", "") .str.replace("\\\\n", "|") ) return dataframe def _load_regex_yaml(self, yaml_file): event_regex = EventParser._load_regex_yaml(self, yaml_file) if self.interested_eventcodes is not None: for eventcode in self.interested_eventcodes: required_event_regex = {} if eventcode not in event_regex: raise KeyError( "Regex for eventcode %s is not available in the config file. Please choose from %s" % (eventcode, list(event_regex.keys())) ) required_event_regex[eventcode] = event_regex[eventcode] return required_event_regex return event_regex def get_columns(self): """ Get columns of windows event codes. :return: Columns of all configured eventcodes, if no interested eventcodes specified. :rtype: set(string) """ columns = set() for key in self.event_regex.keys(): for column in self.event_regex[key].keys(): columns.add(column) return columns
4,209
36.927928
107
py
clx-branch-23.04
clx-branch-23.04/python/clx/parsers/splunk_notable_parser.py
# Copyright (c) 2019, NVIDIA CORPORATION. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import os import cudf from clx.parsers.event_parser import EventParser log = logging.getLogger(__name__) class SplunkNotableParser(EventParser): """This is class parses splunk notable logs. """ REGEX_FILE = "resources/splunk_notable_regex.yaml" EVENT_NAME = "notable" def __init__(self): """Constructor method """ event_regex = {} regex_filepath = ( os.path.dirname(os.path.abspath(__file__)) + "/" + self.REGEX_FILE ) self.event_regex = self._load_regex_yaml(regex_filepath) EventParser.__init__(self, event_regex.keys(), self.EVENT_NAME) def parse(self, dataframe, raw_column): """Parses the Splunk notable raw events. :param dataframe: Raw events to be parsed. :type dataframe: cudf.DataFrame :param raw_column: Raw data contained column name. :type raw_column: string :return: parsed information. :rtype: cudf.DataFrame """ # Cleaning raw data to be consistent. dataframe[raw_column] = dataframe[raw_column].str.replace("\\\\", "") parsed_dataframe = self.parse_raw_event(dataframe, raw_column, self.event_regex) # Replace null values of all columns with empty. parsed_dataframe = parsed_dataframe.fillna("") # Post-processing: for src_ip and dest_ip. parsed_dataframe = self._process_ip_fields(parsed_dataframe) return parsed_dataframe def _process_ip_fields(self, parsed_dataframe): """ This function replaces src_ip column with src_ip2, if scr_ip is empty and does the same way for dest_ip column. """ for ip in ["src_ip", "dest_ip"]: log.debug("******* Processing %s *******" % (ip)) ip2 = ip + "2" ip_len = ip + "_len" # Calculate ip column value length. parsed_dataframe[ip_len] = parsed_dataframe[ip].str.len() # Retrieve empty ip column records. tmp_dataframe = parsed_dataframe[parsed_dataframe[ip_len] == 0] # Retrieve non empty ip column records. parsed_dataframe = parsed_dataframe[parsed_dataframe[ip_len] != 0] if not tmp_dataframe.empty: log.debug("tmp_dataframe size %s" % (str(tmp_dataframe.shape))) # Assign ip2 column values to empty ip column values. tmp_dataframe[ip] = tmp_dataframe[ip2] if not parsed_dataframe.empty: log.debug( "parsed_dataframe is not empty %s" % (str(parsed_dataframe.shape)) ) # Concat, if both parsed_dataframe and tmp_df are not empty. parsed_dataframe = cudf.concat([parsed_dataframe, tmp_dataframe]) else: # If parsed_dataframe is empty assign tmp_df. parsed_dataframe = tmp_dataframe # Remove ip2 and ip_len columns. Since data is captured in ip column. parsed_dataframe = parsed_dataframe.drop([ip_len, ip2], axis=1) return parsed_dataframe
3,763
40.822222
119
py
clx-branch-23.04
clx-branch-23.04/python/clx/parsers/__init__.py
0
0
0
py
clx-branch-23.04
clx-branch-23.04/python/clx/parsers/zeek.py
# Copyright (c) 2019, NVIDIA CORPORATION. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import cudf type_dict = { "bool": "bool", "count": "int64", "int": "int64", "double": "float64", "time": "float64", "interval": "float64", "string": "str", "pattern": "str", "port": "int64", "addr": "str", "subnet": "str", "enum": "str", "function": "str", "event": "str", "hook": "str", "file": "str", "opaque": "str", "any": "str", } def parse_log_file(filepath): """Parse Zeek log file and return cuDF dataframe. Uses header comments to get column names/types and configure parser. :param filepath: filepath for Zeek log file :type filepath: string :return: Zeek log dataframe :rtype: cudf.DataFrame """ header_gdf = cudf.read_csv(filepath, names=["line"], nrows=8) lines_gdf = header_gdf["line"].str.split() column_names = lines_gdf.to_pandas().iloc[6][1:].tolist() column_types = lines_gdf.to_pandas().iloc[7][1:].tolist() column_dtypes = list(map(lambda x: type_dict.get(x, "str"), column_types)) log_gdf = cudf.read_csv( filepath, delimiter="\t", dtype=column_dtypes, names=column_names, skiprows=8, skipfooter=1, ) return log_gdf
1,809
27.730159
122
py
clx-branch-23.04
clx-branch-23.04/docs/source/conf.py
# -*- coding: utf-8 -*- # # Configuration file for the Sphinx documentation builder. # # This file does only contain a selection of the most common options. For a # full list see the documentation: # http://www.sphinx-doc.org/en/master/config # -- Path setup -------------------------------------------------------------- # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # # import os # import sys # sys.path.insert(0, os.path.abspath('.')) # -- Project information ----------------------------------------------------- project = 'clx' copyright = '2019, NVIDIA' author = 'NVIDIA' # The short X.Y version version = '23.04' # The full version, including alpha/beta/rc tags release = '23.04.00' # -- General configuration --------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. # # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'nbsphinx', 'sphinx.ext.intersphinx', 'sphinx.ext.autodoc', 'sphinx.ext.autosummary', 'numpydoc', 'IPython.sphinxext.ipython_console_highlighting', 'IPython.sphinxext.ipython_directive', 'nbsphinx' ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # # source_suffix = ['.rst', '.md'] source_suffix = '.rst' # The master toctree document. master_doc = 'index' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = None # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This pattern also affects html_static_path and html_extra_path . exclude_patterns = [] # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # -- Options for HTML output ------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # #html_theme = 'alabaster' html_theme = "sphinx_rtd_theme" # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # # html_theme_options = {} # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Custom sidebar templates, must be a dictionary that maps document names # to template names. # # The default sidebars (for documents that don't match any pattern) are # defined by theme itself. Builtin themes are using these templates by # default: ``['localtoc.html', 'relations.html', 'sourcelink.html', # 'searchbox.html']``. # # html_sidebars = {} # -- Options for HTMLHelp output --------------------------------------------- # Output file base name for HTML help builder. htmlhelp_basename = 'clxdoc' # -- Options for LaTeX output ------------------------------------------------ latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # # 'preamble': '', # Latex figure (float) alignment # # 'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, 'clx.tex', 'clx Documentation', 'NVIDIA', 'manual'), ] # -- Options for manual page output ------------------------------------------ # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ (master_doc, 'clx', 'clx Documentation', [author], 1) ] # -- Options for Texinfo output ---------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ (master_doc, 'clx', 'clx Documentation', author, 'clx', 'One line description of project.', 'Miscellaneous'), ] # -- Extension configuration ------------------------------------------------- # Example configuration for intersphinx: refer to the Python standard library. intersphinx_mapping = {'https://docs.python.org/': None} # Config numpydoc numpydoc_show_inherited_class_members = False numpydoc_class_members_toctree = False def setup(app): app.add_css_file("https://docs.rapids.ai/assets/css/custom.css") app.add_js_file("https://docs.rapids.ai/assets/js/custom.js", loading_method="defer")
5,409
28.725275
89
py
clx-branch-23.04
clx-branch-23.04/notebooks/ids_detection/util.py
import numpy as np from cuml.metrics import precision_recall_curve, roc_auc_score from sklearn.metrics import roc_curve import cupy as cp import matplotlib.pylab as plt def average_precision_score(y_true, y_score): """ Compute average precision score using precision and recall computed from cuml. """ precision, recall, _ = precision_recall_curve(y_true, y_score) # return step function integral return -cp.sum(cp.diff(recall) * cp.array(precision)[:-1]) def metrics(y_true, y_score): auc = roc_auc_score(y_true=y_true, y_score=y_score) ap = average_precision_score(y_true, y_score) return [auc, ap] def plot_roc(label, y_scores): fpr, tpr, _ = roc_curve(y_true=label.values.tolist(), y_score=y_scores.tolist()) auc = metrics(label, y_scores)[0] plt.plot(fpr, tpr, label="ROC = " + str(np.round(auc,2))) plt.plot(np.arange(0,1.1,0.1), np.arange(0,1.1,0.1), 'r-') plt.ylabel('tpr') plt.xlabel('fpr') plt.legend(loc='best') plt.title('Area under AUC curve') def plot_pr(label, y_scores): ap = metrics(label, y_scores)[1] precision, recall, _ = precision_recall_curve( label, y_scores) plt.plot(recall, precision, label='AP = ' + str(np.round(ap,2))) plt.ylabel('Precision') plt.xlabel('Recall') plt.legend(loc='best') plt.title('Area under PR curve') def missing_values_table(df): mis_val = df.isnull().sum() mis_val_percent = 100 * df.isnull().sum() / len(df) mis_val_table = pd.concat([mis_val, mis_val_percent], axis=1) mis_val_table_ren_columns = mis_val_table.rename( columns = {0 : 'Missing Values', 1 : '% of Total Values'}) mis_val_table_ren_columns = mis_val_table_ren_columns[ mis_val_table_ren_columns.iloc[:,1] != 0].sort_values( '% of Total Values', ascending=False).round(1) print ("Your selected dataframe has " + str(df.shape[1]) + " columns.\n" "There are " + str(mis_val_table_ren_columns.shape[0]) + " columns that have missing values.") return mis_val_table_ren_columns
2,069
38.807692
88
py
clx-branch-23.04
clx-branch-23.04/ci/utils/nbtestlog2junitxml.py
# Generate a junit-xml file from parsing a nbtest log import re from xml.etree.ElementTree import Element, ElementTree from os import path import string from enum import Enum startingPatt = re.compile("^STARTING: ([\w\.\-]+)$") skippingPatt = re.compile("^SKIPPING: ([\w\.\-]+)\s*(\(([\w\.\-\ \,]+)\))?\s*$") exitCodePatt = re.compile("^EXIT CODE: (\d+)$") folderPatt = re.compile("^FOLDER: ([\w\.\-]+)$") timePatt = re.compile("^real\s+([\d\.ms]+)$") linePatt = re.compile("^" + ("-" * 80) + "$") def getFileBaseName(filePathName): return path.splitext(path.basename(filePathName))[0] def makeTestCaseElement(attrDict): return Element("testcase", attrib=attrDict) def makeSystemOutElement(outputLines): e = Element("system-out") e.text = "".join(filter(lambda c: c in string.printable, outputLines)) return e def makeFailureElement(outputLines): e = Element("failure", message="failed") e.text = "".join(filter(lambda c: c in string.printable, outputLines)) return e def setFileNameAttr(attrDict, fileName): attrDict.update(file=fileName, classname="", line="", name="", time="" ) def setClassNameAttr(attrDict, className): attrDict["classname"] = className def setTestNameAttr(attrDict, testName): attrDict["name"] = testName def setTimeAttr(attrDict, timeVal): (mins, seconds) = timeVal.split("m") seconds = float(seconds.strip("s")) + (60 * int(mins)) attrDict["time"] = str(seconds) def incrNumAttr(element, attr): newVal = int(element.attrib.get(attr)) + 1 element.attrib[attr] = str(newVal) def parseLog(logFile, testSuiteElement): # Example attrs: # errors="0" failures="0" hostname="a437d6835edf" name="pytest" skipped="2" tests="6" time="6.174" timestamp="2019-11-18T19:49:47.946307" with open(logFile) as lf: testSuiteElement.attrib["tests"] = "0" testSuiteElement.attrib["errors"] = "0" testSuiteElement.attrib["failures"] = "0" testSuiteElement.attrib["skipped"] = "0" testSuiteElement.attrib["time"] = "0" testSuiteElement.attrib["timestamp"] = "" attrDict = {} #setFileNameAttr(attrDict, logFile) setFileNameAttr(attrDict, "nbtest") parserStateEnum = Enum("parserStateEnum", "newTest startingLine finishLine exitCode") parserState = parserStateEnum.newTest testOutput = "" for line in lf.readlines(): if parserState == parserStateEnum.newTest: m = folderPatt.match(line) if m: setClassNameAttr(attrDict, m.group(1)) continue m = skippingPatt.match(line) if m: setTestNameAttr(attrDict, getFileBaseName(m.group(1))) setTimeAttr(attrDict, "0m0s") skippedElement = makeTestCaseElement(attrDict) message = m.group(3) or "" skippedElement.append(Element("skipped", message=message, type="")) testSuiteElement.append(skippedElement) incrNumAttr(testSuiteElement, "skipped") incrNumAttr(testSuiteElement, "tests") continue m = startingPatt.match(line) if m: parserState = parserStateEnum.startingLine testOutput = "" setTestNameAttr(attrDict, m.group(1)) setTimeAttr(attrDict, "0m0s") continue continue elif parserState == parserStateEnum.startingLine: if linePatt.match(line): parserState = parserStateEnum.finishLine testOutput = "" continue elif parserState == parserStateEnum.finishLine: if linePatt.match(line): parserState = parserStateEnum.exitCode else: testOutput += line continue elif parserState == parserStateEnum.exitCode: m = exitCodePatt.match(line) if m: testCaseElement = makeTestCaseElement(attrDict) if m.group(1) != "0": failureElement = makeFailureElement(testOutput) testCaseElement.append(failureElement) incrNumAttr(testSuiteElement, "failures") else: systemOutElement = makeSystemOutElement(testOutput) testCaseElement.append(systemOutElement) testSuiteElement.append(testCaseElement) parserState = parserStateEnum.newTest testOutput = "" incrNumAttr(testSuiteElement, "tests") continue m = timePatt.match(line) if m: setTimeAttr(attrDict, m.group(1)) continue continue if __name__ == "__main__": import sys testSuitesElement = Element("testsuites") testSuiteElement = Element("testsuite", name="nbtest", hostname="") parseLog(sys.argv[1], testSuiteElement) testSuitesElement.append(testSuiteElement) ElementTree(testSuitesElement).write(sys.argv[1]+".xml", xml_declaration=True)
5,526
32.907975
141
py
clx-branch-23.04
clx-branch-23.04/ci/integration_tests/run_integration_test.py
import sys import time import logging import threading from confluent_kafka.admin import ( AdminClient, NewTopic, NewPartitions, ConfigResource, ConfigSource, ) from confluent_kafka import Producer, Consumer from clx.workflow import netflow_workflow logging.basicConfig(stream=sys.stdout, level=logging.INFO) log = logging.getLogger("integration_test") kafka_bootstrap_server = "kafka:9092" input_test_topics = ["input"] output_test_topic = "cyber-enriched-data" test_messages = ["cyber test {iter}".format(iter=i) for i in range(1, 13)] test_workflow = None def setup(input_topics, output_topic, bootstrap_server): """ Setup required to begin integration test including creation of kafka topics and creation of a test workflow """ log.info("Begin test setup..." + output_topic + " " + bootstrap_server) all_topics = ["input", "cyber-enriched-data"] create_kafka_topics(all_topics, bootstrap_server) global test_workflow test_workflow = create_workflow(input_topics, output_topic, bootstrap_server) log.info("Test setup complete.") def create_kafka_topics(topics, bootstrap_server): """ Creates the provided kafka topics given the kafka bootstrap server """ log.info("Creating kafka topics... ") print(topics) # Create Kafka topics kafka_admin = AdminClient({"bootstrap.servers": bootstrap_server}) kafka_topics = [ NewTopic(topic, num_partitions=1, replication_factor=1) for topic in topics ] fs = kafka_admin.create_topics(kafka_topics) log.info("Kafka topics created... " + str(fs)) def create_workflow(input_topics, output_topic, bootstrap_server): """ Creates the provided workflow given the input kafka topics, output topic, and provided bootstrap server """ log.info("Creating test Netflow workflow...") source = { "type": "kafka", "kafka_brokers": bootstrap_server, "group_id": "cyber-dp", "batch_size": 1, "consumer_kafka_topics": input_topics, "time_window": 5, } dest = { "type": "kafka", "kafka_brokers": bootstrap_server, "group_id": "cyber-dp", "batch_size": 1, "publisher_kafka_topic": output_topic, "output_delimiter": ",", } workflow = netflow_workflow.NetflowWorkflow( source=source, destination=dest, name="my-kafka-workflow" ) log.info("Workflow created... " + workflow.name) return workflow def run_workflow(workflow): """ Runs the given workflow """ log.info("Running netflow workflow.") workflow.run_workflow() def send_test_data(bootstrap_server, topic): """ Sends test messages to the provided kafka bootstrap server and kafka topic """ producer_conf = {"bootstrap.servers": bootstrap_server, "session.timeout.ms": 10000} producer = Producer(producer_conf) log.info("Kafka producer created.") for message in test_messages: time.sleep(1) log.info("Sending msg to workflow: " + message) producer.produce(topic, message) producer.flush() def verify(bootstrap_server, output_topic): """ Verifies that messages were processed by the workflow """ log.info("Verifying messages were processed by workflow...") consumer_conf = { "bootstrap.servers": bootstrap_server, "group.id": "int-test", "session.timeout.ms": 10000, "default.topic.config": {"auto.offset.reset": "earliest"}, } consumer = Consumer(consumer_conf) consumer.subscribe([output_topic]) # Adding extra iteration would allow consumer to prepare and start polling messages. expected_messages = set( ["{0},netflow_enriched".format(msg) for msg in test_messages] ) start_time = time.time() while expected_messages: enriched_msg = consumer.poll(timeout=1.0) if enriched_msg is not None and not enriched_msg.error(): data = enriched_msg.value().decode("utf-8") log.info("Enriched msg processed... " + data) if data in expected_messages: expected_messages.remove(data) if (time.time() - start_time) > 60: raise TimeoutError("Integration test did not complete.") def main(): global input_test_topics, output_test_topic, kafka_bootstrap_server print(input_test_topics) setup(input_test_topics, output_test_topic, kafka_bootstrap_server) # Start thread for running workflow global test_workflow t_run_workflow = threading.Thread( target=run_workflow, args=(test_workflow,), name="t_run_workflow" ) t_run_workflow.daemon = True t_run_workflow.start() time.sleep(15) # Start thread for sending test data to kafka t_send_data = threading.Thread( target=send_test_data, args=(kafka_bootstrap_server, input_test_topics[0]), name="t_send_data", ) t_send_data.start() t_send_data.join() # Verify that expected messages have been processed by the workflow verify(kafka_bootstrap_server, output_test_topic) if __name__ == "__main__": main()
5,141
31.751592
111
py
clx-branch-23.04
clx-branch-23.04/siem_integrations/clx_query/bin/clx_query.py
# Copyright (c) 2020, NVIDIA CORPORATION. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import re import sys, requests, json from splunklib.searchcommands import ( dispatch, GeneratingCommand, Configuration, Option, validators, ) import splunklib.client as client log = logging.getLogger(__name__) REGEX_PATTERN = r"([LIMIT|limit]+.[0-9]+$)" @Configuration() class ClxQuery(GeneratingCommand): query = Option(require=True) def generate(self): configs = client.Configurations(self.service) for config in configs: if config.name == "clx_query_setup": clx_config = config.iter().next().content url = self.construct_url(clx_config) has_query_limit = re.findall(REGEX_PATTERN, self.query) payload = {'query': self.query} if not has_query_limit and clx_config["clx_query_limit"]: self.query = "%s LIMIT %s" %(self.query, clx_config["clx_query_limit"]) payload = {'query': self.query} response = requests.post(url, data=payload) if response.status_code != 200: yield {"ERROR": response.content} else: results = json.loads(json.loads(response.content)) for result in results: yield result def construct_url(self, config): url = "http://%s:%s/%s/" % ( config["clx_hostname"], config["clx_port"], 'clxquery' ) return url dispatch(ClxQuery, sys.argv, sys.stdin, sys.stdout, __name__)
2,076
30.469697
82
py
clx-branch-23.04
clx-branch-23.04/siem_integrations/clx_query/bin/clx_query_conf.py
import splunk.admin as admin import splunk.entity as en """ Copyright (C) 2005 - 2010 Splunk Inc. All Rights Reserved. Description: This skeleton python script handles the parameters in the configuration page. handleList method: lists configurable parameters in the configuration page corresponds to handleractions = list in restmap.conf handleEdit method: controls the parameters and saves the values corresponds to handleractions = edit in restmap.conf """ class ConfigApp(admin.MConfigHandler): """ Set up supported arguments """ def setup(self): if self.requestedAction == admin.ACTION_EDIT: for arg in ["clx_hostname", "clx_port", "clx_query_limit"]: self.supportedArgs.addOptArg(arg) """ Reads configuration from the custom file clx/default/clx_query_setup.conf. """ def handleList(self, confInfo): confDict = self.readConf("clx_query_setup") if None != confDict: for stanza, settings in confDict.items(): for key, val in settings.items(): confInfo[stanza].append(key, val) def handleEdit(self, confInfo): name = self.callerArgs.id args = self.callerArgs self.writeConf("clx_query_setup", "setupentity", self.callerArgs.data) # initialize the handler admin.init(ConfigApp, admin.CONTEXT_NONE)
1,473
30.361702
94
py
clx-branch-23.04
clx-branch-23.04/siem_integrations/clx_query_service/manage.py
#!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): os.environ.setdefault("DJANGO_SETTINGS_MODULE", "clx_query_service.settings") try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == "__main__": main()
637
28
81
py
clx-branch-23.04
clx-branch-23.04/siem_integrations/clx_query_service/clxquery/blazingsql_helper.py
# Copyright (c) 2020, NVIDIA CORPORATION. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from dask_cuda import LocalCUDACluster from dask.distributed import Client from blazingsql import BlazingContext import logging log = logging.getLogger(__name__) """ This class provides functionality to run blazingSQL queires and drop tables. """ class BlazingSQLHelper: def __init__(self): cluster = LocalCUDACluster() client = Client(cluster) self._bc = BlazingContext(dask_client = client, network_interface = 'lo') """This function runs blazingSQL query. :param config: Query related tables configuration. :type config: dict :return: Query results. :rtype: cudf.DataFrame """ def run_query(self, config): for table in config["tables"]: table_name = table["table_name"] file_path = table["input_path"] kwargs = table.copy() del kwargs["table_name"] del kwargs["input_path"] self._bc.create_table(table_name, file_path, **kwargs) sql = config["sql"] log.debug("Executing query: %s" % (sql)) result = self._bc.sql(sql) result = result.compute() return result """This function drops blazingSQL tables. :param table_names: List of table names to drop. :type table_names: List """ def drop_table(self, table_names): for table_name in table_names: log.debug("Drop table: %s" % (table_name)) self._bc.drop_table(table_name)
2,049
32.064516
81
py
clx-branch-23.04
clx-branch-23.04/siem_integrations/clx_query_service/clxquery/tests.py
from django.test import TestCase # Create your tests here.
60
14.25
32
py
clx-branch-23.04
clx-branch-23.04/siem_integrations/clx_query_service/clxquery/views.py
import re import os import logging from clxquery import utils from clxquery.blazingsql_helper import BlazingSQLHelper from django.http import HttpResponse, JsonResponse from rest_framework.generics import CreateAPIView log = logging.getLogger(__name__) class ExecuteClxQuery(CreateAPIView): file_path = os.environ.get("BLZ_READER_CONF") # Load tables configuration config = utils.load_yaml(file_path) configured_tables = set([table["table_name"] for table in config["tables"]]) regex_pattern = r"main.([\w]+)" blz_helper = BlazingSQLHelper() def post(self, request, *args, **kwargs): query = str(request.data['query']) # Check for the list of tables used in the query to prevent loading other tables into gpu memory query_tables = set(re.findall(self.regex_pattern, query)) # Verify list of tables used in the query to make sure they are included in the configuration file if query_tables.issubset(self.configured_tables): try: query_config = {} query_config["tables"] = [] for table in self.config["tables"]: if table["table_name"] in query_tables: query_config["tables"].append(table) query_config["sql"] = query # Run query and get the results df = self.blz_helper.run_query(query_config) # Drop tables to free up memory self.blz_helper.drop_table(query_tables) # Convert cudf to pandas dataframe df = df.to_pandas() # Convert results to json format. results = df.to_json(orient="records") response = JsonResponse(results, safe=False) except Exception as e: stacktrace = str(e) log.error("Error executing query: %s" % (stacktrace)) response = JsonResponse( {"status": "false", "message": stacktrace}, status=500, safe=False ) else: message = ( "One or more tables used in the query are not available in the server configuration. Please select from this list %s or add new tables to your clx-blazingsql configuration." % (configured_tables) ) response = JsonResponse( {"status": "false", "message": message}, status=404, safe=False ) return response
2,655
44.016949
194
py
clx-branch-23.04
clx-branch-23.04/siem_integrations/clx_query_service/clxquery/utils.py
# Copyright (c) 2019, NVIDIA CORPORATION. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import yaml """ Utility script """ def load_yaml(yaml_file): with open(yaml_file) as yaml_file: config = yaml.safe_load(yaml_file) return config
753
28
74
py
clx-branch-23.04
clx-branch-23.04/siem_integrations/clx_query_service/clxquery/admin.py
from django.contrib import admin # Register your models here.
63
15
32
py
clx-branch-23.04
clx-branch-23.04/siem_integrations/clx_query_service/clxquery/models.py
from django.db import models # Create your models here.
57
13.5
28
py
clx-branch-23.04
clx-branch-23.04/siem_integrations/clx_query_service/clxquery/apps.py
from django.apps import AppConfig class ClxQueryConfig(AppConfig): name = "clxquery"
91
14.333333
33
py
clx-branch-23.04
clx-branch-23.04/siem_integrations/clx_query_service/clxquery/__init__.py
0
0
0
py
clx-branch-23.04
clx-branch-23.04/siem_integrations/clx_query_service/clxquery/urls.py
from django.conf.urls import re_path from clxquery import views urlpatterns = [re_path("clxquery/$", views.ExecuteClxQuery.as_view())]
135
33
70
py
clx-branch-23.04
clx-branch-23.04/siem_integrations/clx_query_service/clxquery/migrations/__init__.py
0
0
0
py
clx-branch-23.04
clx-branch-23.04/siem_integrations/clx_query_service/clx_query_service/settings.py
""" Django settings for clx_query_service project. Generated by 'django-admin startproject' using Django 2.2.6. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = "i6nr8@pzj5$@^(y903w5tc)8%v!(lk!3npl$1z7(%##2zxv" # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ["localhost"] # Application definition INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "rest_framework", "clxquery.apps.ClxQueryConfig", ] MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ] ROOT_URLCONF = "clx_query_service.urls" TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [], "APP_DIRS": True, "OPTIONS": { "context_processors": [ "django.template.context_processors.debug", "django.template.context_processors.request", "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", ] }, } ] WSGI_APPLICATION = "clx_query_service.wsgi.application" # Database # https://docs.djangoproject.com/en/2.2/ref/settings/#databases DATABASES = { "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": os.path.join(BASE_DIR, "db.sqlite3"), } } # Password validation # https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator" }, {"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator"}, {"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator"}, {"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator"}, ] # Internationalization # https://docs.djangoproject.com/en/2.2/topics/i18n/ LANGUAGE_CODE = "en-us" TIME_ZONE = "UTC" USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.2/howto/static-files/ STATIC_URL = "/static/"
3,140
25.846154
90
py
clx-branch-23.04
clx-branch-23.04/siem_integrations/clx_query_service/clx_query_service/wsgi.py
""" WSGI config for clx_query_service project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "clx_query_service.settings") application = get_wsgi_application()
411
23.235294
78
py
clx-branch-23.04
clx-branch-23.04/siem_integrations/clx_query_service/clx_query_service/__init__.py
0
0
0
py
clx-branch-23.04
clx-branch-23.04/siem_integrations/clx_query_service/clx_query_service/urls.py
from django.urls import path, include urlpatterns = [path("", include("clxquery.urls"))]
90
21.75
50
py
clx-branch-23.04
clx-branch-23.04/siem_integrations/splunk2kafka/export2kafka/bin/export2kafka.py
from __future__ import print_function import sys import json #import pprint from splunklib.searchcommands import dispatch, StreamingCommand, Configuration, Option from confluent_kafka import Producer import confluent_kafka import time def eprint(*args, **kwargs): print(*args, file=sys.stderr, **kwargs) @Configuration(local=True) class FileSinkCommand(StreamingCommand): broker = Option(require=True) topic = Option(require=True) batch = Option(require=False, default=2000) timeout = Option(require=False, default=60) pool = Option(require=False, default=2) start_time = int(time.time()) def create_producers(self, pool, broker): producers = [] for i in range(pool): producers.append(Producer({'bootstrap.servers': broker, 'session.timeout.ms': 10000})) eprint("exprot2kafka - producer"+str(i)+" created: "+broker) return producers def stream(self, records): topic = str(self.topic) broker = str(self.broker) batch = int(self.batch) timeout = int(self.timeout) pool = int(self.pool) eprint("export2kafka - starting... broker("+broker+") topic("+topic+") batch(" \ +str(batch)+") timeout("+str(timeout)+" mins) pool("+str(pool)+")") eprint("export2kafka - stream starting") producers = self.create_producers(pool, broker) cnt = 0 for record in records: trimmed = {k: v for k, v in record.iteritems()} #eprint(json.dumps(trimmed)) producers[cnt % pool].produce(topic, json.dumps(trimmed)) cnt += 1 if cnt % batch == 0: # batch level reached poll to get producer to move messages out eprint("export2kafka - batch reached, calling poll... processed records: "+str(cnt)) for p in producers: p.poll(0) if cnt % 10 == 0 and int(time.time()) > (60 * timeout) + self.start_time: # quit after timeout has been reached, only check every 10 records eprint("export2kafka - timeout reached, stopping search...") break # return record for display in Splunk yield record eprint("export2kafka - all records processed for stream... processed records: "+str(cnt)) eprint("export2kafka - calling flush...") for p in producers: p.flush() eprint("export2kafka - flush finished...") eprint("export2kafka - stream finished") if __name__ == "__main__": dispatch(FileSinkCommand, sys.argv, sys.stdin, sys.stdout, __name__)
2,439
33.857143
93
py
Most-frequented-locations
Most-frequented-locations-master/MFL.py
""" Extract Home and Work locations from individual spatio-temporal trajectories This script returns the location most frequented by an individual (called MFL) during weekdays' daytime and nighttime according to a certain time window. The MFL during a given time windows is defined as the location in which the individual has spent most of his/her time. In this algorithm, two scales are considered, hours and days. Hopefully, for a given individual, the MFLs detected at the two scales should be the same. The algorithm takes as input a 6 columns csv file with column names (the value separator is a semicolon ";"). Each row of the file represents a spatio-temporal position of an individual's trajectory. The time is given by the columns 2 to 5. It is important to note that the table must be SORTED by individual ID and by time. 1. User ID 2. Year 3. Month (1->12) 4. Day (1->31) 5. Hour (0->23) 6. ID of the geographical location The algorithm has 6 parameters: 1. wdinput: Path of the input file 2. wdoutput: Path of the output file 3. minH: Lower bound (included) of the night time window (ex: 8pm) 4. maxH: Upper bound (included) of the night time window (ex: 7am) 5. minW: Lower bound (included) of the day time window (ex: 8am) 6. maxW: Upper bound (included) of the day time window (ex: 7pm) The algorithm returns a 19 columns csv file with column names (the value separator is a semicolon ";"). Each row represents an individual. 1. ID: ID of the individual 2. NbMonths: Number of distinct months covered by the trajectory 3. NbConsMonths: Maximum number of consecutive months covered by the trajectory 4. MFLHomeDays: MFL during nighttime (day scale), 'NoMFL' if NbDaysHome=0 5. MFLHomeDays2: Second MFL during nighttime (day scale) if ex aqueo, 'NoMFL' otherwise 6. NbDaysHomeMFL: Number of distinct days (during nighttime) spent in the MFL 7. NbDaysHome: Number of distinct days covered by the trajectory (during nighttime) 8. MFLHomeHours: MFL during nighttime (hour scale), 'NoMFL' if NbHoursHome=0 9. MFLHomeHours2: Second MFL during nighttime (hour scale) if ex aqueo, 'NoMFL' otherwise 10. NbHoursHomeMFL: Number of distinct hours spent in the MFL (during nighttime) 11. NbHoursHome: Number of distinct hours covered by the trajectory (during nighttime) 12. MFLWorkDays: MFL during daytime (day scale), 'NoMFL' if NbDaysWork=0 13. MFLWorkDays2: Second MFL during daytime (day scale) if ex aqueo, 'NoMFL' otherwise 14. NbDaysWorkMFL: Number of distinct days spent in the MFL (during daytime) 15. NbDaysWork: Number of distinct days covered by the trajectory (during daytime) 16. MFLWorkHours: MFL during daytime (hour scale), 'NoMFL' if NbHoursWork=0 17. MFLWorkHours2: Second MFL during daytime (hour scale) if ex aqueo, 'NoMFL' otherwise 18. NbHoursWorkMFL: Number of distinct days spent in the MFL (during daytime) 19. NbHoursWork: Number of distinct hours covered by the trajectory (during daytime) Author: Maxime Lenormand (2015) """ # ****************************** IMPORTS ******************************************************************** # *********************************************************************************************************** import sys import random from datetime import datetime import operator # ****************************** PARAMETRES ***************************************************************** # *********************************************************************************************************** wdinput = sys.argv[1] wdoutput = sys.argv[2] minH = int(sys.argv[3]) #Nighttime: [minW,maxW] maxH = int(sys.argv[4]) minW = int(sys.argv[5]) #Daytime: [minH,maxH] maxW = int(sys.argv[6]) print(" ") print("Parameters:" + " "+ wdinput + " " + wdoutput + " " + str(minH) + " " + str(maxH) + " " + str(minW) + " " + str(maxW)) print(" ") # ****************************** MAIN *********************************************************************** # *********************************************************************************************************** #Input file input_file = open(wdinput) #Open file next(input_file) #Skip column names input_file2 = open(wdinput) #Open the file again to detect the last user's position next(input_file2) #Skip column names next(input_file2) #Skip first position #Output file output_file = open(wdoutput,'w') output_file.write('ID') output_file.write(';') output_file.write('NbMonths') output_file.write(';') output_file.write('NbConsMonths') output_file.write(';') output_file.write('MFLHomeDays') output_file.write(';') output_file.write('MFLHomeDays2') output_file.write(';') output_file.write('NbDaysHomeMFL') output_file.write(';') output_file.write('NbDaysHome') output_file.write(';') output_file.write('MFLHomeHours') output_file.write(';') output_file.write('MFLHomeHours2') output_file.write(';') output_file.write('NbHoursHomeMFL') output_file.write(';') output_file.write('NbHoursHome') output_file.write(';') output_file.write('MFLWorkDays') output_file.write(';') output_file.write('MFLWorkDays2') output_file.write(';') output_file.write('NbDaysWorkMFL') output_file.write(';') output_file.write('NbDaysWork') output_file.write(';') output_file.write('MFLWorkHours') output_file.write(';') output_file.write('MFLWorkHours2') output_file.write(';') output_file.write('NbHoursWorkMFL') output_file.write(';') output_file.write('NbHoursWork') output_file.write('\n') #Initializing Variables NbTotMonths = 0 #Total number of distinct months covered by the trajectories TotMonths = {} #Dictionary of months NbMonths = 0 #Number of distinct months covered by the trajectory NbConsMonthsTmp = 0 #Temporary number of consecutive months NbConsMonths = 0 #Maximal number of consecutive months YearMonth = () #List of years MonthMonth = () #List of months Hday = {} #Dictionary containing for each location a counter and a dictionary of days (during nighttime) NbHday={} #Dictionary of distinct days covered by the trajectory (during nighttime) Hhour = {} #Dictionary containing for each location a counter and a dictionary of hours (during nighttime) NbHhour={} #Dictionary of distinct hours covered by the trajectory (during nighttime) Wday = {} #Dictionary containing for each location a counter and a dictionary of days (during daytime) NbWday={} #Dictionary of distinct days covered by the trajectory (during daytime) Whour = {} #Dictionary containing for each location a counter and a dictionary of hours (during daytime) NbWhour={} #Dictionary of distinct hours covered by the trajectory (during daytime) nbuser = 0 #Counter user #Looping through the file line by line for line in input_file: #Print number users if random.random() > 0.99999: print ("Number of users:" + " " + str(nbuser)) #User's position attributes attr = line.rstrip('\n\r').split(';') #Split line ID = attr[0] #Individual ID year = int(attr[1]) #Year month = int(attr[2]) #Month day = int(attr[3]) #Day hour = int(attr[4]) #Hour loc = int(attr[5]) #Location ID YM = str(year) + "_" + str(month) #Month ID YMD = str(year) + "_" + str(month) + "_" + str(day) #Day ID YMDH = str(year) + "_" + str(month) + "_" + str(day) + "_" + str(hour) #Hour ID #Weed day (from 0 to 6) weekday=datetime(int(year), int(month), int(day)) weekday=weekday.weekday() #Next User ID to detect the last users' position and the last line try: attr = next(input_file2).rstrip('\n\r').split(';') ID_next = attr[0] #User ID except(StopIteration): ID_next = ID + "last" #Fake ID if last line #Total number of distinct months if (not TotMonths.__contains__(YM)): #if new month increase the counter NbTotMonths = NbTotMonths + 1 TotMonths[YM] = 0 #Month YearMonth = YearMonth + (year,) MonthMonth = MonthMonth + (month,) if len(YearMonth)>1: if (not (year == YearMonth[-2] and month == MonthMonth[-2])): NbMonths = NbMonths + 1 if ((year == YearMonth[-2] and month == (MonthMonth[-2]+1)) or (year == (YearMonth[-2]-1) and month == 1 and MonthMonth[-2]==12)): NbConsMonthsTmp = NbConsMonthsTmp + 1 NbConsMonths = max(NbConsMonths, NbConsMonthsTmp) else: NbConsMonthsTmp = 1 else: NbMonths = 1 NbConsMonthsTmp = 1 NbConsMonths = 1 #Home if (((hour >= minH) or (hour <= maxH)) and (weekday < 5)): #If new day increase the counter if (not (NbHday.__contains__(YMD))): NbHday[YMD]=1 #If new hour increase the counter if (not (NbHhour.__contains__(YMDH))): NbHhour[YMDH]=1 #If the location already exists if Hday.__contains__(loc): #If new day increase the counter if (not (Hday[loc][1].__contains__(YMD))): Hday[loc][0] = Hday[loc][0] + 1 Hday[loc][1][YMD] = 0 #If new hour increase the counter if (not (Hhour[loc][1].__contains__(YMDH))): Hhour[loc][0] = Hhour[loc][0] + 1 Hhour[loc][1][YMDH] = 0 #If new location else: Hday[loc] = [1,{}] Hday[loc][1][YMD] = 0 Hhour[loc] = [1,{}] Hhour[loc][1][YMDH] = 0 #Work if (((hour >= minW) and (hour <= maxW)) and (weekday < 5)): #If new day increase the counter if (not (NbWday.__contains__(YMD))): NbWday[YMD]=1 #If new hour increase the counter if (not (NbWhour.__contains__(YMDH))): NbWhour[YMDH]=1 #If the location already exists if Wday.__contains__(loc): #If new day increase the counter if (not (Wday[loc][1].__contains__(YMD))): Wday[loc][0] = Wday[loc][0] + 1 Wday[loc][1][YMD] = 0 #If new hour increase the counter if (not (Whour[loc][1].__contains__(YMDH))): Whour[loc][0] = Whour[loc][0] + 1 Whour[loc][1][YMDH] = 0 #If new location else: Wday[loc] = [1,{}] Wday[loc][1][YMD] = 0 Whour[loc] = [1,{}] Whour[loc][1][YMDH] = 0 #If last user's position, extract the metrics if (ID != ID_next): #Home day MFLHomeDays = 'NoMFL' MFLHomeDays2 = 'NoMFL' NbDaysHomeMFL = 0 sort = sorted(Hday.items(), key=operator.itemgetter(1), reverse=True) #Sort locations by number of days if len(sort): MFLHomeDays = sort[0][0] NbDaysHomeMFL = sort[0][1][0] if len(sort)>1: if sort[1][1][0] == sort[0][1][0]: MFLHomeDays2 = sort[1][0] #Home hour MFLHomeHours = 'NoMFL' MFLHomeHours2 = 'NoMFL' NbHoursHomeMFL = 0 sort = sorted(Hhour.items(), key=operator.itemgetter(1), reverse=True) #Sort locations by number of hours if len(sort): MFLHomeHours = sort[0][0] NbHoursHomeMFL = sort[0][1][0] if len(sort)>1: if sort[1][1][0] == sort[0][1][0]: MFLHomeHours2 = sort[1][0] #Work day MFLWorkDays = 'NoMFL' MFLWorkDays2 = 'NoMFL' NbDaysWorkMFL = 0 sort = sorted(Wday.items(), key=operator.itemgetter(1), reverse=True) #Sort location by number of days if len(sort): MFLWorkDays = sort[0][0] NbDaysWorkMFL = sort[0][1][0] if len(sort)>1: if sort[1][1][0] == sort[0][1][0]: MFLWorkDays2 = sort[1][0] #Work hour MFLWorkHours = 'NoMFL' MFLWorkHours2 = 'NoMFL' NbHoursWorkMFL = 0 sort = sorted(Whour.items(), key=operator.itemgetter(1), reverse=True) #Sort location by number of hours if len(sort): MFLWorkHours = sort[0][0] NbHoursWorkMFL = sort[0][1][0] if len(sort)>1: if sort[1][1][0] == sort[0][1][0]: MFLWorkHours2 = sort[1][0] #Write output output_file.write(str(ID)) output_file.write(';') output_file.write(str(NbMonths)) output_file.write(';') output_file.write(str(NbConsMonths)) output_file.write(';') output_file.write(str(MFLHomeDays)) output_file.write(';') output_file.write(str(MFLHomeDays2)) output_file.write(';') output_file.write(str(NbDaysHomeMFL)) output_file.write(';') output_file.write(str(len(NbHday))) output_file.write(';') output_file.write(str(MFLHomeHours)) output_file.write(';') output_file.write(str(MFLHomeHours2)) output_file.write(';') output_file.write(str(NbHoursHomeMFL)) output_file.write(';') output_file.write(str(len(NbHhour))) output_file.write(';') output_file.write(str(MFLWorkDays)) output_file.write(';') output_file.write(str(MFLWorkDays2)) output_file.write(';') output_file.write(str(NbDaysWorkMFL)) output_file.write(';') output_file.write(str(len(NbWday))) output_file.write(';') output_file.write(str(MFLWorkHours)) output_file.write(';') output_file.write(str(MFLWorkHours2)) output_file.write(';') output_file.write(str(NbHoursWorkMFL)) output_file.write(';') output_file.write(str(len(NbWhour))) output_file.write('\n') #Re-initialise the variables YearMonth = () MonthMonth = () NbConsMonthsTmp = 0 NbConsMonths = 0 Hday = {} NbHday={} Hhour = {} NbHhour={} Wday = {} NbWday={} Whour = {} NbWhour={} nbuser = nbuser + 1 #count user #Close files input_file.close() input_file2.close() output_file.close() #Print the total number of months print(" ") print("The total number of distinct months covered by the trajectories is " + str(NbTotMonths))
15,425
40.579515
142
py
material-failure-prediction
material-failure-prediction-main/run_DML.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import scipy.io as sio import numpy as np from PIL import Image from DML import DML def read_image_as_tensor(filename): """ This function converts JPG image to numpy matrix format :param filename: image path :return: 2D numpy matrix with normalization scaled """ data_list = [] img = Image.open(filename) img.thumbnail((150, 150), Image.AFFINE) arr = np.array(img).reshape((150, 150, 3)) data_list.append(arr) img.close() data_X = np.array(data_list) return data_X / 255. if __name__ == '__main__': print("-----------------------------------") x1 = read_image_as_tensor('DML-Inputs/x1.jpg') x2 = np.asarray(sio.loadmat('DML-Inputs/x2.mat')['x2']) model = DML() result = model.DML_model(path='pretrain', x_1=x1, x_2=x2) print("Fatigue fracture progress: {0:.2f}%".format(result)) print("-----------------------------------")
1,022
25.230769
63
py
material-failure-prediction
material-failure-prediction-main/run_PH.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import imageio import numpy as np import homcloud.interface as hc import scipy.io as sio import os from CT_utils import CT_utils from CT_utils import ImageTDA from sklearn.preprocessing import MinMaxScaler def crop_convert(folder, filename='', range_begin=1, range_end=1001, thres=128): """ This function converts X-C images to binary format. :param folder: image folder :param filename: filename :param range_begin: the index number of starting image :param range_end: the index number of ending image :param thres: the threshold value for conversion """ result_folder = 'Result/'+folder dataset_folder = 'Dataset/'+folder if os.path.isdir(result_folder) is False: os.mkdir(result_folder) os.mkdir(result_folder + '/CT Binary') os.mkdir(result_folder + '/CT Binary(NOBG)') os.mkdir(result_folder + '/PH Result') ct_object = CT_utils(ct_path=dataset_folder, result_path=result_folder, filename=filename, thres=thres) ct_object.image_process(range_begin=range_begin, range_end=range_end) def TDA_analysis(folder, range_begin=1, range_end=126): """ This functions calculates the void topology by using HomCloud API. :param folder: Sample folder path :param range_begin: starting range of input images :param range_end: ending range of input images """ image_folder = 'Result/' + folder pict = np.stack([imageio.imread(image_folder + "/CT Binary(NOBG)/pict_{:04d}.jpg".format(n)) > 128 for n in range(range_begin, range_end)], axis=0) result_folder = 'Result/' + folder + '/PH Result' print('\n\nCalculating by Homcloud library...') hc.PDList.from_bitmap_levelset(hc.distance_transform(pict, signed=True), save_to=result_folder + '/PD.idiagram') hc.BitmapPHTreesPair.from_bitmap_levelset(hc.distance_transform(pict, signed=True), save_to=result_folder + '/PD.p2mt') print('Completed!\n\n') print('PH Analysis begins~') pdlist = hc.PDList(result_folder + '/PD.idiagram') pd1 = pdlist.dth_diagram(0) vmax = 50 vmin = -6 pd1.histogram((vmin - 2, vmax), 50).plot(colorbar={"type": "log"}) phtreespair = hc.BitmapPHTreesPair(result_folder + '/PD.p2mt') phtree_0 = phtreespair.dim_0_trees() numbers_count = [] bir = [-9, -8, -7, -6, -5, -4, -3, -2, -1] for k in range(len(bir)): for i in range(-20, 61): x = bir[k] y = i nodes_0 = phtree_0.pair_nodes_in_rectangle(x, x, y, y) if len(nodes_0) != 0: numbers_count.append([x, y, len(nodes_0)]) result = np.array(numbers_count) min_b = np.min(result[:, [0]]) max_d = np.max(result[:, [1]]) numbers_count.append([min_b, max_d, 1.0]) sio.savemat(result_folder + '/bin_count.mat', {'bin_count': np.array(numbers_count)}) def calc_PHmetric(filename='', vol=0.): """ This function calculates the proposed PD metric. :param filename: Persistent Diagram metric :param vol: Total volume of input space :return: PD metric """ count = sio.loadmat(filename)['bin_count'] count = np.asarray(count) size = count.shape[0] xnew = np.unique(count[:, 0]) bin_birth = [] for i in range(xnew.shape[0]): temp = 0 for j in range(size): if xnew[i] == count[j, 0]: temp = temp + count[j, 2] bin_birth.append(temp) xnew = abs(xnew) * 3 xnew = np.flipud(xnew) bin_birth = np.flipud(bin_birth) metric = [] total_vol_with_3 = 0 total_vol_with_3_6 = 0 total_vol_with_6 = 0 for i in range(xnew.shape[0]): if xnew[i] <= 3: total_vol_with_3 += bin_birth[i] elif 3 < xnew[i] <= 6: total_vol_with_3_6 += bin_birth[i] elif xnew[i] > 6: total_vol_with_6 += bin_birth[i] metric.append(total_vol_with_3 / vol) metric.append(total_vol_with_3_6 / vol) metric.append(total_vol_with_6 / vol) sum_v = np.sum(count[:, 2]) d_ = np.zeros((count.shape[0], 2)) for i in range(count.shape[0]): d_[i, 0] = abs(count[i, 1] - count[i, 0]) d_[i, 1] = count[i, 2] d = np.zeros((count.shape[0], 2)) for i in range(count.shape[0]): d[i, 0] = d_[i, 0] * 3 - 1.5 d[i, 1] = np.power(d[i, 0], count[i, 2]/sum_v) D = np.prod(d[:, 1]) metric.append(D) v = np.zeros((count.shape[0], 2)) for i in range(count.shape[0]): v[i, 0] = abs((d_[i, 0] * 3 - 1.5) - D) v[i, 1] = np.power(v[i, 0], count[i, 2] / sum_v) V = np.prod(v[:, 1]) metric.append(V) return np.asarray(metric) def normalize_metric(metric): """ This function normalizes the PD metric by using Min-Max scaling. :param metric: PD metric :return: normalized PD metric """ scaler = MinMaxScaler() sample_scaled_feat = [[89], [18628]] scaler.fit_transform(sample_scaled_feat) metric[0, 0] = scaler.transform(metric[0, 0].reshape(1, -1)) sample_scaled_feat = [[0], [39]] scaler.fit_transform(sample_scaled_feat) metric[0, 1] = scaler.transform(metric[0, 1].reshape(1, -1)) sample_scaled_feat = [[0], [95]] scaler.fit_transform(sample_scaled_feat) metric[0, 2] = scaler.transform(metric[0, 2].reshape(1, -1)) sample_scaled_feat = [[9.453], [93.71]] scaler.fit_transform(sample_scaled_feat) metric[0, 3] = scaler.transform(metric[0, 3].reshape(1, -1)) sample_scaled_feat = [[2.23], [19.59]] scaler.fit_transform(sample_scaled_feat) metric[0, 4] = scaler.transform(metric[0, 4].reshape(1, -1)) return metric if __name__ == '__main__': # Calculate Void topology print("-----------------------------------") folder = 'Sample' crop_convert(folder, filename='#20210311_#3-6_Fatigue', range_begin=309, range_end=809, thres=128) TDA_analysis(folder, range_begin=309, range_end=809) # Calculate PD Metric print("-----------------------------------") mat_file = 'Result/Sample/PH Result/bin_count.mat' vol = (3.000 * 500 / 1000) * 1.412 * 0.406 metric = calc_PHmetric(filename=mat_file, vol=vol) print("PD Metric is created!\n") metric = np.array(metric).reshape((1, 5)) metric = normalize_metric(metric) sio.savemat('DML-Inputs/x2.mat', {'x2': metric}) # Generate PD Image print("-----------------------------------") pd_dim = 0 R = [-10, 66] R_x = [-10, 2] R_y = [-10, 66] ph = ImageTDA(path="Result/Sample/PH Result/PD.idiagram", pd_dim=pd_dim) ph.plot_clean_pd_for_ml(pd_range=R, x_show=R_x, y_show=R_y) print("PD Image is created!\n\n") print("Done!") print("-----------------------------------")
6,941
30.554545
107
py
material-failure-prediction
material-failure-prediction-main/CT_utils.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function from PIL import Image import imageio import numpy as np import homcloud.interface as hc from scipy.stats import gaussian_kde import matplotlib.pyplot as plt import matplotlib.colors as colors class CT_utils(object): def __init__(self, ct_path, result_path, filename, thres=128): """ Construstor :param ct_path: X-CT image path :param result_path: Result path :param filename: filename of image path """ self.ct_path = ct_path self.result_path = result_path self.filename = filename self.thres = thres print('Creating CT...') def image_process(self, range_begin=1, range_end=1003): """ This function processes the binary conversion. :param range_begin: the index number of starting image :param range_end: the index number of ending image :return: a binary format of numpy matrix """ for i in range(range_begin, range_end): img = Image.open(self.ct_path + "/" + self.filename + "{:04d}.tiff".format(i)) bw = np.asarray(img).copy() bw = np.true_divide(bw, [255.0], out=None) bw[bw >= self.thres] = 255 bw[bw < self.thres] = 0 bwfile = Image.fromarray(255-np.uint8(bw)) bwfile.save(self.result_path + "/CT Binary/pict_{:04d}.jpg".format(i)) no_bw = bw.copy() bwfile = Image.fromarray(np.uint8(no_bw)) bwfile.save(self.result_path + "/CT Binary(NOBG)/pict_{:04d}.jpg".format(i)) return np.stack([imageio.imread(self.result_path + "/CT Binary(NOBG)/pict_{:04d}.jpg".format(n)) > 128 for n in range(range_begin, range_end)], axis=0) @staticmethod def remove_bg(bw): """ This function converts the background as 'black' and the voids as 'white'. :param bw: the input of image :return: the result of conversion """ tempbw = bw.copy() result = np.zeros((bw.shape[0], bw.shape[1])) for i in range(bw.shape[1]): index_store_white = [] if np.max(bw[:, i]) == 0: bw[:, i] = 255. else: for j in range(bw.shape[0]): if bw[j, i] == 255: index_store_white.append(j) for j in range(bw.shape[0]): if not index_store_white: bw[j, i] = 255. else: if j < index_store_white[0] or j > index_store_white[-1]: bw[j, i] = 255. for i in range(tempbw.shape[0]): index_store_white = [] if np.max(tempbw[i, :]) == 0: tempbw[i, :] = 255. else: for j in range(tempbw.shape[1]): if tempbw[i, j] == 255: index_store_white.append(j) for j in range(tempbw.shape[1]): if not index_store_white: tempbw[i, j] = 255. else: if j < index_store_white[0] or j > index_store_white[-1]: tempbw[i, j] = 255. for i in range(tempbw.shape[0]): for j in range(tempbw.shape[1]): if tempbw[i, j] == bw[i, j] and tempbw[i, j] == 0: result[i, j] = 0 else: result[i, j] = 255 result = 255 - result for i in range(result.shape[0]): for j in range(result.shape[1]): if result[i, j] == 255: result[i - 1:i + 1, j - 1:j + 1] = 255 return result class ImageTDA(object): def __init__(self, path, pd_dim=0): """ Constructor :param path: image path :param pd_dim: we set as 0th PD [For more info, please refers to https://homcloud.dev/basic-usage.en.html] """ self.img_path = path self.pd_dim = pd_dim def plot_clean_pd_for_ml(self, pd_range, x_show=None, y_show=None): """ This function generates the final output of PD image with new range and colormap by using the Homcloud API. :param pd_range: the range of birth and death points :param x_show: x axis :param y_show: y axis """ fig = plt.figure(figsize=(5, 5)) ax = fig.add_subplot(111) ''' idiag ''' pdlist = hc.PDList('%s' % self.img_path) pd = pdlist.dth_diagram(self.pd_dim) pairs = pd.pairs() B = [pair.birth_time() for pair in pairs] D = [pair.death_time() for pair in pairs] B.append(10001) D.append(10001) B.append(10003) D.append(10002) bd_pair = np.vstack([B, D]) g_kde = gaussian_kde(bd_pair)(bd_pair) ''' phtrees ''' norm = colors.Normalize(vmin=1.0, vmax=2200) ax.scatter(B, D, c=g_kde * (1 / g_kde.min()), cmap='rainbow', s=40, marker='s', norm=norm, edgecolor='', zorder=2) if x_show is None and y_show is None: ax.set_xlim(pd_range) ax.set_ylim(pd_range) else: ax.set_xlim(x_show) ax.set_ylim(y_show) ax.axis('off') fig.tight_layout() fig.savefig('DML-Inputs/x1.jpg', bbox_inches='tight', pad_inches=0) plt.close()
5,560
32.299401
115
py
material-failure-prediction
material-failure-prediction-main/DML.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import tensorflow as tf import tensorflow.python.util.deprecation as deprecation # Hide all the warning messages from TensorFlow deprecation._PRINT_DEPRECATION_WARNINGS = False os.environ['TF_CPP_MIN_LOG_LEVEL'] = '1' config = tf.ConfigProto() config.gpu_options.allow_growth = True class DML(object): def __init__(self): print('DML pretrain model loading...\n\n') @staticmethod def DML_model(path, x_1=None, x_2=None): """ This function loads the weights from pretrained model. :param path: path of the pretrain model :param x_1: the input of PD image :param x_2: the input of PD-extracted metric :return: prediction result """ graph = tf.get_default_graph() with tf.Session(config=config) as sess: saver = tf.train.import_meta_graph(path + '/DML.meta') saver.restore(sess, path + '/DML') x1 = graph.get_tensor_by_name("input_img:0") x2 = graph.get_tensor_by_name("input_x:0") drop_prob = graph.get_tensor_by_name("keep_prob:0") pred_ = graph.get_tensor_by_name("ann_net/output/add:0") input_feed = {x1: x_1, x2: x_2, drop_prob: 1.0} result_ = sess.run(pred_/2, feed_dict=input_feed) return result_.reshape(-1)[0] * 100
1,447
30.478261
68
py
pdarts
pdarts-master/test.py
import os import sys import glob import numpy as np import torch import utils import logging import argparse import torch.nn as nn import genotypes import torch.utils import torchvision.datasets as dset import torch.backends.cudnn as cudnn from model import NetworkCIFAR as Network parser = argparse.ArgumentParser("cifar") parser.add_argument('--data', type=str, default='../data', help='location of the data corpus') parser.add_argument('--batch_size', type=int, default=128, help='batch size') parser.add_argument('--report_freq', type=float, default=50, help='report frequency') parser.add_argument('--gpu', type=int, default=0, help='gpu device id') parser.add_argument('--init_channels', type=int, default=36, help='num of init channels') parser.add_argument('--layers', type=int, default=20, help='total number of layers') parser.add_argument('--model_path', type=str, default='CIFAR10.pt', help='path of pretrained model') parser.add_argument('--auxiliary', action='store_true', default=False, help='use auxiliary tower') parser.add_argument('--cutout', action='store_true', default=False, help='use cutout') parser.add_argument('--cutout_length', type=int, default=16, help='cutout length') parser.add_argument('--arch', type=str, default='PDARTS', help='which architecture to use') args = parser.parse_args() log_format = '%(asctime)s %(message)s' logging.basicConfig(stream=sys.stdout, level=logging.INFO, format=log_format, datefmt='%m/%d %I:%M:%S %p') CIFAR_CLASSES = 10 def main(): if not torch.cuda.is_available(): logging.info('no gpu device available') sys.exit(1) torch.cuda.set_device(args.gpu) cudnn.enabled=True logging.info("args = %s", args) genotype = eval("genotypes.%s" % args.arch) model = Network(args.init_channels, CIFAR_CLASSES, args.layers, args.auxiliary, genotype) model = model.cuda() try: utils.load(model, args.model_path) except: model = model.module utils.load(model, args.model_path) logging.info("param size = %fMB", utils.count_parameters_in_MB(model)) criterion = nn.CrossEntropyLoss() criterion = criterion.cuda() _, test_transform = utils._data_transforms_cifar10(args) test_data = dset.CIFAR10(root=args.data, train=False, download=True, transform=test_transform) test_queue = torch.utils.data.DataLoader( test_data, batch_size=args.batch_size, shuffle=False, pin_memory=False, num_workers=2) model.drop_path_prob = 0.0 test_acc, test_obj = infer(test_queue, model, criterion) logging.info('Test_acc %f', test_acc) def infer(test_queue, model, criterion): objs = utils.AvgrageMeter() top1 = utils.AvgrageMeter() top5 = utils.AvgrageMeter() model.eval() for step, (input, target) in enumerate(test_queue): input = input.cuda() target = target.cuda() with torch.no_grad(): logits, _ = model(input) loss = criterion(logits, target) prec1, prec5 = utils.accuracy(logits, target, topk=(1, 5)) n = input.size(0) objs.update(loss.data.item(), n) top1.update(prec1.data.item(), n) top5.update(prec5.data.item(), n) if step % args.report_freq == 0: logging.info('test %03d %e %f %f', step, objs.avg, top1.avg, top5.avg) return top1.avg, objs.avg if __name__ == '__main__': main()
3,279
31.475248
100
py
pdarts
pdarts-master/train_imagenet.py
import os import sys import numpy as np import time import torch import utils import glob import random import logging import argparse import torch.nn as nn import genotypes import torch.utils import torchvision.datasets as dset import torchvision.transforms as transforms import torch.backends.cudnn as cudnn from torch.autograd import Variable from model import NetworkImageNet as Network parser = argparse.ArgumentParser("training imagenet") parser.add_argument('--workers', type=int, default=32, help='number of workers to load dataset') parser.add_argument('--batch_size', type=int, default=256, help='batch size') parser.add_argument('--learning_rate', type=float, default=0.1, help='init learning rate') parser.add_argument('--momentum', type=float, default=0.9, help='momentum') parser.add_argument('--weight_decay', type=float, default=3e-5, help='weight decay') parser.add_argument('--report_freq', type=float, default=100, help='report frequency') parser.add_argument('--epochs', type=int, default=250, help='num of training epochs') parser.add_argument('--init_channels', type=int, default=48, help='num of init channels') parser.add_argument('--layers', type=int, default=14, help='total number of layers') parser.add_argument('--auxiliary', action='store_true', default=False, help='use auxiliary tower') parser.add_argument('--auxiliary_weight', type=float, default=0.4, help='weight for auxiliary loss') parser.add_argument('--drop_path_prob', type=float, default=0, help='drop path probability') parser.add_argument('--save', type=str, default='/tmp/checkpoints/', help='experiment name') parser.add_argument('--seed', type=int, default=0, help='random seed') parser.add_argument('--arch', type=str, default='PDARTS', help='which architecture to use') parser.add_argument('--grad_clip', type=float, default=5., help='gradient clipping') parser.add_argument('--label_smooth', type=float, default=0.1, help='label smoothing') parser.add_argument('--lr_scheduler', type=str, default='linear', help='lr scheduler, linear or cosine') parser.add_argument('--tmp_data_dir', type=str, default='/tmp/cache/', help='temp data dir') parser.add_argument('--note', type=str, default='try', help='note for this run') args, unparsed = parser.parse_known_args() args.save = '{}eval-{}-{}'.format(args.save, args.note, time.strftime("%Y%m%d-%H%M%S")) utils.create_exp_dir(args.save, scripts_to_save=glob.glob('*.py')) log_format = '%(asctime)s %(message)s' logging.basicConfig(stream=sys.stdout, level=logging.INFO, format=log_format, datefmt='%m/%d %I:%M:%S %p') fh = logging.FileHandler(os.path.join(args.save, 'log.txt')) fh.setFormatter(logging.Formatter(log_format)) logging.getLogger().addHandler(fh) CLASSES = 1000 class CrossEntropyLabelSmooth(nn.Module): def __init__(self, num_classes, epsilon): super(CrossEntropyLabelSmooth, self).__init__() self.num_classes = num_classes self.epsilon = epsilon self.logsoftmax = nn.LogSoftmax(dim=1) def forward(self, inputs, targets): log_probs = self.logsoftmax(inputs) targets = torch.zeros_like(log_probs).scatter_(1, targets.unsqueeze(1), 1) targets = (1 - self.epsilon) * targets + self.epsilon / self.num_classes loss = (-targets * log_probs).mean(0).sum() return loss def main(): if not torch.cuda.is_available(): logging.info('No GPU device available') sys.exit(1) np.random.seed(args.seed) cudnn.benchmark = True torch.manual_seed(args.seed) cudnn.enabled=True torch.cuda.manual_seed(args.seed) logging.info("args = %s", args) logging.info("unparsed_args = %s", unparsed) num_gpus = torch.cuda.device_count() genotype = eval("genotypes.%s" % args.arch) print('---------Genotype---------') logging.info(genotype) print('--------------------------') model = Network(args.init_channels, CLASSES, args.layers, args.auxiliary, genotype) if num_gpus > 1: model = nn.DataParallel(model) model = model.cuda() else: model = model.cuda() logging.info("param size = %fMB", utils.count_parameters_in_MB(model)) criterion = nn.CrossEntropyLoss() criterion = criterion.cuda() criterion_smooth = CrossEntropyLabelSmooth(CLASSES, args.label_smooth) criterion_smooth = criterion_smooth.cuda() optimizer = torch.optim.SGD( model.parameters(), args.learning_rate, momentum=args.momentum, weight_decay=args.weight_decay ) data_dir = os.path.join(args.tmp_data_dir, 'imagenet') traindir = os.path.join(data_dir, 'train') validdir = os.path.join(data_dir, 'val') normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) train_data = dset.ImageFolder( traindir, transforms.Compose([ transforms.RandomResizedCrop(224), transforms.RandomHorizontalFlip(), transforms.ColorJitter( brightness=0.4, contrast=0.4, saturation=0.4, hue=0.2), transforms.ToTensor(), normalize, ])) valid_data = dset.ImageFolder( validdir, transforms.Compose([ transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(), normalize, ])) train_queue = torch.utils.data.DataLoader( train_data, batch_size=args.batch_size, shuffle=True, pin_memory=True, num_workers=args.workers) valid_queue = torch.utils.data.DataLoader( valid_data, batch_size=args.batch_size, shuffle=False, pin_memory=True, num_workers=args.workers) # scheduler = torch.optim.lr_scheduler.StepLR(optimizer, args.decay_period, gamma=args.gamma) scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, float(args.epochs)) best_acc_top1 = 0 best_acc_top5 = 0 for epoch in range(args.epochs): if args.lr_scheduler == 'cosine': scheduler.step() current_lr = scheduler.get_lr()[0] elif args.lr_scheduler == 'linear': current_lr = adjust_lr(optimizer, epoch) else: print('Wrong lr type, exit') sys.exit(1) logging.info('Epoch: %d lr %e', epoch, current_lr) if epoch < 5 and args.batch_size > 256: for param_group in optimizer.param_groups: param_group['lr'] = current_lr * (epoch + 1) / 5.0 logging.info('Warming-up Epoch: %d, LR: %e', epoch, current_lr * (epoch + 1) / 5.0) if num_gpus > 1: model.module.drop_path_prob = args.drop_path_prob * epoch / args.epochs else: model.drop_path_prob = args.drop_path_prob * epoch / args.epochs epoch_start = time.time() train_acc, train_obj = train(train_queue, model, criterion_smooth, optimizer) logging.info('Train_acc: %f', train_acc) valid_acc_top1, valid_acc_top5, valid_obj = infer(valid_queue, model, criterion) logging.info('Valid_acc_top1: %f', valid_acc_top1) logging.info('Valid_acc_top5: %f', valid_acc_top5) epoch_duration = time.time() - epoch_start logging.info('Epoch time: %ds.', epoch_duration) is_best = False if valid_acc_top5 > best_acc_top5: best_acc_top5 = valid_acc_top5 if valid_acc_top1 > best_acc_top1: best_acc_top1 = valid_acc_top1 is_best = True utils.save_checkpoint({ 'epoch': epoch + 1, 'state_dict': model.state_dict(), 'best_acc_top1': best_acc_top1, 'optimizer' : optimizer.state_dict(), }, is_best, args.save) def adjust_lr(optimizer, epoch): # Smaller slope for the last 5 epochs because lr * 1/250 is relatively large if args.epochs - epoch > 5: lr = args.learning_rate * (args.epochs - 5 - epoch) / (args.epochs - 5) else: lr = args.learning_rate * (args.epochs - epoch) / ((args.epochs - 5) * 5) for param_group in optimizer.param_groups: param_group['lr'] = lr return lr def train(train_queue, model, criterion, optimizer): objs = utils.AvgrageMeter() top1 = utils.AvgrageMeter() top5 = utils.AvgrageMeter() batch_time = utils.AvgrageMeter() model.train() for step, (input, target) in enumerate(train_queue): target = target.cuda(non_blocking=True) input = input.cuda(non_blocking=True) b_start = time.time() optimizer.zero_grad() logits, logits_aux = model(input) loss = criterion(logits, target) if args.auxiliary: loss_aux = criterion(logits_aux, target) loss += args.auxiliary_weight*loss_aux loss.backward() nn.utils.clip_grad_norm_(model.parameters(), args.grad_clip) optimizer.step() batch_time.update(time.time() - b_start) prec1, prec5 = utils.accuracy(logits, target, topk=(1, 5)) n = input.size(0) objs.update(loss.data.item(), n) top1.update(prec1.data.item(), n) top5.update(prec5.data.item(), n) if step % args.report_freq == 0: end_time = time.time() if step == 0: duration = 0 start_time = time.time() else: duration = end_time - start_time start_time = time.time() logging.info('TRAIN Step: %03d Objs: %e R1: %f R5: %f Duration: %ds BTime: %.3fs', step, objs.avg, top1.avg, top5.avg, duration, batch_time.avg) return top1.avg, objs.avg def infer(valid_queue, model, criterion): objs = utils.AvgrageMeter() top1 = utils.AvgrageMeter() top5 = utils.AvgrageMeter() model.eval() for step, (input, target) in enumerate(valid_queue): input = input.cuda() target = target.cuda(non_blocking=True) with torch.no_grad(): logits, _ = model(input) loss = criterion(logits, target) prec1, prec5 = utils.accuracy(logits, target, topk=(1, 5)) n = input.size(0) objs.update(loss.data.item(), n) top1.update(prec1.data.item(), n) top5.update(prec5.data.item(), n) if step % args.report_freq == 0: end_time = time.time() if step == 0: duration = 0 start_time = time.time() else: duration = end_time - start_time start_time = time.time() logging.info('VALID Step: %03d Objs: %e R1: %f R5: %f Duration: %ds', step, objs.avg, top1.avg, top5.avg, duration) return top1.avg, top5.avg, objs.avg if __name__ == '__main__': main()
10,818
38.922509
127
py
pdarts
pdarts-master/utils.py
import os import numpy as np import torch import shutil import torchvision.transforms as transforms from torch.autograd import Variable class AvgrageMeter(object): def __init__(self): self.reset() def reset(self): self.avg = 0 self.sum = 0 self.cnt = 0 def update(self, val, n=1): self.sum += val * n self.cnt += n self.avg = self.sum / self.cnt def accuracy(output, target, topk=(1,)): maxk = max(topk) batch_size = target.size(0) _, pred = output.topk(maxk, 1, True, True) pred = pred.t() correct = pred.eq(target.view(1, -1).expand_as(pred)) res = [] for k in topk: correct_k = correct[:k].view(-1).float().sum(0) res.append(correct_k.mul_(100.0/batch_size)) return res class Cutout(object): def __init__(self, length): self.length = length def __call__(self, img): h, w = img.size(1), img.size(2) mask = np.ones((h, w), np.float32) y = np.random.randint(h) x = np.random.randint(w) y1 = np.clip(y - self.length // 2, 0, h) y2 = np.clip(y + self.length // 2, 0, h) x1 = np.clip(x - self.length // 2, 0, w) x2 = np.clip(x + self.length // 2, 0, w) mask[y1: y2, x1: x2] = 0. mask = torch.from_numpy(mask) mask = mask.expand_as(img) img *= mask return img def _data_transforms_cifar10(args): CIFAR_MEAN = [0.49139968, 0.48215827, 0.44653124] CIFAR_STD = [0.24703233, 0.24348505, 0.26158768] train_transform = transforms.Compose([ transforms.RandomCrop(32, padding=4), transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Normalize(CIFAR_MEAN, CIFAR_STD), ]) if args.cutout: train_transform.transforms.append(Cutout(args.cutout_length)) valid_transform = transforms.Compose([ transforms.ToTensor(), transforms.Normalize(CIFAR_MEAN, CIFAR_STD), ]) return train_transform, valid_transform def _data_transforms_cifar100(args): CIFAR_MEAN = [0.5071, 0.4867, 0.4408] CIFAR_STD = [0.2675, 0.2565, 0.2761] train_transform = transforms.Compose([ transforms.RandomCrop(32, padding=4), transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Normalize(CIFAR_MEAN, CIFAR_STD), ]) if args.cutout: train_transform.transforms.append(Cutout(args.cutout_length)) valid_transform = transforms.Compose([ transforms.ToTensor(), transforms.Normalize(CIFAR_MEAN, CIFAR_STD), ]) return train_transform, valid_transform def count_parameters_in_MB(model): return np.sum(np.prod(v.size()) for name, v in model.named_parameters() if "auxiliary" not in name)/1e6 def save_checkpoint(state, is_best, save): filename = os.path.join(save, 'checkpoint.pth.tar') torch.save(state, filename) if is_best: best_filename = os.path.join(save, 'model_best.pth.tar') shutil.copyfile(filename, best_filename) def save(model, model_path): torch.save(model.state_dict(), model_path) def load(model, model_path): model.load_state_dict(torch.load(model_path)) def drop_path(x, drop_prob): if drop_prob > 0.: keep_prob = 1.-drop_prob mask = Variable(torch.cuda.FloatTensor(x.size(0), 1, 1, 1).bernoulli_(keep_prob)) x.div_(keep_prob) x.mul_(mask) return x def create_exp_dir(path, scripts_to_save=None): if not os.path.exists(path): os.mkdir(path) print('Experiment dir : {}'.format(path)) if scripts_to_save is not None: os.mkdir(os.path.join(path, 'scripts')) for script in scripts_to_save: dst_file = os.path.join(path, 'scripts', os.path.basename(script)) shutil.copyfile(script, dst_file)
3,652
24.907801
105
py
pdarts
pdarts-master/model.py
import torch import torch.nn as nn from operations import * from torch.autograd import Variable from utils import drop_path class Cell(nn.Module): def __init__(self, genotype, C_prev_prev, C_prev, C, reduction, reduction_prev): super(Cell, self).__init__() if reduction_prev: self.preprocess0 = FactorizedReduce(C_prev_prev, C) else: self.preprocess0 = ReLUConvBN(C_prev_prev, C, 1, 1, 0) self.preprocess1 = ReLUConvBN(C_prev, C, 1, 1, 0) if reduction: op_names, indices = zip(*genotype.reduce) concat = genotype.reduce_concat else: op_names, indices = zip(*genotype.normal) concat = genotype.normal_concat self._compile(C, op_names, indices, concat, reduction) def _compile(self, C, op_names, indices, concat, reduction): assert len(op_names) == len(indices) self._steps = len(op_names) // 2 self._concat = concat self.multiplier = len(concat) self._ops = nn.ModuleList() for name, index in zip(op_names, indices): stride = 2 if reduction and index < 2 else 1 op = OPS[name](C, stride, True) self._ops += [op] self._indices = indices def forward(self, s0, s1, drop_prob): s0 = self.preprocess0(s0) s1 = self.preprocess1(s1) states = [s0, s1] for i in range(self._steps): h1 = states[self._indices[2*i]] h2 = states[self._indices[2*i+1]] op1 = self._ops[2*i] op2 = self._ops[2*i+1] h1 = op1(h1) h2 = op2(h2) if self.training and drop_prob > 0.: if not isinstance(op1, Identity): h1 = drop_path(h1, drop_prob) if not isinstance(op2, Identity): h2 = drop_path(h2, drop_prob) s = h1 + h2 states += [s] return torch.cat([states[i] for i in self._concat], dim=1) class AuxiliaryHeadCIFAR(nn.Module): def __init__(self, C, num_classes): """assuming input size 8x8""" super(AuxiliaryHeadCIFAR, self).__init__() self.features = nn.Sequential( nn.ReLU(inplace=True), nn.AvgPool2d(5, stride=3, padding=0, count_include_pad=False), # image size = 2 x 2 nn.Conv2d(C, 128, 1, bias=False), nn.BatchNorm2d(128), nn.ReLU(inplace=True), nn.Conv2d(128, 768, 2, bias=False), nn.BatchNorm2d(768), nn.ReLU(inplace=True) ) self.classifier = nn.Linear(768, num_classes) def forward(self, x): x = self.features(x) x = self.classifier(x.view(x.size(0),-1)) return x class AuxiliaryHeadImageNet(nn.Module): def __init__(self, C, num_classes): """assuming input size 14x14""" super(AuxiliaryHeadImageNet, self).__init__() self.features = nn.Sequential( nn.ReLU(inplace=True), nn.AvgPool2d(5, stride=2, padding=0, count_include_pad=False), nn.Conv2d(C, 128, 1, bias=False), nn.BatchNorm2d(128), nn.ReLU(inplace=True), nn.Conv2d(128, 768, 2, bias=False), nn.BatchNorm2d(768), nn.ReLU(inplace=True) ) self.classifier = nn.Linear(768, num_classes) def forward(self, x): x = self.features(x) x = self.classifier(x.view(x.size(0),-1)) return x class NetworkCIFAR(nn.Module): def __init__(self, C, num_classes, layers, auxiliary, genotype): super(NetworkCIFAR, self).__init__() self._layers = layers self._auxiliary = auxiliary stem_multiplier = 3 C_curr = stem_multiplier*C self.stem = nn.Sequential( nn.Conv2d(3, C_curr, 3, padding=1, bias=False), nn.BatchNorm2d(C_curr) ) C_prev_prev, C_prev, C_curr = C_curr, C_curr, C self.cells = nn.ModuleList() reduction_prev = False for i in range(layers): if i in [layers//3, 2*layers//3]: C_curr *= 2 reduction = True else: reduction = False cell = Cell(genotype, C_prev_prev, C_prev, C_curr, reduction, reduction_prev) reduction_prev = reduction self.cells += [cell] C_prev_prev, C_prev = C_prev, cell.multiplier*C_curr if i == 2*layers//3: C_to_auxiliary = C_prev if auxiliary: self.auxiliary_head = AuxiliaryHeadCIFAR(C_to_auxiliary, num_classes) self.global_pooling = nn.AdaptiveAvgPool2d(1) self.classifier = nn.Linear(C_prev, num_classes) def forward(self, input): logits_aux = None s0 = s1 = self.stem(input) for i, cell in enumerate(self.cells): s0, s1 = s1, cell(s0, s1, self.drop_path_prob) if i == 2*self._layers//3: if self._auxiliary and self.training: logits_aux = self.auxiliary_head(s1) out = self.global_pooling(s1) logits = self.classifier(out.view(out.size(0),-1)) return logits, logits_aux class NetworkImageNet(nn.Module): def __init__(self, C, num_classes, layers, auxiliary, genotype): super(NetworkImageNet, self).__init__() self._layers = layers self._auxiliary = auxiliary self.stem0 = nn.Sequential( nn.Conv2d(3, C // 2, kernel_size=3, stride=2, padding=1, bias=False), nn.BatchNorm2d(C // 2), nn.ReLU(inplace=True), nn.Conv2d(C // 2, C, 3, stride=2, padding=1, bias=False), nn.BatchNorm2d(C), ) self.stem1 = nn.Sequential( nn.ReLU(inplace=True), nn.Conv2d(C, C, 3, stride=2, padding=1, bias=False), nn.BatchNorm2d(C), ) C_prev_prev, C_prev, C_curr = C, C, C self.cells = nn.ModuleList() reduction_prev = True for i in range(layers): if i in [layers // 3, 2 * layers // 3]: C_curr *= 2 reduction = True else: reduction = False cell = Cell(genotype, C_prev_prev, C_prev, C_curr, reduction, reduction_prev) reduction_prev = reduction self.cells += [cell] C_prev_prev, C_prev = C_prev, cell.multiplier * C_curr if i == 2 * layers // 3: C_to_auxiliary = C_prev if auxiliary: self.auxiliary_head = AuxiliaryHeadImageNet(C_to_auxiliary, num_classes) self.global_pooling = nn.AvgPool2d(7) self.classifier = nn.Linear(C_prev, num_classes) def forward(self, input): logits_aux = None s0 = self.stem0(input) s1 = self.stem1(s0) for i, cell in enumerate(self.cells): s0, s1 = s1, cell(s0, s1, self.drop_path_prob) if i == 2 * self._layers // 3: if self._auxiliary and self.training: logits_aux = self.auxiliary_head(s1) out = self.global_pooling(s1) logits = self.classifier(out.view(out.size(0), -1)) return logits, logits_aux
7,284
34.710784
95
py
pdarts
pdarts-master/model_search.py
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from operations import * from torch.autograd import Variable from genotypes import PRIMITIVES from genotypes import Genotype class MixedOp(nn.Module): def __init__(self, C, stride, switch, p): super(MixedOp, self).__init__() self.m_ops = nn.ModuleList() self.p = p for i in range(len(switch)): if switch[i]: primitive = PRIMITIVES[i] op = OPS[primitive](C, stride, False) if 'pool' in primitive: op = nn.Sequential(op, nn.BatchNorm2d(C, affine=False)) if isinstance(op, Identity) and p > 0: op = nn.Sequential(op, nn.Dropout(self.p)) self.m_ops.append(op) def update_p(self): for op in self.m_ops: if isinstance(op, nn.Sequential): if isinstance(op[0], Identity): op[1].p = self.p def forward(self, x, weights): return sum(w * op(x) for w, op in zip(weights, self.m_ops)) class Cell(nn.Module): def __init__(self, steps, multiplier, C_prev_prev, C_prev, C, reduction, reduction_prev, switches, p): super(Cell, self).__init__() self.reduction = reduction self.p = p if reduction_prev: self.preprocess0 = FactorizedReduce(C_prev_prev, C, affine=False) else: self.preprocess0 = ReLUConvBN(C_prev_prev, C, 1, 1, 0, affine=False) self.preprocess1 = ReLUConvBN(C_prev, C, 1, 1, 0, affine=False) self._steps = steps self._multiplier = multiplier self.cell_ops = nn.ModuleList() switch_count = 0 for i in range(self._steps): for j in range(2+i): stride = 2 if reduction and j < 2 else 1 op = MixedOp(C, stride, switch=switches[switch_count], p=self.p) self.cell_ops.append(op) switch_count = switch_count + 1 def update_p(self): for op in self.cell_ops: op.p = self.p op.update_p() def forward(self, s0, s1, weights): s0 = self.preprocess0(s0) s1 = self.preprocess1(s1) states = [s0, s1] offset = 0 for i in range(self._steps): s = sum(self.cell_ops[offset+j](h, weights[offset+j]) for j, h in enumerate(states)) offset += len(states) states.append(s) return torch.cat(states[-self._multiplier:], dim=1) class Network(nn.Module): def __init__(self, C, num_classes, layers, criterion, steps=4, multiplier=4, stem_multiplier=3, switches_normal=[], switches_reduce=[], p=0.0): super(Network, self).__init__() self._C = C self._num_classes = num_classes self._layers = layers self._criterion = criterion self._steps = steps self._multiplier = multiplier self.p = p self.switches_normal = switches_normal switch_ons = [] for i in range(len(switches_normal)): ons = 0 for j in range(len(switches_normal[i])): if switches_normal[i][j]: ons = ons + 1 switch_ons.append(ons) ons = 0 self.switch_on = switch_ons[0] C_curr = stem_multiplier*C self.stem = nn.Sequential( nn.Conv2d(3, C_curr, 3, padding=1, bias=False), nn.BatchNorm2d(C_curr) ) C_prev_prev, C_prev, C_curr = C_curr, C_curr, C self.cells = nn.ModuleList() reduction_prev = False for i in range(layers): if i in [layers//3, 2*layers//3]: C_curr *= 2 reduction = True cell = Cell(steps, multiplier, C_prev_prev, C_prev, C_curr, reduction, reduction_prev, switches_reduce, self.p) else: reduction = False cell = Cell(steps, multiplier, C_prev_prev, C_prev, C_curr, reduction, reduction_prev, switches_normal, self.p) # cell = Cell(steps, multiplier, C_prev_prev, C_prev, C_curr, reduction, reduction_prev, switches) reduction_prev = reduction self.cells += [cell] C_prev_prev, C_prev = C_prev, multiplier*C_curr self.global_pooling = nn.AdaptiveAvgPool2d(1) self.classifier = nn.Linear(C_prev, num_classes) self._initialize_alphas() def forward(self, input): s0 = s1 = self.stem(input) for i, cell in enumerate(self.cells): if cell.reduction: if self.alphas_reduce.size(1) == 1: weights = F.softmax(self.alphas_reduce, dim=0) else: weights = F.softmax(self.alphas_reduce, dim=-1) else: if self.alphas_normal.size(1) == 1: weights = F.softmax(self.alphas_normal, dim=0) else: weights = F.softmax(self.alphas_normal, dim=-1) s0, s1 = s1, cell(s0, s1, weights) out = self.global_pooling(s1) logits = self.classifier(out.view(out.size(0),-1)) return logits def update_p(self): for cell in self.cells: cell.p = self.p cell.update_p() def _loss(self, input, target): logits = self(input) return self._criterion(logits, target) def _initialize_alphas(self): k = sum(1 for i in range(self._steps) for n in range(2+i)) num_ops = self.switch_on self.alphas_normal = nn.Parameter(torch.FloatTensor(1e-3*np.random.randn(k, num_ops))) self.alphas_reduce = nn.Parameter(torch.FloatTensor(1e-3*np.random.randn(k, num_ops))) self._arch_parameters = [ self.alphas_normal, self.alphas_reduce, ] def arch_parameters(self): return self._arch_parameters
6,003
34.738095
147
py
pdarts
pdarts-master/train_search.py
import os import sys import time import glob import numpy as np import torch import utils import logging import argparse import torch.nn as nn import torch.utils import torch.nn.functional as F import torchvision.datasets as dset import torch.backends.cudnn as cudnn import copy from model_search import Network from genotypes import PRIMITIVES from genotypes import Genotype parser = argparse.ArgumentParser("cifar") parser.add_argument('--workers', type=int, default=2, help='number of workers to load dataset') parser.add_argument('--batch_size', type=int, default=96, help='batch size') parser.add_argument('--learning_rate', type=float, default=0.025, help='init learning rate') parser.add_argument('--learning_rate_min', type=float, default=0.0, help='min learning rate') parser.add_argument('--momentum', type=float, default=0.9, help='momentum') parser.add_argument('--weight_decay', type=float, default=3e-4, help='weight decay') parser.add_argument('--report_freq', type=float, default=50, help='report frequency') parser.add_argument('--epochs', type=int, default=25, help='num of training epochs') parser.add_argument('--init_channels', type=int, default=16, help='num of init channels') parser.add_argument('--layers', type=int, default=5, help='total number of layers') parser.add_argument('--cutout', action='store_true', default=False, help='use cutout') parser.add_argument('--cutout_length', type=int, default=16, help='cutout length') parser.add_argument('--drop_path_prob', type=float, default=0.3, help='drop path probability') parser.add_argument('--save', type=str, default='/tmp/checkpoints/', help='experiment path') parser.add_argument('--seed', type=int, default=2, help='random seed') parser.add_argument('--grad_clip', type=float, default=5, help='gradient clipping') parser.add_argument('--train_portion', type=float, default=0.5, help='portion of training data') parser.add_argument('--arch_learning_rate', type=float, default=6e-4, help='learning rate for arch encoding') parser.add_argument('--arch_weight_decay', type=float, default=1e-3, help='weight decay for arch encoding') parser.add_argument('--tmp_data_dir', type=str, default='/tmp/cache/', help='temp data dir') parser.add_argument('--note', type=str, default='try', help='note for this run') parser.add_argument('--dropout_rate', action='append', default=[], help='dropout rate of skip connect') parser.add_argument('--add_width', action='append', default=['0'], help='add channels') parser.add_argument('--add_layers', action='append', default=['0'], help='add layers') parser.add_argument('--cifar100', action='store_true', default=False, help='search with cifar100 dataset') args = parser.parse_args() args.save = '{}search-{}-{}'.format(args.save, args.note, time.strftime("%Y%m%d-%H%M%S")) utils.create_exp_dir(args.save, scripts_to_save=glob.glob('*.py')) log_format = '%(asctime)s %(message)s' logging.basicConfig(stream=sys.stdout, level=logging.INFO, format=log_format, datefmt='%m/%d %I:%M:%S %p') fh = logging.FileHandler(os.path.join(args.save, 'log.txt')) fh.setFormatter(logging.Formatter(log_format)) logging.getLogger().addHandler(fh) if args.cifar100: CIFAR_CLASSES = 100 data_folder = 'cifar-100-python' else: CIFAR_CLASSES = 10 data_folder = 'cifar-10-batches-py' def main(): if not torch.cuda.is_available(): logging.info('No GPU device available') sys.exit(1) np.random.seed(args.seed) cudnn.benchmark = True torch.manual_seed(args.seed) cudnn.enabled=True torch.cuda.manual_seed(args.seed) logging.info("args = %s", args) # prepare dataset if args.cifar100: train_transform, valid_transform = utils._data_transforms_cifar100(args) else: train_transform, valid_transform = utils._data_transforms_cifar10(args) if args.cifar100: train_data = dset.CIFAR100(root=args.tmp_data_dir, train=True, download=True, transform=train_transform) else: train_data = dset.CIFAR10(root=args.tmp_data_dir, train=True, download=True, transform=train_transform) num_train = len(train_data) indices = list(range(num_train)) split = int(np.floor(args.train_portion * num_train)) train_queue = torch.utils.data.DataLoader( train_data, batch_size=args.batch_size, sampler=torch.utils.data.sampler.SubsetRandomSampler(indices[:split]), pin_memory=True, num_workers=args.workers) valid_queue = torch.utils.data.DataLoader( train_data, batch_size=args.batch_size, sampler=torch.utils.data.sampler.SubsetRandomSampler(indices[split:num_train]), pin_memory=True, num_workers=args.workers) # build Network criterion = nn.CrossEntropyLoss() criterion = criterion.cuda() switches = [] for i in range(14): switches.append([True for j in range(len(PRIMITIVES))]) switches_normal = copy.deepcopy(switches) switches_reduce = copy.deepcopy(switches) # To be moved to args num_to_keep = [5, 3, 1] num_to_drop = [3, 2, 2] if len(args.add_width) == 3: add_width = args.add_width else: add_width = [0, 0, 0] if len(args.add_layers) == 3: add_layers = args.add_layers else: add_layers = [0, 6, 12] if len(args.dropout_rate) ==3: drop_rate = args.dropout_rate else: drop_rate = [0.0, 0.0, 0.0] eps_no_archs = [10, 10, 10] for sp in range(len(num_to_keep)): model = Network(args.init_channels + int(add_width[sp]), CIFAR_CLASSES, args.layers + int(add_layers[sp]), criterion, switches_normal=switches_normal, switches_reduce=switches_reduce, p=float(drop_rate[sp])) model = nn.DataParallel(model) model = model.cuda() logging.info("param size = %fMB", utils.count_parameters_in_MB(model)) network_params = [] for k, v in model.named_parameters(): if not (k.endswith('alphas_normal') or k.endswith('alphas_reduce')): network_params.append(v) optimizer = torch.optim.SGD( network_params, args.learning_rate, momentum=args.momentum, weight_decay=args.weight_decay) optimizer_a = torch.optim.Adam(model.module.arch_parameters(), lr=args.arch_learning_rate, betas=(0.5, 0.999), weight_decay=args.arch_weight_decay) scheduler = torch.optim.lr_scheduler.CosineAnnealingLR( optimizer, float(args.epochs), eta_min=args.learning_rate_min) sm_dim = -1 epochs = args.epochs eps_no_arch = eps_no_archs[sp] scale_factor = 0.2 for epoch in range(epochs): scheduler.step() lr = scheduler.get_lr()[0] logging.info('Epoch: %d lr: %e', epoch, lr) epoch_start = time.time() # training if epoch < eps_no_arch: model.module.p = float(drop_rate[sp]) * (epochs - epoch - 1) / epochs model.module.update_p() train_acc, train_obj = train(train_queue, valid_queue, model, network_params, criterion, optimizer, optimizer_a, lr, train_arch=False) else: model.module.p = float(drop_rate[sp]) * np.exp(-(epoch - eps_no_arch) * scale_factor) model.module.update_p() train_acc, train_obj = train(train_queue, valid_queue, model, network_params, criterion, optimizer, optimizer_a, lr, train_arch=True) logging.info('Train_acc %f', train_acc) epoch_duration = time.time() - epoch_start logging.info('Epoch time: %ds', epoch_duration) # validation if epochs - epoch < 5: valid_acc, valid_obj = infer(valid_queue, model, criterion) logging.info('Valid_acc %f', valid_acc) utils.save(model, os.path.join(args.save, 'weights.pt')) print('------Dropping %d paths------' % num_to_drop[sp]) # Save switches info for s-c refinement. if sp == len(num_to_keep) - 1: switches_normal_2 = copy.deepcopy(switches_normal) switches_reduce_2 = copy.deepcopy(switches_reduce) # drop operations with low architecture weights arch_param = model.module.arch_parameters() normal_prob = F.softmax(arch_param[0], dim=sm_dim).data.cpu().numpy() for i in range(14): idxs = [] for j in range(len(PRIMITIVES)): if switches_normal[i][j]: idxs.append(j) if sp == len(num_to_keep) - 1: # for the last stage, drop all Zero operations drop = get_min_k_no_zero(normal_prob[i, :], idxs, num_to_drop[sp]) else: drop = get_min_k(normal_prob[i, :], num_to_drop[sp]) for idx in drop: switches_normal[i][idxs[idx]] = False reduce_prob = F.softmax(arch_param[1], dim=-1).data.cpu().numpy() for i in range(14): idxs = [] for j in range(len(PRIMITIVES)): if switches_reduce[i][j]: idxs.append(j) if sp == len(num_to_keep) - 1: drop = get_min_k_no_zero(reduce_prob[i, :], idxs, num_to_drop[sp]) else: drop = get_min_k(reduce_prob[i, :], num_to_drop[sp]) for idx in drop: switches_reduce[i][idxs[idx]] = False logging.info('switches_normal = %s', switches_normal) logging_switches(switches_normal) logging.info('switches_reduce = %s', switches_reduce) logging_switches(switches_reduce) if sp == len(num_to_keep) - 1: arch_param = model.module.arch_parameters() normal_prob = F.softmax(arch_param[0], dim=sm_dim).data.cpu().numpy() reduce_prob = F.softmax(arch_param[1], dim=sm_dim).data.cpu().numpy() normal_final = [0 for idx in range(14)] reduce_final = [0 for idx in range(14)] # remove all Zero operations for i in range(14): if switches_normal_2[i][0] == True: normal_prob[i][0] = 0 normal_final[i] = max(normal_prob[i]) if switches_reduce_2[i][0] == True: reduce_prob[i][0] = 0 reduce_final[i] = max(reduce_prob[i]) # Generate Architecture, similar to DARTS keep_normal = [0, 1] keep_reduce = [0, 1] n = 3 start = 2 for i in range(3): end = start + n tbsn = normal_final[start:end] tbsr = reduce_final[start:end] edge_n = sorted(range(n), key=lambda x: tbsn[x]) keep_normal.append(edge_n[-1] + start) keep_normal.append(edge_n[-2] + start) edge_r = sorted(range(n), key=lambda x: tbsr[x]) keep_reduce.append(edge_r[-1] + start) keep_reduce.append(edge_r[-2] + start) start = end n = n + 1 # set switches according the ranking of arch parameters for i in range(14): if not i in keep_normal: for j in range(len(PRIMITIVES)): switches_normal[i][j] = False if not i in keep_reduce: for j in range(len(PRIMITIVES)): switches_reduce[i][j] = False # translate switches into genotype genotype = parse_network(switches_normal, switches_reduce) logging.info(genotype) ## restrict skipconnect (normal cell only) logging.info('Restricting skipconnect...') # generating genotypes with different numbers of skip-connect operations for sks in range(0, 9): max_sk = 8 - sks num_sk = check_sk_number(switches_normal) if not num_sk > max_sk: continue while num_sk > max_sk: normal_prob = delete_min_sk_prob(switches_normal, switches_normal_2, normal_prob) switches_normal = keep_1_on(switches_normal_2, normal_prob) switches_normal = keep_2_branches(switches_normal, normal_prob) num_sk = check_sk_number(switches_normal) logging.info('Number of skip-connect: %d', max_sk) genotype = parse_network(switches_normal, switches_reduce) logging.info(genotype) def train(train_queue, valid_queue, model, network_params, criterion, optimizer, optimizer_a, lr, train_arch=True): objs = utils.AvgrageMeter() top1 = utils.AvgrageMeter() top5 = utils.AvgrageMeter() for step, (input, target) in enumerate(train_queue): model.train() n = input.size(0) input = input.cuda() target = target.cuda(non_blocking=True) if train_arch: # In the original implementation of DARTS, it is input_search, target_search = next(iter(valid_queue), which slows down # the training when using PyTorch 0.4 and above. try: input_search, target_search = next(valid_queue_iter) except: valid_queue_iter = iter(valid_queue) input_search, target_search = next(valid_queue_iter) input_search = input_search.cuda() target_search = target_search.cuda(non_blocking=True) optimizer_a.zero_grad() logits = model(input_search) loss_a = criterion(logits, target_search) loss_a.backward() nn.utils.clip_grad_norm_(model.module.arch_parameters(), args.grad_clip) optimizer_a.step() optimizer.zero_grad() logits = model(input) loss = criterion(logits, target) loss.backward() nn.utils.clip_grad_norm_(network_params, args.grad_clip) optimizer.step() prec1, prec5 = utils.accuracy(logits, target, topk=(1, 5)) objs.update(loss.data.item(), n) top1.update(prec1.data.item(), n) top5.update(prec5.data.item(), n) if step % args.report_freq == 0: logging.info('TRAIN Step: %03d Objs: %e R1: %f R5: %f', step, objs.avg, top1.avg, top5.avg) return top1.avg, objs.avg def infer(valid_queue, model, criterion): objs = utils.AvgrageMeter() top1 = utils.AvgrageMeter() top5 = utils.AvgrageMeter() model.eval() for step, (input, target) in enumerate(valid_queue): input = input.cuda() target = target.cuda(non_blocking=True) with torch.no_grad(): logits = model(input) loss = criterion(logits, target) prec1, prec5 = utils.accuracy(logits, target, topk=(1, 5)) n = input.size(0) objs.update(loss.data.item(), n) top1.update(prec1.data.item(), n) top5.update(prec5.data.item(), n) if step % args.report_freq == 0: logging.info('valid %03d %e %f %f', step, objs.avg, top1.avg, top5.avg) return top1.avg, objs.avg def parse_network(switches_normal, switches_reduce): def _parse_switches(switches): n = 2 start = 0 gene = [] step = 4 for i in range(step): end = start + n for j in range(start, end): for k in range(len(switches[j])): if switches[j][k]: gene.append((PRIMITIVES[k], j - start)) start = end n = n + 1 return gene gene_normal = _parse_switches(switches_normal) gene_reduce = _parse_switches(switches_reduce) concat = range(2, 6) genotype = Genotype( normal=gene_normal, normal_concat=concat, reduce=gene_reduce, reduce_concat=concat ) return genotype def get_min_k(input_in, k): input = copy.deepcopy(input_in) index = [] for i in range(k): idx = np.argmin(input) index.append(idx) input[idx] = 1 return index def get_min_k_no_zero(w_in, idxs, k): w = copy.deepcopy(w_in) index = [] if 0 in idxs: zf = True else: zf = False if zf: w = w[1:] index.append(0) k = k - 1 for i in range(k): idx = np.argmin(w) w[idx] = 1 if zf: idx = idx + 1 index.append(idx) return index def logging_switches(switches): for i in range(len(switches)): ops = [] for j in range(len(switches[i])): if switches[i][j]: ops.append(PRIMITIVES[j]) logging.info(ops) def check_sk_number(switches): count = 0 for i in range(len(switches)): if switches[i][3]: count = count + 1 return count def delete_min_sk_prob(switches_in, switches_bk, probs_in): def _get_sk_idx(switches_in, switches_bk, k): if not switches_in[k][3]: idx = -1 else: idx = 0 for i in range(3): if switches_bk[k][i]: idx = idx + 1 return idx probs_out = copy.deepcopy(probs_in) sk_prob = [1.0 for i in range(len(switches_bk))] for i in range(len(switches_in)): idx = _get_sk_idx(switches_in, switches_bk, i) if not idx == -1: sk_prob[i] = probs_out[i][idx] d_idx = np.argmin(sk_prob) idx = _get_sk_idx(switches_in, switches_bk, d_idx) probs_out[d_idx][idx] = 0.0 return probs_out def keep_1_on(switches_in, probs): switches = copy.deepcopy(switches_in) for i in range(len(switches)): idxs = [] for j in range(len(PRIMITIVES)): if switches[i][j]: idxs.append(j) drop = get_min_k_no_zero(probs[i, :], idxs, 2) for idx in drop: switches[i][idxs[idx]] = False return switches def keep_2_branches(switches_in, probs): switches = copy.deepcopy(switches_in) final_prob = [0.0 for i in range(len(switches))] for i in range(len(switches)): final_prob[i] = max(probs[i]) keep = [0, 1] n = 3 start = 2 for i in range(3): end = start + n tb = final_prob[start:end] edge = sorted(range(n), key=lambda x: tb[x]) keep.append(edge[-1] + start) keep.append(edge[-2] + start) start = end n = n + 1 for i in range(len(switches)): if not i in keep: for j in range(len(PRIMITIVES)): switches[i][j] = False return switches if __name__ == '__main__': start_time = time.time() main() end_time = time.time() duration = end_time - start_time logging.info('Total searching time: %ds', duration)
19,015
39.545842
215
py
pdarts
pdarts-master/test_imagenet.py
import os import sys import numpy as np import torch import utils import glob import random import logging import argparse import torch.nn as nn import genotypes import torch.utils import torchvision.datasets as dset import torchvision.transforms as transforms import torch.backends.cudnn as cudnn from model import NetworkImageNet as Network parser = argparse.ArgumentParser("imagenet") parser.add_argument('--data', type=str, default='../data/imagenet/', help='location of the data corpus') parser.add_argument('--batch_size', type=int, default=128, help='batch size') parser.add_argument('--report_freq', type=float, default=100, help='report frequency') parser.add_argument('--init_channels', type=int, default=48, help='num of init channels') parser.add_argument('--layers', type=int, default=14, help='total number of layers') parser.add_argument('--model_path', type=str, default='../models/imagenet.pth.tar', help='path of pretrained model') parser.add_argument('--auxiliary', action='store_true', default=False, help='use auxiliary tower') parser.add_argument('--arch', type=str, default='PDARTS', help='which architecture to use') args = parser.parse_args() log_format = '%(asctime)s %(message)s' logging.basicConfig(stream=sys.stdout, level=logging.INFO, format=log_format, datefmt='%m/%d %I:%M:%S %p') CLASSES = 1000 def main(): if not torch.cuda.is_available(): logging.info('no gpu device available') sys.exit(1) cudnn.enabled=True logging.info("args = %s", args) genotype = eval("genotypes.%s" % args.arch) model = Network(args.init_channels, CLASSES, args.layers, args.auxiliary, genotype) model = nn.DataParallel(model) model = model.cuda() model.load_state_dict(torch.load(args.model_path)['state_dict']) logging.info("param size = %fMB", utils.count_parameters_in_MB(model)) criterion = nn.CrossEntropyLoss() criterion = criterion.cuda() validdir = os.path.join(args.data, 'val') normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) valid_data = dset.ImageFolder( validdir, transforms.Compose([ transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(), normalize, ])) valid_queue = torch.utils.data.DataLoader( valid_data, batch_size=args.batch_size, shuffle=False, pin_memory=False, num_workers=4) model.module.drop_path_prob = 0.0 valid_acc_top1, valid_acc_top5, valid_obj = infer(valid_queue, model, criterion) logging.info('Valid_acc_top1 %f', valid_acc_top1) logging.info('Valid_acc_top5 %f', valid_acc_top5) def infer(valid_queue, model, criterion): objs = utils.AvgrageMeter() top1 = utils.AvgrageMeter() top5 = utils.AvgrageMeter() model.eval() for step, (input, target) in enumerate(valid_queue): input = input.cuda() target = target.cuda() with torch.no_grad(): logits, _ = model(input) loss = criterion(logits, target) prec1, prec5 = utils.accuracy(logits, target, topk=(1, 5)) n = input.size(0) objs.update(loss.data.item(), n) top1.update(prec1.data.item(), n) top5.update(prec5.data.item(), n) if step % args.report_freq == 0: logging.info('Valid %03d %e %f %f', step, objs.avg, top1.avg, top5.avg) return top1.avg, top5.avg, objs.avg if __name__ == '__main__': main()
3,334
31.378641
116
py
pdarts
pdarts-master/train_cifar.py
import os import sys import time import glob import numpy as np import torch import utils import logging import argparse import torch.nn as nn import genotypes import torch.utils import torchvision.datasets as dset import torch.backends.cudnn as cudnn from torch.autograd import Variable from model import NetworkCIFAR as Network parser = argparse.ArgumentParser("cifar") parser.add_argument('--workers', type=int, default=4, help='number of workers') parser.add_argument('--batch_size', type=int, default=128, help='batch size') parser.add_argument('--learning_rate', type=float, default=0.025, help='init learning rate') parser.add_argument('--momentum', type=float, default=0.9, help='momentum') parser.add_argument('--weight_decay', type=float, default=3e-4, help='weight decay') parser.add_argument('--report_freq', type=float, default=50, help='report frequency') parser.add_argument('--epochs', type=int, default=600, help='num of training epochs') parser.add_argument('--init_channels', type=int, default=36, help='num of init channels') parser.add_argument('--layers', type=int, default=20, help='total number of layers') parser.add_argument('--auxiliary', action='store_true', default=False, help='use auxiliary tower') parser.add_argument('--auxiliary_weight', type=float, default=0.4, help='weight for auxiliary loss') parser.add_argument('--cutout', action='store_true', default=False, help='use cutout') parser.add_argument('--cutout_length', type=int, default=16, help='cutout length') parser.add_argument('--drop_path_prob', type=float, default=0.3, help='drop path probability') parser.add_argument('--save', type=str, default='/tmp/checkpoints/', help='experiment name') parser.add_argument('--seed', type=int, default=0, help='random seed') parser.add_argument('--arch', type=str, default='PDARTS', help='which architecture to use') parser.add_argument('--grad_clip', type=float, default=5, help='gradient clipping') parser.add_argument('--tmp_data_dir', type=str, default='/tmp/cache/', help='temp data dir') parser.add_argument('--note', type=str, default='try', help='note for this run') parser.add_argument('--cifar100', action='store_true', default=False, help='if use cifar100') args, unparsed = parser.parse_known_args() args.save = '{}eval-{}-{}'.format(args.save, args.note, time.strftime("%Y%m%d-%H%M%S")) utils.create_exp_dir(args.save, scripts_to_save=glob.glob('*.py')) log_format = '%(asctime)s %(message)s' logging.basicConfig(stream=sys.stdout, level=logging.INFO, format=log_format, datefmt='%m/%d %I:%M:%S %p') fh = logging.FileHandler(os.path.join(args.save, 'log.txt')) fh.setFormatter(logging.Formatter(log_format)) logging.getLogger().addHandler(fh) if args.cifar100: CIFAR_CLASSES = 100 data_folder = 'cifar-100-python' else: CIFAR_CLASSES = 10 data_folder = 'cifar-10-batches-py' def main(): if not torch.cuda.is_available(): logging.info('No GPU device available') sys.exit(1) np.random.seed(args.seed) cudnn.benchmark = True torch.manual_seed(args.seed) cudnn.enabled=True torch.cuda.manual_seed(args.seed) logging.info("args = %s", args) logging.info("unparsed args = %s", unparsed) num_gpus = torch.cuda.device_count() genotype = eval("genotypes.%s" % args.arch) print('---------Genotype---------') logging.info(genotype) print('--------------------------') model = Network(args.init_channels, CIFAR_CLASSES, args.layers, args.auxiliary, genotype) model = torch.nn.DataParallel(model) model = model.cuda() logging.info("param size = %fMB", utils.count_parameters_in_MB(model)) criterion = nn.CrossEntropyLoss() criterion = criterion.cuda() optimizer = torch.optim.SGD( model.parameters(), args.learning_rate, momentum=args.momentum, weight_decay=args.weight_decay ) if args.cifar100: train_transform, valid_transform = utils._data_transforms_cifar100(args) else: train_transform, valid_transform = utils._data_transforms_cifar10(args) if args.cifar100: train_data = dset.CIFAR100(root=args.tmp_data_dir, train=True, download=True, transform=train_transform) valid_data = dset.CIFAR100(root=args.tmp_data_dir, train=False, download=True, transform=valid_transform) else: train_data = dset.CIFAR10(root=args.tmp_data_dir, train=True, download=True, transform=train_transform) valid_data = dset.CIFAR10(root=args.tmp_data_dir, train=False, download=True, transform=valid_transform) train_queue = torch.utils.data.DataLoader( train_data, batch_size=args.batch_size, shuffle=True, pin_memory=True, num_workers=args.workers) valid_queue = torch.utils.data.DataLoader( valid_data, batch_size=args.batch_size, shuffle=False, pin_memory=True, num_workers=args.workers) scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, float(args.epochs)) best_acc = 0.0 for epoch in range(args.epochs): scheduler.step() logging.info('Epoch: %d lr %e', epoch, scheduler.get_lr()[0]) model.module.drop_path_prob = args.drop_path_prob * epoch / args.epochs model.drop_path_prob = args.drop_path_prob * epoch / args.epochs start_time = time.time() train_acc, train_obj = train(train_queue, model, criterion, optimizer) logging.info('Train_acc: %f', train_acc) valid_acc, valid_obj = infer(valid_queue, model, criterion) if valid_acc > best_acc: best_acc = valid_acc logging.info('Valid_acc: %f', valid_acc) end_time = time.time() duration = end_time - start_time print('Epoch time: %ds.' % duration ) utils.save(model.module, os.path.join(args.save, 'weights.pt')) def train(train_queue, model, criterion, optimizer): objs = utils.AvgrageMeter() top1 = utils.AvgrageMeter() model.train() for step, (input, target) in enumerate(train_queue): input = input.cuda(non_blocking=True) target = target.cuda(non_blocking=True) optimizer.zero_grad() logits, logits_aux = model(input) loss = criterion(logits, target) if args.auxiliary: loss_aux = criterion(logits_aux, target) loss += args.auxiliary_weight*loss_aux loss.backward() nn.utils.clip_grad_norm_(model.parameters(), args.grad_clip) optimizer.step() prec1, _ = utils.accuracy(logits, target, topk=(1,5)) n = input.size(0) objs.update(loss.data.item(), n) top1.update(prec1.data.item(), n) if step % args.report_freq == 0: logging.info('Train Step: %03d Objs: %e Acc: %f', step, objs.avg, top1.avg) return top1.avg, objs.avg def infer(valid_queue, model, criterion): objs = utils.AvgrageMeter() top1 = utils.AvgrageMeter() model.eval() for step, (input, target) in enumerate(valid_queue): input = input.cuda(non_blocking=True) target = target.cuda(non_blocking=True) with torch.no_grad(): logits, _ = model(input) loss = criterion(logits, target) prec1, _ = utils.accuracy(logits, target, topk=(1,5)) n = input.size(0) objs.update(loss.data.item(), n) top1.update(prec1.data.item(), n) if step % args.report_freq == 0: logging.info('Valid Step: %03d Objs: %e Acc: %f', step, objs.avg, top1.avg) return top1.avg, objs.avg if __name__ == '__main__': start_time = time.time() main() end_time = time.time() duration = end_time - start_time logging.info('Eval time: %ds.', duration)
7,688
39.68254
113
py
pdarts
pdarts-master/visualize.py
import sys import genotypes from graphviz import Digraph def plot(genotype, filename): g = Digraph( format='pdf', edge_attr=dict(fontsize='20', fontname="times"), node_attr=dict(style='filled', shape='rect', align='center', fontsize='20', height='0.5', width='0.5', penwidth='2', fontname="times"), engine='dot') g.body.extend(['rankdir=LR']) g.node("c_{k-2}", fillcolor='darkseagreen2') g.node("c_{k-1}", fillcolor='darkseagreen2') assert len(genotype) % 2 == 0 steps = len(genotype) // 2 for i in range(steps): g.node(str(i), fillcolor='lightblue') for i in range(steps): for k in [2*i, 2*i + 1]: op, j = genotype[k] if j == 0: u = "c_{k-2}" elif j == 1: u = "c_{k-1}" else: u = str(j-2) v = str(i) g.edge(u, v, label=op, fillcolor="gray") g.node("c_{k}", fillcolor='palegoldenrod') for i in range(steps): g.edge(str(i), "c_{k}", fillcolor="gray") g.render(filename, view=True) if __name__ == '__main__': if len(sys.argv) != 2: print("usage:\n python {} ARCH_NAME".format(sys.argv[0])) sys.exit(1) genotype_name = sys.argv[1] try: genotype = eval('genotypes.{}'.format(genotype_name)) except AttributeError: print("{} is not specified in genotypes.py".format(genotype_name)) sys.exit(1) plot(genotype.normal, "normal") plot(genotype.reduce, "reduction")
1,419
24.357143
141
py
pdarts
pdarts-master/genotypes.py
from collections import namedtuple Genotype = namedtuple('Genotype', 'normal normal_concat reduce reduce_concat') PRIMITIVES = [ 'none', 'max_pool_3x3', 'avg_pool_3x3', 'skip_connect', 'sep_conv_3x3', 'sep_conv_5x5', 'dil_conv_3x3', 'dil_conv_5x5' ] NASNet = Genotype( normal = [ ('sep_conv_5x5', 1), ('sep_conv_3x3', 0), ('sep_conv_5x5', 0), ('sep_conv_3x3', 0), ('avg_pool_3x3', 1), ('skip_connect', 0), ('avg_pool_3x3', 0), ('avg_pool_3x3', 0), ('sep_conv_3x3', 1), ('skip_connect', 1), ], normal_concat = [2, 3, 4, 5, 6], reduce = [ ('sep_conv_5x5', 1), ('sep_conv_7x7', 0), ('max_pool_3x3', 1), ('sep_conv_7x7', 0), ('avg_pool_3x3', 1), ('sep_conv_5x5', 0), ('skip_connect', 3), ('avg_pool_3x3', 2), ('sep_conv_3x3', 2), ('max_pool_3x3', 1), ], reduce_concat = [4, 5, 6], ) AmoebaNet = Genotype( normal = [ ('avg_pool_3x3', 0), ('max_pool_3x3', 1), ('sep_conv_3x3', 0), ('sep_conv_5x5', 2), ('sep_conv_3x3', 0), ('avg_pool_3x3', 3), ('sep_conv_3x3', 1), ('skip_connect', 1), ('skip_connect', 0), ('avg_pool_3x3', 1), ], normal_concat = [4, 5, 6], reduce = [ ('avg_pool_3x3', 0), ('sep_conv_3x3', 1), ('max_pool_3x3', 0), ('sep_conv_7x7', 2), ('sep_conv_7x7', 0), ('avg_pool_3x3', 1), ('max_pool_3x3', 0), ('max_pool_3x3', 1), ('conv_7x1_1x7', 0), ('sep_conv_3x3', 5), ], reduce_concat = [3, 4, 6] ) DARTS_V1 = Genotype(normal=[('sep_conv_3x3', 1), ('sep_conv_3x3', 0), ('skip_connect', 0), ('sep_conv_3x3', 1), ('skip_connect', 0), ('sep_conv_3x3', 1), ('sep_conv_3x3', 0), ('skip_connect', 2)], normal_concat=[2, 3, 4, 5], reduce=[('max_pool_3x3', 0), ('max_pool_3x3', 1), ('skip_connect', 2), ('max_pool_3x3', 0), ('max_pool_3x3', 0), ('skip_connect', 2), ('skip_connect', 2), ('avg_pool_3x3', 0)], reduce_concat=[2, 3, 4, 5]) DARTS_V2 = Genotype(normal=[('sep_conv_3x3', 0), ('sep_conv_3x3', 1), ('sep_conv_3x3', 0), ('sep_conv_3x3', 1), ('sep_conv_3x3', 1), ('skip_connect', 0), ('skip_connect', 0), ('dil_conv_3x3', 2)], normal_concat=[2, 3, 4, 5], reduce=[('max_pool_3x3', 0), ('max_pool_3x3', 1), ('skip_connect', 2), ('max_pool_3x3', 1), ('max_pool_3x3', 0), ('skip_connect', 2), ('skip_connect', 2), ('max_pool_3x3', 1)], reduce_concat=[2, 3, 4, 5]) PDARTS = Genotype(normal=[('skip_connect', 0), ('dil_conv_3x3', 1), ('skip_connect', 0),('sep_conv_3x3', 1), ('sep_conv_3x3', 1), ('sep_conv_3x3', 3), ('sep_conv_3x3',0), ('dil_conv_5x5', 4)], normal_concat=range(2, 6), reduce=[('avg_pool_3x3', 0), ('sep_conv_5x5', 1), ('sep_conv_3x3', 0), ('dil_conv_5x5', 2), ('max_pool_3x3', 0), ('dil_conv_3x3', 1), ('dil_conv_3x3', 1), ('dil_conv_5x5', 3)], reduce_concat=range(2, 6))
2,818
34.2375
429
py
pdarts
pdarts-master/operations.py
import torch import torch.nn as nn OPS = { 'none' : lambda C, stride, affine: Zero(stride), 'avg_pool_3x3' : lambda C, stride, affine: nn.AvgPool2d(3, stride=stride, padding=1, count_include_pad=False), 'max_pool_3x3' : lambda C, stride, affine: nn.MaxPool2d(3, stride=stride, padding=1), 'skip_connect' : lambda C, stride, affine: Identity() if stride == 1 else FactorizedReduce(C, C, affine=affine), 'sep_conv_3x3' : lambda C, stride, affine: SepConv(C, C, 3, stride, 1, affine=affine), 'sep_conv_5x5' : lambda C, stride, affine: SepConv(C, C, 5, stride, 2, affine=affine), 'sep_conv_7x7' : lambda C, stride, affine: SepConv(C, C, 7, stride, 3, affine=affine), 'dil_conv_3x3' : lambda C, stride, affine: DilConv(C, C, 3, stride, 2, 2, affine=affine), 'dil_conv_5x5' : lambda C, stride, affine: DilConv(C, C, 5, stride, 4, 2, affine=affine), 'conv_7x1_1x7' : lambda C, stride, affine: nn.Sequential( nn.ReLU(inplace=False), nn.Conv2d(C, C, (1,7), stride=(1, stride), padding=(0, 3), bias=False), nn.Conv2d(C, C, (7,1), stride=(stride, 1), padding=(3, 0), bias=False), nn.BatchNorm2d(C, affine=affine) ), } class ReLUConvBN(nn.Module): def __init__(self, C_in, C_out, kernel_size, stride, padding, affine=True): super(ReLUConvBN, self).__init__() self.op = nn.Sequential( nn.ReLU(inplace=False), nn.Conv2d(C_in, C_out, kernel_size, stride=stride, padding=padding, bias=False), nn.BatchNorm2d(C_out, affine=affine) ) def forward(self, x): return self.op(x) class DilConv(nn.Module): def __init__(self, C_in, C_out, kernel_size, stride, padding, dilation, affine=True): super(DilConv, self).__init__() self.op = nn.Sequential( nn.ReLU(inplace=False), nn.Conv2d(C_in, C_in, kernel_size=kernel_size, stride=stride, padding=padding, dilation=dilation, groups=C_in, bias=False), nn.Conv2d(C_in, C_out, kernel_size=1, padding=0, bias=False), nn.BatchNorm2d(C_out, affine=affine), ) def forward(self, x): return self.op(x) class SepConv(nn.Module): def __init__(self, C_in, C_out, kernel_size, stride, padding, affine=True): super(SepConv, self).__init__() self.op = nn.Sequential( nn.ReLU(inplace=False), nn.Conv2d(C_in, C_in, kernel_size=kernel_size, stride=stride, padding=padding, groups=C_in, bias=False), nn.Conv2d(C_in, C_in, kernel_size=1, padding=0, bias=False), nn.BatchNorm2d(C_in, affine=affine), nn.ReLU(inplace=False), nn.Conv2d(C_in, C_in, kernel_size=kernel_size, stride=1, padding=padding, groups=C_in, bias=False), nn.Conv2d(C_in, C_out, kernel_size=1, padding=0, bias=False), nn.BatchNorm2d(C_out, affine=affine), ) def forward(self, x): return self.op(x) class Identity(nn.Module): def __init__(self): super(Identity, self).__init__() def forward(self, x): return x ''' class Zero(nn.Module): def __init__(self, stride): super(Zero, self).__init__() self.stride = stride def forward(self, x): if self.stride == 1: return x.mul(0.) return x[:,:,::self.stride,::self.stride].mul(0.) ''' class Zero(nn.Module): def __init__(self, stride): super(Zero, self).__init__() self.stride = stride def forward(self, x): n, c, h, w = x.size() h //= self.stride w //= self.stride if x.is_cuda: with torch.cuda.device(x.get_device()): padding = torch.cuda.FloatTensor(n, c, h, w).fill_(0) else: padding = torch.FloatTensor(n, c, h, w).fill_(0) return padding class FactorizedReduce(nn.Module): def __init__(self, C_in, C_out, affine=True): super(FactorizedReduce, self).__init__() assert C_out % 2 == 0 self.relu = nn.ReLU(inplace=False) self.conv_1 = nn.Conv2d(C_in, C_out // 2, 1, stride=2, padding=0, bias=False) self.conv_2 = nn.Conv2d(C_in, C_out // 2, 1, stride=2, padding=0, bias=False) self.bn = nn.BatchNorm2d(C_out, affine=affine) def forward(self, x): x = self.relu(x) out = torch.cat([self.conv_1(x), self.conv_2(x[:,:,1:,1:])], dim=1) out = self.bn(out) return out
4,144
32.97541
129
py
pytorch-kaldi-gan
pytorch-kaldi-gan-master/run_exp.py
########################################################## # pytorch-kaldi-gan # Walter Heymans # North West University # 2020 # Adapted from: # pytorch-kaldi v.0.1 # Mirco Ravanelli, Titouan Parcollet # Mila, University of Montreal # October 2018 ########################################################## from __future__ import print_function import os import sys import glob import configparser import numpy as np from utils import ( check_cfg, create_lists, create_configs, compute_avg_performance, read_args_command_line, run_shell, compute_n_chunks, get_all_archs, cfg_item2sec, dump_epoch_results, create_curves, change_lr_cfg, expand_str_ep, do_validation_after_chunk, get_val_info_file_path, get_val_cfg_file_path, get_chunks_after_which_to_validate, ) from data_io import read_lab_fea_refac01 as read_lab_fea from shutil import copyfile from core import read_next_chunk_into_shared_list_with_subprocess, extract_data_from_shared_list, convert_numpy_to_torch import re from distutils.util import strtobool import importlib import math import multiprocessing import weights_and_biases as wandb import torch skip_decode = False def _run_forwarding_in_subprocesses(config): use_cuda = strtobool(config["exp"]["use_cuda"]) if use_cuda: return False else: return True def _is_first_validation(ep, ck, N_ck_tr, config): def _get_nr_of_valid_per_epoch_from_config(config): if not "nr_of_valid_per_epoch" in config["exp"]: return 1 return int(config["exp"]["nr_of_valid_per_epoch"]) if ep>0: return False val_chunks = get_chunks_after_which_to_validate(N_ck_tr, _get_nr_of_valid_per_epoch_from_config(config)) if ck == val_chunks[0]: return True return False def _max_nr_of_parallel_forwarding_processes(config): if "max_nr_of_parallel_forwarding_processes" in config["forward"]: return int(config["forward"]["max_nr_of_parallel_forwarding_processes"]) return -1 def print_version_info(): print("") print("".center(40, "#")) print(" Pytorch-Kaldi-GAN ".center(38, " ").center(40, "#")) print(" Walter Heymans ".center(38, " ").center(40, "#")) print(" North West University ".center(38, " ").center(40, "#")) print(" 2020 ".center(38, " ").center(40, "#")) print("".center(38, " ").center(40, "#")) print(" Adapted form: ".center(38, " ").center(40, "#")) print(" Pytorch-Kaldi v.0.1 ".center(38, " ").center(40, "#")) print(" Mirco Ravanelli, Titouan Parcollet ".center(38, " ").center(40, "#")) print(" Mila, University of Montreal ".center(38, " ").center(40, "#")) print(" October 2018 ".center(38, " ").center(40, "#")) print("".center(40, "#"), end="\n\n") # START OF EXECUTION # print_version_info() # Reading global cfg file (first argument-mandatory file) cfg_file = sys.argv[1] if not (os.path.exists(cfg_file)): sys.stderr.write("ERROR: The config file %s does not exist!\n" % (cfg_file)) sys.exit(0) else: config = configparser.ConfigParser() config.read(cfg_file) config_file_name = str(os.path.basename(cfg_file)).replace(".cfg", "") # Reading and parsing optional arguments from command line (e.g.,--optimization,lr=0.002) [section_args, field_args, value_args] = read_args_command_line(sys.argv, config) # Output folder creation out_folder = config["exp"]["out_folder"] if not os.path.exists(out_folder): os.makedirs(out_folder + "/exp_files") # Log file path log_file = config["exp"]["out_folder"] + "/log.log" # Read, parse, and check the config file cfg_file_proto = config["cfg_proto"]["cfg_proto"] [config, name_data, name_arch] = check_cfg(cfg_file, config, cfg_file_proto) # Read cfg file options is_production = strtobool(config["exp"]["production"]) cfg_file_proto_chunk = config["cfg_proto"]["cfg_proto_chunk"] cmd = config["exp"]["cmd"] N_ep = int(config["exp"]["N_epochs_tr"]) N_ep_str_format = "0" + str(max(math.ceil(np.log10(N_ep)), 1)) + "d" tr_data_lst = config["data_use"]["train_with"].split(",") valid_data_lst = config["data_use"]["valid_with"].split(",") forward_data_lst = config["data_use"]["forward_with"].split(",") max_seq_length_train = config["batches"]["max_seq_length_train"] forward_save_files = list(map(strtobool, config["forward"]["save_out_file"].split(","))) print("- Reading config file......OK!") # Copy the global cfg file into the output folder cfg_file = out_folder + "/conf.cfg" with open(cfg_file, "w") as configfile: config.write(configfile) # Load the run_nn function from core libriary # The run_nn is a function that process a single chunk of data run_nn_script = config["exp"]["run_nn_script"].split(".py")[0] module = importlib.import_module("core") run_nn = getattr(module, run_nn_script) # Splitting data into chunks (see out_folder/additional_files) create_lists(config) # Writing the config files create_configs(config) print("- Chunk creation......OK!\n") # create res_file res_file_path = out_folder + "/res.res" res_file = open(res_file_path, "w") res_file.close() # Learning rates and architecture-specific optimization parameters arch_lst = get_all_archs(config) lr = {} auto_lr_annealing = {} improvement_threshold = {} halving_factor = {} pt_files = {} for arch in arch_lst: lr[arch] = expand_str_ep(config[arch]["arch_lr"], "float", N_ep, "|", "*") if len(config[arch]["arch_lr"].split("|")) > 1: auto_lr_annealing[arch] = False else: auto_lr_annealing[arch] = True improvement_threshold[arch] = float(config[arch]["arch_improvement_threshold"]) halving_factor[arch] = float(config[arch]["arch_halving_factor"]) pt_files[arch] = config[arch]["arch_pretrain_file"] # If production, skip training and forward directly from last saved models if is_production: ep = N_ep - 1 N_ep = 0 model_files = {} for arch in pt_files.keys(): model_files[arch] = out_folder + "/exp_files/final_" + arch + ".pkl" op_counter = 1 # used to dected the next configuration file from the list_chunks.txt # Reading the ordered list of config file to process cfg_file_list = [line.rstrip("\n") for line in open(out_folder + "/exp_files/list_chunks.txt")] cfg_file_list.append(cfg_file_list[-1]) # A variable that tells if the current chunk is the first one that is being processed: processed_first = True data_name = [] data_set = [] data_end_index = [] fea_dict = [] lab_dict = [] arch_dict = [] if config["gan"]["arch_gan"] == "True": gan_on = True # Checking directories directory_g = os.path.join(out_folder, config["gan"]["output_path_g"]) directory_d = os.path.join(out_folder, config["gan"]["output_path_d"]) gan_dir = os.path.dirname(directory_g) if not os.path.exists(gan_dir): os.mkdir(gan_dir) if not os.path.exists(gan_dir + "/images"): os.mkdir(gan_dir + "/images") try: if str(config["generator"]["pretrained_file"]) != "none": if os.path.exists(str(config["generator"]["pretrained_file"])): copyfile(str(config["generator"]["pretrained_file"]), directory_g) print("Loaded pretrained G.") except KeyError: pass try: if str(config["discriminator"]["pretrained_file"]) != "none": if os.path.exists(str(config["discriminator"]["pretrained_file"])): copyfile(str(config["discriminator"]["pretrained_file"]), directory_d) print("Loaded pretrained D.") except KeyError: pass else: gan_on = False def print_settings(): print_width = 72 print(" SETTINGS ".center(print_width, "=")) print("# Epochs:\t\t", N_ep) print("# Batch size:\t\t", int(config["batches"]["batch_size_train"])) print("# Seed:\t\t\t", int(config["exp"]["seed"])) print("# Weights and Biases:\t", str(config["wandb"]["wandb"])) print("# GAN training:\t\t", str(config["gan"]["arch_gan"])) print("") print(" Acoustic Model settings ".center(print_width, "-")) print("# Name:\t\t\t", str(config["architecture1"]["arch_name"])) print("# Learning rate:\t", float(config["architecture1"]["arch_lr"])) print("# Halving factor:\t", float(config["architecture1"]["arch_halving_factor"])) print("# Improvement threshold:", float(config["architecture1"]["arch_improvement_threshold"])) print("# Optimizer:\t\t", str(config["architecture1"]["arch_opt"])) try: if config["gan"]["double_features"] == "True": print("# Double features:\t", config["gan"]["double_features"]) except KeyError: pass if gan_on: print("") print(" Generator Architecture ".center(print_width, "-")) print("# Name:\t\t\t", str(config["generator"]["arch_name"])) print("=".center(print_width, "="), end = "\n\n") print_settings() if str(config["wandb"]["wandb"]) == "True": wandb_cfg = wandb.load_cfg_dict_from_yaml(str(config["wandb"]["config"])) # UPDATE config file if Weights and Biases file is different wandb_cfg["max_epochs"] = int(config["exp"]["N_epochs_tr"]) wandb_cfg["seed"] = int(config["exp"]["seed"]) wandb_cfg["batch_size"] = int(config["batches"]["batch_size_train"]) wandb_cfg["lr"] = float(config["architecture1"]["arch_lr"]) wandb_cfg["gan_on"] = config["gan"]["arch_gan"] wandb_details = os.path.join(out_folder, "wandb_details.txt") if not os.path.exists(wandb_details): wandb_details_file = open(wandb_details, "w") wandb.initialize_wandb(project = str(config["wandb"]["project"]), config = wandb_cfg, directory = out_folder, resume = False) try: wandb_details_file.write(wandb.get_run_id() + '\n') wandb_details_file.write(wandb.get_run_name()) except TypeError: pass wandb_details_file.close() else: wandb_details_file = open(wandb_details, "r") file_content = wandb_details_file.read().splitlines() try: wandb_run_id = file_content[0] wandb_run_name = file_content[1] except IndexError: wandb_run_id = "" wandb_run_name = "" pass wandb_details_file.close() if not wandb_run_id == "": wandb.initialize_wandb(project = str(config["wandb"]["project"]), config = wandb_cfg, directory = out_folder, resume = True, identity = wandb_run_id, name = wandb_run_name) else: wandb.initialize_wandb(project = str(config["wandb"]["project"]), config = wandb_cfg, directory = out_folder, resume = True) if str(config["wandb"]["decode_only"]) == "True": wandb_decode_only = True wandb_on = False else: wandb_on = True wandb_decode_only = False wandb.quick_log("status", "training", commit = False) else: wandb_on = False wandb_decode_only = False create_gan_dataset = False try: if config["ganset"]["create_set"] == "True": create_gan_dataset = True print("\nGAN dataset will be created.\n") # Output folder creation gan_out_folder = config["ganset"]["out_folder"] if not os.path.exists(gan_out_folder): os.makedirs(gan_out_folder) except KeyError: pass fine_tuning = True try: if config["exp"]["fine_tuning"] == "False": fine_tuning = False except KeyError: pass # --------TRAINING LOOP--------# for ep in range(N_ep): if wandb_on: wandb.quick_log("epoch", ep + 1, commit = False) processed_first = True tr_loss_tot = 0 tr_error_tot = 0 tr_time_tot = 0 val_time_tot = 0 print( "------------------------------ Epoch %s / %s ------------------------------" % (format(ep + 1, N_ep_str_format), format(N_ep, N_ep_str_format)) ) for tr_data in tr_data_lst: # Compute the total number of chunks for each training epoch N_ck_tr = compute_n_chunks(out_folder, tr_data, ep, N_ep_str_format, "train") N_ck_str_format = "0" + str(max(math.ceil(np.log10(N_ck_tr)), 1)) + "d" # ***Epoch training*** for ck in range(N_ck_tr): if not fine_tuning and ck > 1: break # Get training time per chunk import time starting_time = time.time() print_chunk_time = False if wandb_on: wandb.quick_log("chunk", ck + 1, commit = True) # paths of the output files (info,model,chunk_specific cfg file) info_file = ( out_folder + "/exp_files/train_" + tr_data + "_ep" + format(ep, N_ep_str_format) + "_ck" + format(ck, N_ck_str_format) + ".info" ) if ep + ck == 0: model_files_past = {} else: model_files_past = model_files model_files = {} for arch in pt_files.keys(): model_files[arch] = info_file.replace(".info", "_" + arch + ".pkl") config_chunk_file = ( out_folder + "/exp_files/train_" + tr_data + "_ep" + format(ep, N_ep_str_format) + "_ck" + format(ck, N_ck_str_format) + ".cfg" ) # update learning rate in the cfg file (if needed) change_lr_cfg(config_chunk_file, lr, ep) # if this chunk has not already been processed, do training... if not (os.path.exists(info_file)): print_chunk_time = True print("Training %s chunk = %i / %i" % (tr_data, ck + 1, N_ck_tr)) # getting the next chunk next_config_file = cfg_file_list[op_counter] [data_name, data_set, data_end_index, fea_dict, lab_dict, arch_dict] = run_nn( data_name, data_set, data_end_index, fea_dict, lab_dict, arch_dict, config_chunk_file, processed_first, next_config_file, wandb_on = wandb_on, epoch = ep, chunk = ck + 1 ) # update the first_processed variable processed_first = False if not (os.path.exists(info_file)): sys.stderr.write( "ERROR: training epoch %i, chunk %i not done! File %s does not exist.\nSee %s \n" % (ep, ck, info_file, log_file) ) sys.exit(0) # update the operation counter op_counter += 1 # update pt_file (used to initialized the DNN for the next chunk) for pt_arch in pt_files.keys(): pt_files[pt_arch] = ( out_folder + "/exp_files/train_" + tr_data + "_ep" + format(ep, N_ep_str_format) + "_ck" + format(ck, N_ck_str_format) + "_" + pt_arch + ".pkl" ) # remove previous pkl files if len(model_files_past.keys()) > 0: for pt_arch in pt_files.keys(): if os.path.exists(model_files_past[pt_arch]): os.remove(model_files_past[pt_arch]) if do_validation_after_chunk(ck, N_ck_tr, config) and (tr_data == tr_data_lst[-1]) and not(create_gan_dataset): if not _is_first_validation(ep,ck, N_ck_tr, config): valid_peformance_dict_prev = valid_peformance_dict valid_peformance_dict = {} for valid_data in valid_data_lst: N_ck_valid = compute_n_chunks(out_folder, valid_data, ep, N_ep_str_format, "valid") N_ck_str_format_val = "0" + str(max(math.ceil(np.log10(N_ck_valid)), 1)) + "d" for ck_val in range(N_ck_valid): info_file = get_val_info_file_path( out_folder, valid_data, ep, ck, ck_val, N_ep_str_format, N_ck_str_format, N_ck_str_format_val, ) config_chunk_file = get_val_cfg_file_path( out_folder, valid_data, ep, ck, ck_val, N_ep_str_format, N_ck_str_format, N_ck_str_format_val, ) if not (os.path.exists(info_file)): print("Validating %s chunk = %i / %i" % (valid_data, ck_val + 1, N_ck_valid)) next_config_file = cfg_file_list[op_counter] data_name, data_set, data_end_index, fea_dict, lab_dict, arch_dict = run_nn( data_name, data_set, data_end_index, fea_dict, lab_dict, arch_dict, config_chunk_file, processed_first, next_config_file, wandb_on = wandb_on, ) processed_first = False if not (os.path.exists(info_file)): sys.stderr.write( "ERROR: validation on epoch %i, chunk %i, valid chunk %i of dataset %s not done! File %s does not exist.\nSee %s \n" % (ep, ck, ck_val, valid_data, info_file, log_file) ) sys.exit(0) op_counter += 1 valid_info_lst = sorted( glob.glob( get_val_info_file_path( out_folder, valid_data, ep, ck, None, N_ep_str_format, N_ck_str_format, N_ck_str_format_val, ) ) ) valid_loss, valid_error, valid_time = compute_avg_performance(valid_info_lst) valid_peformance_dict[valid_data] = [valid_loss, valid_error, valid_time] val_time_tot += valid_time if not _is_first_validation(ep,ck, N_ck_tr, config): err_valid_mean = np.mean(np.asarray(list(valid_peformance_dict.values()))[:, 1]) err_valid_mean_prev = np.mean(np.asarray(list(valid_peformance_dict_prev.values()))[:, 1]) for lr_arch in lr.keys(): if ep < N_ep - 1 and auto_lr_annealing[lr_arch]: if ((err_valid_mean_prev - err_valid_mean) / err_valid_mean) < improvement_threshold[ lr_arch ]: new_lr_value = float(lr[lr_arch][ep]) * halving_factor[lr_arch] for i in range(ep + 1, N_ep): lr[lr_arch][i] = str(new_lr_value) ending_time = time.time() if print_chunk_time: chunk_time = ending_time - starting_time print("Chunk time:", round(chunk_time), "s\n") if wandb_on: wandb.quick_log("chunk_time", chunk_time, commit=False) # Training Loss and Error tr_info_lst = sorted( glob.glob(out_folder + "/exp_files/train_" + tr_data + "_ep" + format(ep, N_ep_str_format) + "*.info") ) [tr_loss, tr_error, tr_time] = compute_avg_performance(tr_info_lst) tr_loss_tot = tr_loss_tot + tr_loss tr_error_tot = tr_error_tot + tr_error tr_time_tot = tr_time_tot + tr_time tot_time = tr_time + val_time_tot if not create_gan_dataset: if fine_tuning: # Print results in both res_file and stdout dump_epoch_results( res_file_path, ep, tr_data_lst, tr_loss_tot, tr_error_tot, tot_time, valid_data_lst, valid_peformance_dict, lr, N_ep, ) if wandb_on: for lr_arch in lr.keys(): wandb.quick_log("learning_rate", float(lr[lr_arch][ep]), commit = False) for valid_data in valid_data_lst: wandb.quick_log("valid_loss_" + str(valid_data), float(valid_peformance_dict[valid_data][0]), commit = False) wandb.quick_log("valid_error_" + str(valid_data), float(valid_peformance_dict[valid_data][1]), commit = False) # Training has ended, copy the last .pkl to final_arch.pkl for production for pt_arch in pt_files.keys(): if os.path.exists(model_files[pt_arch]) and not os.path.exists(out_folder + "/exp_files/final_" + pt_arch + ".pkl"): copyfile(model_files[pt_arch], out_folder + "/exp_files/final_" + pt_arch + ".pkl") # Terminate application if GAN dataset creation is set try: if config["ganset"]["create_set"] == "True": print("\nGAN dataset created!") exit() except KeyError: pass # --------FORWARD--------# if wandb_on or wandb_decode_only: wandb.quick_log("status", "forwarding", commit = True) for forward_data in forward_data_lst: # Compute the number of chunks N_ck_forward = compute_n_chunks(out_folder, forward_data, ep, N_ep_str_format, "forward") N_ck_str_format = "0" + str(max(math.ceil(np.log10(N_ck_forward)), 1)) + "d" processes = list() info_files = list() for ck in range(N_ck_forward): if not is_production: print("Testing %s chunk = %i / %i" % (forward_data, ck + 1, N_ck_forward)) else: print("Forwarding %s chunk = %i / %i" % (forward_data, ck + 1, N_ck_forward)) # output file info_file = ( out_folder + "/exp_files/forward_" + forward_data + "_ep" + format(ep, N_ep_str_format) + "_ck" + format(ck, N_ck_str_format) + ".info" ) config_chunk_file = ( out_folder + "/exp_files/forward_" + forward_data + "_ep" + format(ep, N_ep_str_format) + "_ck" + format(ck, N_ck_str_format) + ".cfg" ) # Do forward if the chunk was not already processed if not (os.path.exists(info_file)): # Doing forward # getting the next chunk next_config_file = cfg_file_list[op_counter] # run chunk processing if _run_forwarding_in_subprocesses(config): shared_list = list() output_folder = config["exp"]["out_folder"] save_gpumem = strtobool(config["exp"]["save_gpumem"]) use_cuda = strtobool(config["exp"]["use_cuda"]) p = read_next_chunk_into_shared_list_with_subprocess( read_lab_fea, shared_list, config_chunk_file, is_production, output_folder, wait_for_process=True ) data_name, data_end_index_fea, data_end_index_lab, fea_dict, lab_dict, arch_dict, data_set_dict = extract_data_from_shared_list( shared_list ) data_set_inp, data_set_ref = convert_numpy_to_torch(data_set_dict, save_gpumem, use_cuda) data_set = {"input": data_set_inp, "ref": data_set_ref} data_end_index = {"fea": data_end_index_fea, "lab": data_end_index_lab} p = multiprocessing.Process( target=run_nn, kwargs={ "data_name": data_name, "data_set": data_set, "data_end_index": data_end_index, "fea_dict": fea_dict, "lab_dict": lab_dict, "arch_dict": arch_dict, "cfg_file": config_chunk_file, "processed_first": False, "next_config_file": None, }, ) processes.append(p) if _max_nr_of_parallel_forwarding_processes(config) != -1 and len( processes ) > _max_nr_of_parallel_forwarding_processes(config): processes[0].join() del processes[0] p.start() else: [data_name, data_set, data_end_index, fea_dict, lab_dict, arch_dict] = run_nn( data_name, data_set, data_end_index, fea_dict, lab_dict, arch_dict, config_chunk_file, processed_first, next_config_file, wandb_on = wandb_on, ) processed_first = False if not (os.path.exists(info_file)): sys.stderr.write( "ERROR: forward chunk %i of dataset %s not done! File %s does not exist.\nSee %s \n" % (ck, forward_data, info_file, log_file) ) sys.exit(0) info_files.append(info_file) # update the operation counter op_counter += 1 if _run_forwarding_in_subprocesses(config): for process in processes: process.join() for info_file in info_files: if not (os.path.exists(info_file)): sys.stderr.write( "ERROR: File %s does not exist. Forwarding did not suceed.\nSee %s \n" % (info_file, log_file) ) sys.exit(0) # --------DECODING--------# if wandb_on or wandb_decode_only: wandb.quick_log("status", "decoding", commit = True) dec_lst = glob.glob(out_folder + "/exp_files/*_to_decode.ark") forward_data_lst = config["data_use"]["forward_with"].split(",") forward_outs = config["forward"]["forward_out"].split(",") forward_dec_outs = list(map(strtobool, config["forward"]["require_decoding"].split(","))) def get_wer_stats(word_error_rate_string): wer_stats = word_error_rate_string.split(" ") word_error_rate = float(wer_stats[1]) word_tot = wer_stats[5] word_tot = int(word_tot.replace(",", "")) word_ins = int(wer_stats[6]) word_del = int(wer_stats[8]) word_sub = int(wer_stats[10]) return word_error_rate, word_tot, word_ins, word_del, word_sub def get_unique_filename(results_file_name): file_unique_var = False if not os.path.exists(results_file_name): # File does not exist yet return results_file_name # File does exist, determine number to append results_file_name = results_file_name.replace(".txt", "") # no number added file_number = 1 while not file_unique_var: temp_filename = results_file_name + "__" + str(file_number) + ".txt" if not os.path.exists(temp_filename): file_unique_var = True results_file_name = temp_filename else: file_number += 1 return results_file_name def store_wer_stats(run_name, dataset, word_error_rate_string): if not os.path.exists("results"): os.makedirs("results") results_file_name = "results/" + config["exp"]["dataset_name"] + "__" + dataset + "__" + run_name + ".txt" results_file_name = get_unique_filename(results_file_name) results_file = open(results_file_name, "w") results_file.write(word_error_rate_string) results_file.close() if skip_decode: exit(0) for data in forward_data_lst: for k in range(len(forward_outs)): if forward_dec_outs[k]: print("Decoding %s output %s" % (data, forward_outs[k])) info_file = out_folder + "/exp_files/decoding_" + data + "_" + forward_outs[k] + ".info" # create decode config file config_dec_file = out_folder + "/decoding_" + data + "_" + forward_outs[k] + ".conf" config_dec = configparser.ConfigParser() config_dec.add_section("decoding") for dec_key in config["decoding"].keys(): config_dec.set("decoding", dec_key, config["decoding"][dec_key]) # add graph_dir, datadir, alidir lab_field = config[cfg_item2sec(config, "data_name", data)]["lab"] # Production case, we don't have labels if not is_production: pattern = "lab_folder=(.*)\nlab_opts=(.*)\nlab_count_file=(.*)\nlab_data_folder=(.*)\nlab_graph=(.*)" alidir = re.findall(pattern, lab_field)[0][0] config_dec.set("decoding", "alidir", os.path.abspath(alidir)) datadir = re.findall(pattern, lab_field)[0][3] config_dec.set("decoding", "data", os.path.abspath(datadir)) graphdir = re.findall(pattern, lab_field)[0][4] config_dec.set("decoding", "graphdir", os.path.abspath(graphdir)) else: pattern = "lab_data_folder=(.*)\nlab_graph=(.*)" datadir = re.findall(pattern, lab_field)[0][0] config_dec.set("decoding", "data", os.path.abspath(datadir)) graphdir = re.findall(pattern, lab_field)[0][1] config_dec.set("decoding", "graphdir", os.path.abspath(graphdir)) # The ali dir is supposed to be in exp/model/ which is one level ahead of graphdir alidir = graphdir.split("/")[0 : len(graphdir.split("/")) - 1] alidir = "/".join(alidir) config_dec.set("decoding", "alidir", os.path.abspath(alidir)) with open(config_dec_file, "w") as configfile: config_dec.write(configfile) out_folder = os.path.abspath(out_folder) files_dec = out_folder + "/exp_files/forward_" + data + "_ep*_ck*_" + forward_outs[k] + "_to_decode.ark" out_dec_folder = out_folder + "/decode_" + data + "_" + forward_outs[k] if not (os.path.exists(info_file)): # Run the decoder cmd_decode = ( cmd + config["decoding"]["decoding_script_folder"] + "/" + config["decoding"]["decoding_script"] + " " + os.path.abspath(config_dec_file) + " " + out_dec_folder + ' "' + files_dec + '"' ) run_shell(cmd_decode, log_file) # remove ark files if needed if not forward_save_files[k]: list_rem = glob.glob(files_dec) for rem_ark in list_rem: os.remove(rem_ark) # Print WER results and write info file cmd_res = "./check_res_dec.sh " + out_dec_folder wers = run_shell(cmd_res, log_file).decode("utf-8") res_file = open(res_file_path, "a") res_file.write("%s\n" % wers) print(wers) try: if len(wers) > 0: w_error_rate, w_tot, w_ins, w_del, w_sub = get_wer_stats(wers) store_wer_stats(config_file_name, data, wers) if wandb_on or wandb_decode_only: wandb.quick_log("WER_" + data, w_error_rate, commit=True) except IOError: pass if wandb_on or wandb_decode_only: wandb.quick_log("status", "complete", commit = True)
33,246
35.216776
152
py
pytorch-kaldi-gan
pytorch-kaldi-gan-master/quaternion_neural_networks.py
########################################################## # Quaternion Neural Networks # Titouan Parcollet, Xinchi Qiu, Mirco Ravanelli # University of Oxford and Mila, University of Montreal # May 2020 ########################################################## import torch import torch.nn.functional as F import torch.nn as nn from torch.nn.parameter import Parameter from torch.autograd import Variable from torch.nn.utils.rnn import PackedSequence from torch.nn import Module import numpy as np from scipy.stats import chi from numpy.random import RandomState from distutils.util import strtobool import math class QLSTM(nn.Module): """ This class implements a straightforward QLSTM as described in "Quaternion Recurrent Neural Networks", Titouan P., ICLR 2019 Please note that the autograd parameter is usefull if you run out of VRAM. Set it to False, and the model will use a custom QuaternionLinear function that follows a custom backpropagation. The training will be even slower but will consume 4 times less VRAM. """ def __init__(self, options,inp_dim): super(QLSTM, self).__init__() # Reading parameters self.input_dim=inp_dim self.lstm_lay=list(map(int, options['lstm_lay'].split(','))) self.lstm_drop=list(map(float, options['lstm_drop'].split(','))) self.lstm_act=options['lstm_act'].split(',') self.bidir=strtobool(options['lstm_bidir']) self.use_cuda=strtobool(options['use_cuda']) self.autograd=strtobool(options['autograd']) self.to_do=options['to_do'] if self.to_do=='train': self.test_flag=False else: self.test_flag=True # List initialization self.wfx = nn.ModuleList([]) # Forget self.ufh = nn.ModuleList([]) # Forget self.wix = nn.ModuleList([]) # Input self.uih = nn.ModuleList([]) # Input self.wox = nn.ModuleList([]) # Output self.uoh = nn.ModuleList([]) # Output self.wcx = nn.ModuleList([]) # Cell state self.uch = nn.ModuleList([]) # Cell state self.act = nn.ModuleList([]) # Activations self.N_lstm_lay=len(self.lstm_lay) # Initialization of hidden layers current_input=self.input_dim for i in range(self.N_lstm_lay): # Activations self.act.append(act_fun(self.lstm_act[i])) add_bias=True # QuaternionLinearAutograd = Autograd (High VRAM consumption but faster) # QuaternionLinear = Custom Backward (Low VRAM consumption but slower) if(self.autograd): # Feed-forward connections self.wfx.append(QuaternionLinearAutograd(current_input, self.lstm_lay[i],bias=add_bias)) self.wix.append(QuaternionLinearAutograd(current_input, self.lstm_lay[i],bias=add_bias)) self.wox.append(QuaternionLinearAutograd(current_input, self.lstm_lay[i],bias=add_bias)) self.wcx.append(QuaternionLinearAutograd(current_input, self.lstm_lay[i],bias=add_bias)) # Recurrent connections self.ufh.append(QuaternionLinearAutograd(self.lstm_lay[i], self.lstm_lay[i],bias=False)) self.uih.append(QuaternionLinearAutograd(self.lstm_lay[i], self.lstm_lay[i],bias=False)) self.uoh.append(QuaternionLinearAutograd(self.lstm_lay[i], self.lstm_lay[i],bias=False)) self.uch.append(QuaternionLinearAutograd(self.lstm_lay[i], self.lstm_lay[i],bias=False)) else: # Feed-forward connections self.wfx.append(QuaternionLinear(current_input, self.lstm_lay[i],bias=add_bias)) self.wix.append(QuaternionLinear(current_input, self.lstm_lay[i],bias=add_bias)) self.wox.append(QuaternionLinear(current_input, self.lstm_lay[i],bias=add_bias)) self.wcx.append(QuaternionLinear(current_input, self.lstm_lay[i],bias=add_bias)) # Recurrent connections self.ufh.append(QuaternionLinear(self.lstm_lay[i], self.lstm_lay[i],bias=False)) self.uih.append(QuaternionLinear(self.lstm_lay[i], self.lstm_lay[i],bias=False)) self.uoh.append(QuaternionLinear(self.lstm_lay[i], self.lstm_lay[i],bias=False)) self.uch.append(QuaternionLinear(self.lstm_lay[i], self.lstm_lay[i],bias=False)) if self.bidir: current_input=2*self.lstm_lay[i] else: current_input=self.lstm_lay[i] self.out_dim=self.lstm_lay[i]+self.bidir*self.lstm_lay[i] def forward(self, x): for i in range(self.N_lstm_lay): # Initial state and concatenation if self.bidir: h_init = torch.zeros(2*x.shape[1], self.lstm_lay[i]) x=torch.cat([x,flip(x,0)],1) else: h_init = torch.zeros(x.shape[1],self.lstm_lay[i]) # Drop mask initilization (same mask for all time steps) if self.test_flag==False: drop_mask=torch.bernoulli(torch.Tensor(h_init.shape[0],h_init.shape[1]).fill_(1-self.lstm_drop[i])) else: drop_mask=torch.FloatTensor([1-self.lstm_drop[i]]) if self.use_cuda: h_init=h_init.cuda() drop_mask=drop_mask.cuda() # Feed-forward affine transformations (all steps in parallel) wfx_out=self.wfx[i](x) wix_out=self.wix[i](x) wox_out=self.wox[i](x) wcx_out=self.wcx[i](x) # Processing time steps hiddens = [] ct=h_init ht=h_init for k in range(x.shape[0]): # LSTM equations ft=torch.sigmoid(wfx_out[k]+self.ufh[i](ht)) it=torch.sigmoid(wix_out[k]+self.uih[i](ht)) ot=torch.sigmoid(wox_out[k]+self.uoh[i](ht)) ct=it*self.act[i](wcx_out[k]+self.uch[i](ht))*drop_mask+ft*ct ht=ot*self.act[i](ct) hiddens.append(ht) # Stacking hidden states h=torch.stack(hiddens) # Bidirectional concatenations if self.bidir: h_f=h[:,0:int(x.shape[1]/2)] h_b=flip(h[:,int(x.shape[1]/2):x.shape[1]].contiguous(),0) h=torch.cat([h_f,h_b],2) # Setup x for the next hidden layer x=h return x # # From this point, the defined functions are PyTorch modules extending # linear layers to the quaternion domain. # class QuaternionLinearAutograd(Module): r"""Applies a quaternion linear transformation to the incoming data. The backward process follows the Autograd scheme. """ def __init__(self, in_features, out_features, bias=True, init_criterion='glorot', weight_init='quaternion', seed=None): super(QuaternionLinearAutograd, self).__init__() self.in_features = in_features//4 self.out_features = out_features//4 self.r_weight = Parameter(torch.Tensor(self.in_features, self.out_features)) self.i_weight = Parameter(torch.Tensor(self.in_features, self.out_features)) self.j_weight = Parameter(torch.Tensor(self.in_features, self.out_features)) self.k_weight = Parameter(torch.Tensor(self.in_features, self.out_features)) if bias: self.bias = Parameter(torch.Tensor(self.out_features*4)) else: self.bias = torch.zeros(self.out_features*4) self.init_criterion = init_criterion self.weight_init = weight_init self.seed = seed if seed is not None else np.random.randint(0,1234) self.rng = RandomState(self.seed) self.reset_parameters() def reset_parameters(self): winit = {'quaternion': quaternion_init, 'unitary': unitary_init, 'random': random_init}[self.weight_init] if self.bias is not None: self.bias.data.fill_(0) affect_init(self.r_weight, self.i_weight, self.j_weight, self.k_weight, winit, self.rng, self.init_criterion) def forward(self, input): return quaternion_linear(input, self.r_weight, self.i_weight, self.j_weight, self.k_weight, self.bias) def __repr__(self): return self.__class__.__name__ + '(' \ + 'in_features=' + str(self.in_features) \ + ', out_features=' + str(self.out_features) \ + ', bias=' + str(self.bias is not None) \ + ', init_criterion=' + str(self.init_criterion) \ + ', weight_init=' + str(self.weight_init) \ + ', seed=' + str(self.seed) + ')' class QuaternionLinear(Module): r"""A custom Autograd function is call to drastically reduce the VRAM consumption. Nonetheless, computing time is increased compared to QuaternionLinearAutograd(). """ def __init__(self, in_features, out_features, bias=True, init_criterion='glorot', weight_init='quaternion', seed=None): super(QuaternionLinear, self).__init__() self.in_features = in_features//4 self.out_features = out_features//4 self.r_weight = Parameter(torch.Tensor(self.in_features, self.out_features)) self.i_weight = Parameter(torch.Tensor(self.in_features, self.out_features)) self.j_weight = Parameter(torch.Tensor(self.in_features, self.out_features)) self.k_weight = Parameter(torch.Tensor(self.in_features, self.out_features)) if bias: self.bias = Parameter(torch.Tensor(self.out_features*4)) else: self.register_parameter('bias', None) self.init_criterion = init_criterion self.weight_init = weight_init self.seed = seed if seed is not None else np.random.randint(0,1234) self.rng = RandomState(self.seed) self.reset_parameters() def reset_parameters(self): winit = {'quaternion': quaternion_init, 'unitary': unitary_init}[self.weight_init] if self.bias is not None: self.bias.data.fill_(0) affect_init(self.r_weight, self.i_weight, self.j_weight, self.k_weight, winit, self.rng, self.init_criterion) def forward(self, input): # See the autograd section for explanation of what happens here. if input.dim() == 3: T, N, C = input.size() input = input.view(T * N, C) output = QuaternionLinearFunction.apply(input, self.r_weight, self.i_weight, self.j_weight, self.k_weight, self.bias) output = output.view(T, N, output.size(1)) elif input.dim() == 2: output = QuaternionLinearFunction.apply(input, self.r_weight, self.i_weight, self.j_weight, self.k_weight, self.bias) else: raise NotImplementedError return output def __repr__(self): return self.__class__.__name__ + '(' \ + 'in_features=' + str(self.in_features) \ + ', out_features=' + str(self.out_features) \ + ', bias=' + str(self.bias is not None) \ + ', init_criterion=' + str(self.init_criterion) \ + ', weight_init=' + str(self.weight_init) \ + ', seed=' + str(self.seed) + ')' # # Thereafter are utility functions needed by the above classes # def flip(x, dim): xsize = x.size() dim = x.dim() + dim if dim < 0 else dim x = x.contiguous() x = x.view(-1, *xsize[dim:]) x = x.view(x.size(0), x.size(1), -1)[:, getattr(torch.arange(x.size(1)-1, -1, -1), ('cpu','cuda')[x.is_cuda])().long(), :] return x.view(xsize) def act_fun(act_type): if act_type=="relu": return nn.ReLU() if act_type=="prelu": return nn.PReLU() if act_type=="tanh": return nn.Tanh() if act_type=="sigmoid": return nn.Sigmoid() if act_type=="hardtanh": return nn.Hardtanh() if act_type=="leaky_relu": return nn.LeakyReLU(0.2) if act_type=="elu": return nn.ELU() if act_type=="softmax": return nn.LogSoftmax(dim=1) if act_type=="linear": return nn.LeakyReLU(1) # initializzed like this, but not used in forward! def check_input(input): if input.dim() not in {2, 3}: raise RuntimeError( "quaternion linear accepts only input of dimension 2 or 3." " input.dim = " + str(input.dim()) ) nb_hidden = input.size()[-1] if nb_hidden % 4 != 0: raise RuntimeError( "Quaternion Tensors must be divisible by 4." " input.size()[1] = " + str(nb_hidden) ) # # Quaternion getters! # def get_r(input): check_input(input) nb_hidden = input.size()[-1] if input.dim() == 2: return input.narrow(1, 0, nb_hidden // 4) elif input.dim() == 3: return input.narrow(2, 0, nb_hidden // 4) def get_i(input): check_input(input) nb_hidden = input.size()[-1] if input.dim() == 2: return input.narrow(1, nb_hidden // 4, nb_hidden // 4) if input.dim() == 3: return input.narrow(2, nb_hidden // 4, nb_hidden // 4) def get_j(input): check_input(input) nb_hidden = input.size()[-1] if input.dim() == 2: return input.narrow(1, nb_hidden // 2, nb_hidden // 4) if input.dim() == 3: return input.narrow(2, nb_hidden // 2, nb_hidden // 4) def get_k(input): check_input(input) nb_hidden = input.size()[-1] if input.dim() == 2: return input.narrow(1, nb_hidden - nb_hidden // 4, nb_hidden // 4) if input.dim() == 3: return input.narrow(2, nb_hidden - nb_hidden // 4, nb_hidden // 4) def quaternion_linear(input, r_weight, i_weight, j_weight, k_weight, bias): """ Applies a quaternion linear transformation to the incoming data: It is important to notice that the forward phase of a QNN is defined as W * Inputs (with * equal to the Hamilton product). The constructed cat_kernels_4_quaternion is a modified version of the quaternion representation so when we do torch.mm(Input,W) it's equivalent to W * Inputs. """ cat_kernels_4_r = torch.cat([r_weight, -i_weight, -j_weight, -k_weight], dim=0) cat_kernels_4_i = torch.cat([i_weight, r_weight, -k_weight, j_weight], dim=0) cat_kernels_4_j = torch.cat([j_weight, k_weight, r_weight, -i_weight], dim=0) cat_kernels_4_k = torch.cat([k_weight, -j_weight, i_weight, r_weight], dim=0) cat_kernels_4_quaternion = torch.cat([cat_kernels_4_r, cat_kernels_4_i, cat_kernels_4_j, cat_kernels_4_k], dim=1) if input.dim() == 2 : if bias is not None: return torch.addmm(bias, input, cat_kernels_4_quaternion) else: return torch.mm(input, cat_kernels_4_quaternion) else: output = torch.matmul(input, cat_kernels_4_quaternion) if bias is not None: return output+bias else: return output # Custom AUTOGRAD for lower VRAM consumption class QuaternionLinearFunction(torch.autograd.Function): @staticmethod def forward(ctx, input, r_weight, i_weight, j_weight, k_weight, bias=None): ctx.save_for_backward(input, r_weight, i_weight, j_weight, k_weight, bias) check_input(input) cat_kernels_4_r = torch.cat([r_weight, -i_weight, -j_weight, -k_weight], dim=0) cat_kernels_4_i = torch.cat([i_weight, r_weight, -k_weight, j_weight], dim=0) cat_kernels_4_j = torch.cat([j_weight, k_weight, r_weight, -i_weight], dim=0) cat_kernels_4_k = torch.cat([k_weight, -j_weight, i_weight, r_weight], dim=0) cat_kernels_4_quaternion = torch.cat([cat_kernels_4_r, cat_kernels_4_i, cat_kernels_4_j, cat_kernels_4_k], dim=1) if input.dim() == 2 : if bias is not None: return torch.addmm(bias, input, cat_kernels_4_quaternion) else: return torch.mm(input, cat_kernels_4_quaternion) else: output = torch.matmul(input, cat_kernels_4_quaternion) if bias is not None: return output+bias else: return output # This function has only a single output, so it gets only one gradient @staticmethod def backward(ctx, grad_output): input, r_weight, i_weight, j_weight, k_weight, bias = ctx.saved_tensors grad_input = grad_weight_r = grad_weight_i = grad_weight_j = grad_weight_k = grad_bias = None input_r = torch.cat([r_weight, -i_weight, -j_weight, -k_weight], dim=0) input_i = torch.cat([i_weight, r_weight, -k_weight, j_weight], dim=0) input_j = torch.cat([j_weight, k_weight, r_weight, -i_weight], dim=0) input_k = torch.cat([k_weight, -j_weight, i_weight, r_weight], dim=0) cat_kernels_4_quaternion_T = Variable(torch.cat([input_r, input_i, input_j, input_k], dim=1).permute(1,0), requires_grad=False) r = get_r(input) i = get_i(input) j = get_j(input) k = get_k(input) input_r = torch.cat([r, -i, -j, -k], dim=0) input_i = torch.cat([i, r, -k, j], dim=0) input_j = torch.cat([j, k, r, -i], dim=0) input_k = torch.cat([k, -j, i, r], dim=0) input_mat = Variable(torch.cat([input_r, input_i, input_j, input_k], dim=1), requires_grad=False) r = get_r(grad_output) i = get_i(grad_output) j = get_j(grad_output) k = get_k(grad_output) input_r = torch.cat([r, i, j, k], dim=1) input_i = torch.cat([-i, r, k, -j], dim=1) input_j = torch.cat([-j, -k, r, i], dim=1) input_k = torch.cat([-k, j, -i, r], dim=1) grad_mat = torch.cat([input_r, input_i, input_j, input_k], dim=0) if ctx.needs_input_grad[0]: grad_input = grad_output.mm(cat_kernels_4_quaternion_T) if ctx.needs_input_grad[1]: grad_weight = grad_mat.permute(1,0).mm(input_mat).permute(1,0) unit_size_x = r_weight.size(0) unit_size_y = r_weight.size(1) grad_weight_r = grad_weight.narrow(0,0,unit_size_x).narrow(1,0,unit_size_y) grad_weight_i = grad_weight.narrow(0,0,unit_size_x).narrow(1,unit_size_y,unit_size_y) grad_weight_j = grad_weight.narrow(0,0,unit_size_x).narrow(1,unit_size_y*2,unit_size_y) grad_weight_k = grad_weight.narrow(0,0,unit_size_x).narrow(1,unit_size_y*3,unit_size_y) if ctx.needs_input_grad[5]: grad_bias = grad_output.sum(0).squeeze(0) return grad_input, grad_weight_r, grad_weight_i, grad_weight_j, grad_weight_k, grad_bias # # PARAMETERS INITIALIZATION # def unitary_init(in_features, out_features, rng, kernel_size=None, criterion='he'): if kernel_size is not None: receptive_field = np.prod(kernel_size) fan_in = in_features * receptive_field fan_out = out_features * receptive_field else: fan_in = in_features fan_out = out_features if criterion == 'glorot': s = 1. / np.sqrt(2*(fan_in + fan_out)) elif criterion == 'he': s = 1. / np.sqrt(2*fan_in) else: raise ValueError('Invalid criterion: ' + criterion) if kernel_size is None: kernel_shape = (in_features, out_features) else: if type(kernel_size) is int: kernel_shape = (out_features, in_features) + tuple((kernel_size,)) else: kernel_shape = (out_features, in_features) + (*kernel_size,) s = np.sqrt(3.0) * s number_of_weights = np.prod(kernel_shape) v_r = np.random.uniform(-s,s,number_of_weights) v_i = np.random.uniform(-s,s,number_of_weights) v_j = np.random.uniform(-s,s,number_of_weights) v_k = np.random.uniform(-s,s,number_of_weights) # Unitary quaternion for i in range(0, number_of_weights): norm = np.sqrt(v_r[i]**2 + v_i[i]**2 + v_j[i]**2 + v_k[i]**2)+0.0001 v_r[i]/= norm v_i[i]/= norm v_j[i]/= norm v_k[i]/= norm v_r = v_r.reshape(kernel_shape) v_i = v_i.reshape(kernel_shape) v_j = v_j.reshape(kernel_shape) v_k = v_k.reshape(kernel_shape) return (v_r, v_i, v_j, v_k) def random_init(in_features, out_features, rng, kernel_size=None, criterion='glorot'): if kernel_size is not None: receptive_field = np.prod(kernel_size) fan_in = in_features * receptive_field fan_out = out_features * receptive_field else: fan_in = in_features fan_out = out_features if criterion == 'glorot': s = 1. / np.sqrt(2*(fan_in + fan_out)) elif criterion == 'he': s = 1. / np.sqrt(2*fan_in) else: raise ValueError('Invalid criterion: ' + criterion) if kernel_size is None: kernel_shape = (in_features, out_features) else: if type(kernel_size) is int: kernel_shape = (out_features, in_features) + tuple((kernel_size,)) else: kernel_shape = (out_features, in_features) + (*kernel_size,) number_of_weights = np.prod(kernel_shape) v_r = np.random.uniform(0.0,1.0,number_of_weights) v_i = np.random.uniform(0.0,1.0,number_of_weights) v_j = np.random.uniform(0.0,1.0,number_of_weights) v_k = np.random.uniform(0.0,1.0,number_of_weights) v_r = v_r.reshape(kernel_shape) v_i = v_i.reshape(kernel_shape) v_j = v_j.reshape(kernel_shape) v_k = v_k.reshape(kernel_shape) weight_r = v_r * s weight_i = v_i * s weight_j = v_j * s weight_k = v_k * s return (weight_r, weight_i, weight_j, weight_k) def quaternion_init(in_features, out_features, rng, kernel_size=None, criterion='glorot'): if kernel_size is not None: receptive_field = np.prod(kernel_size) fan_in = in_features * receptive_field fan_out = out_features * receptive_field else: fan_in = in_features fan_out = out_features if criterion == 'glorot': s = 1. / np.sqrt(2*(fan_in + fan_out)) elif criterion == 'he': s = 1. / np.sqrt(2*fan_in) else: raise ValueError('Invalid criterion: ' + criterion) rng = RandomState(np.random.randint(1,1234)) # Generating randoms and purely imaginary quaternions : if kernel_size is None: kernel_shape = (in_features, out_features) else: if type(kernel_size) is int: kernel_shape = (out_features, in_features) + tuple((kernel_size,)) else: kernel_shape = (out_features, in_features) + (*kernel_size,) modulus = chi.rvs(4,loc=0,scale=s,size=kernel_shape) number_of_weights = np.prod(kernel_shape) v_i = np.random.normal(0,1.0,number_of_weights) v_j = np.random.normal(0,1.0,number_of_weights) v_k = np.random.normal(0,1.0,number_of_weights) # Purely imaginary quaternions unitary for i in range(0, number_of_weights): norm = np.sqrt(v_i[i]**2 + v_j[i]**2 + v_k[i]**2 +0.0001) v_i[i]/= norm v_j[i]/= norm v_k[i]/= norm v_i = v_i.reshape(kernel_shape) v_j = v_j.reshape(kernel_shape) v_k = v_k.reshape(kernel_shape) phase = rng.uniform(low=-np.pi, high=np.pi, size=kernel_shape) weight_r = modulus * np.cos(phase) weight_i = modulus * v_i*np.sin(phase) weight_j = modulus * v_j*np.sin(phase) weight_k = modulus * v_k*np.sin(phase) return (weight_r, weight_i, weight_j, weight_k) def affect_init(r_weight, i_weight, j_weight, k_weight, init_func, rng, init_criterion): if r_weight.size() != i_weight.size() or r_weight.size() != j_weight.size() or \ r_weight.size() != k_weight.size() : raise ValueError('The real and imaginary weights ' 'should have the same size . Found: r:' + str(r_weight.size()) +' i:' + str(i_weight.size()) +' j:' + str(j_weight.size()) +' k:' + str(k_weight.size())) elif r_weight.dim() != 2: raise Exception('affect_init accepts only matrices. Found dimension = ' + str(r_weight.dim())) kernel_size = None r, i, j, k = init_func(r_weight.size(0), r_weight.size(1), rng, kernel_size, init_criterion) r, i, j, k = torch.from_numpy(r), torch.from_numpy(i), torch.from_numpy(j), torch.from_numpy(k) r_weight.data = r.type_as(r_weight.data) i_weight.data = i.type_as(i_weight.data) j_weight.data = j.type_as(j_weight.data) k_weight.data = k.type_as(k_weight.data)
24,754
37.20216
135
py
pytorch-kaldi-gan
pytorch-kaldi-gan-master/resample_files.py
import torch import torchaudio import numpy as np import matplotlib.pyplot as plt import configparser import os import sys import random import shutil # Reading global cfg file (first argument-mandatory file) cfg_file = sys.argv[1] if not (os.path.exists(cfg_file)): sys.stderr.write("ERROR: The config file %s does not exist!\n" % (cfg_file)) sys.exit(0) else: config = configparser.ConfigParser() config.read(cfg_file) # Output folder creation out_folder = config["resample"]["out_folder"] if not os.path.exists(out_folder): os.makedirs(out_folder) data_folder = config["resample"]["data_folder"] print("- Reading config file......OK!") # Preparing speakers def normalize_tensor(tensor): ''' Normalize tensor between -1 and 1 ''' max_val = torch.abs(torch.max(tensor)) min_val = torch.abs(torch.min(tensor)) return torch.mul(torch.sub(torch.div(torch.add(tensor, min_val), torch.add(max_val, min_val)), 0.5), 2) if config["resample"]["dataset"] == "qutnoise": audio_files = os.listdir(data_folder) # Create parallel dataset print("\n- Starting resampling.\n") sample_rate = int(config["resample"]["sample_rate"]) for sound in audio_files: sound_dir = os.path.join(data_folder, sound) recording, o_sample_rate = torchaudio.load(sound_dir) recording = normalize_tensor(recording) save_dir = os.path.join(out_folder, sound) torchaudio.save(save_dir, recording, sample_rate = sample_rate) print("Saved:", sound)
1,528
26.303571
107
py
pytorch-kaldi-gan
pytorch-kaldi-gan-master/core.py
########################################################## # pytorch-kaldi-gan # Walter Heymans # North West University # 2020 # Adapted from: # pytorch-kaldi v.0.1 # Mirco Ravanelli, Titouan Parcollet # Mila, University of Montreal # October 2018 ########################################################## import sys import configparser import os from utils import is_sequential_dict, model_init, optimizer_init, forward_model, progress from data_io import load_counts import numpy as np import random import torch from distutils.util import strtobool import time import threading import itertools import torch.nn.functional as functional from data_io import read_lab_fea, open_or_fd, write_mat from utils import shift import gan_networks import weights_and_biases as wandb def save_tensor_list_to_png(array, titles=[], fig_name="tensor.png"): import matplotlib.pyplot as plt plt.figure() for i in range(1, len(array) + 1): plt.subplot(len(array), 1, i) if len(array) == 4 and i <= 2: graph_colour = "b" elif len(array) == 4: graph_colour = "r" elif i == 2: graph_colour = "r" else: graph_colour = "b" plt.plot(array[i - 1].detach().numpy(), graph_colour) if len(titles) == len(array): plt.title(titles[i - 1]) plt.tight_layout(True) plt.savefig(fig_name) plt.close() def compute_gradient_penalty(D, real_samples, fake_samples): Tensor = torch.cuda.FloatTensor from torch.autograd import Variable """Calculates the gradient penalty loss for WGAN GP""" # Random weight term for interpolation between real and fake samples alpha = Tensor(np.random.random((real_samples.size(0), 440))) # Get random interpolation between real and fake samples interpolates = (alpha * real_samples + ((1 - alpha) * fake_samples)).requires_grad_(True) d_interpolates = D(interpolates) fake = Variable(Tensor(real_samples.shape[0], 1).fill_(1.0), requires_grad=False) # Get gradient w.r.t. interpolates gradients = torch.autograd.grad( outputs=d_interpolates, inputs=interpolates, grad_outputs=fake, create_graph=True, retain_graph=True, only_inputs=True, )[0] gradients = gradients.view(gradients.size(0), -1) gradient_penalty = ((gradients.norm(2, dim=1) - 1) ** 2).mean() return gradient_penalty def get_pearson_correlation(tensor1, tensor2): from scipy.stats import pearsonr output1 = tensor1.detach().cpu().numpy() output2 = tensor2.detach().cpu().numpy() if output1.shape == output2.shape: # calculate Pearson's correlation if len(output1.shape) > 1: correlation = 0 for i in range(output1.shape[0]): try: temp_corr, _ = pearsonr(output1[i], output2[i]) except: temp_corr = 0 correlation += temp_corr if output1.shape[0] > 0: correlation = correlation / output1.shape[0] else: correlation, _ = pearsonr(output1, output2) return correlation else: return 0 def get_mean_squared_error(tensor1, tensor2): output1 = tensor1.detach().cpu() output2 = tensor2.detach().cpu() if output1.shape == output2.shape: if len(output1.shape) > 1: error = 0 for i in range(output1.shape[0]): error += torch.mean(torch.abs(torch.abs(output1) - torch.abs(output2))) if output1.shape[0] > 0: error = error / output1.shape[0] else: error = torch.mean(torch.abs(torch.abs(output1) - torch.abs(output2))) return error.numpy() else: return 0 def read_next_chunk_into_shared_list_with_subprocess( read_lab_fea, shared_list, cfg_file, is_production, output_folder, wait_for_process ): p = threading.Thread(target=read_lab_fea, args=(cfg_file, is_production, shared_list, output_folder)) p.start() if wait_for_process: p.join() return None else: return p def extract_data_from_shared_list(shared_list): data_name = shared_list[0] data_end_index_fea = shared_list[1] data_end_index_lab = shared_list[2] fea_dict = shared_list[3] lab_dict = shared_list[4] arch_dict = shared_list[5] data_set = shared_list[6] return data_name, data_end_index_fea, data_end_index_lab, fea_dict, lab_dict, arch_dict, data_set def convert_numpy_to_torch(data_set_dict, save_gpumem, use_cuda): if not (save_gpumem) and use_cuda: data_set_inp = torch.from_numpy(data_set_dict["input"]).float().cuda() data_set_ref = torch.from_numpy(data_set_dict["ref"]).float().cuda() else: data_set_inp = torch.from_numpy(data_set_dict["input"]).float() data_set_ref = torch.from_numpy(data_set_dict["ref"]).float() data_set_ref = data_set_ref.view((data_set_ref.shape[0], 1)) return data_set_inp, data_set_ref def get_labels(batch_size, label): return torch.ones((batch_size, 1)) * label def wgan_loss_d(dx, dz): return -torch.mean(dx) + torch.mean(dz) def run_nn( data_name, data_set, data_end_index, fea_dict, lab_dict, arch_dict, cfg_file, processed_first, next_config_file, epoch=1, wandb_on=False, chunk=0 ): # This function processes the current chunk using the information in cfg_file. In parallel, the next chunk is load into the CPU memory # Reading chunk-specific cfg file (first argument-mandatory file) if not (os.path.exists(cfg_file)): sys.stderr.write("ERROR: The config file %s does not exist!\n" % (cfg_file)) sys.exit(0) else: config = configparser.ConfigParser() config.read(cfg_file) # Setting torch seed seed = int(config["exp"]["seed"]) torch.manual_seed(seed) random.seed(seed) np.random.seed(seed) # Reading config parameters output_folder = config["exp"]["out_folder"] use_cuda = strtobool(config["exp"]["use_cuda"]) multi_gpu = strtobool(config["exp"]["multi_gpu"]) try: torch.cuda.set_device(int(config["exp"]["cuda_device"])) except KeyError: torch.cuda.set_device(0) to_do = config["exp"]["to_do"] info_file = config["exp"]["out_info"] model = config["model"]["model"].split("\n") forward_outs = config["forward"]["forward_out"].split(",") forward_normalize_post = list(map(strtobool, config["forward"]["normalize_posteriors"].split(","))) forward_count_files = config["forward"]["normalize_with_counts_from"].split(",") require_decodings = list(map(strtobool, config["forward"]["require_decoding"].split(","))) use_cuda = strtobool(config["exp"]["use_cuda"]) save_gpumem = strtobool(config["exp"]["save_gpumem"]) is_production = strtobool(config["exp"]["production"]) if to_do == "train": batch_size = int(config["batches"]["batch_size_train"]) try: gan_batch_size = int(config["gan"]["batch_size"]) except KeyError: pass if to_do == "valid": batch_size = int(config["batches"]["batch_size_valid"]) if to_do == "forward": batch_size = 1 if config["gan"]["arch_gan"] == "True" and to_do == "train": gan_on = True else: gan_on = False # ***** Reading the Data ******** if processed_first: # Reading all the features and labels for this chunk shared_list = [] p = threading.Thread(target=read_lab_fea, args=(cfg_file, is_production, shared_list, output_folder)) p.start() p.join() data_name = shared_list[0] data_end_index = shared_list[1] fea_dict = shared_list[2] lab_dict = shared_list[3] arch_dict = shared_list[4] data_set = shared_list[5] # converting numpy tensors into pytorch tensors and put them on GPUs if specified if not (save_gpumem) and use_cuda: data_set = torch.from_numpy(data_set).float().cuda() else: data_set = torch.from_numpy(data_set).float() try: if config["ganset"]["create_set"] == "True": gan_out_folder = config["ganset"]["out_folder"] smallset = data_set[:,:40].clone() smallset = torch.cat((smallset, torch.unsqueeze(data_set[:,-1], dim = 1)), dim = 1) torch.save(smallset, os.path.join(gan_out_folder, "chunk_" + str(chunk) + ".pt")) except KeyError: pass else: try: if config["ganset"]["create_set"] == "True": gan_out_folder = config["ganset"]["out_folder"] smallset = data_set[:,:40].clone() smallset = torch.cat((smallset, torch.unsqueeze(data_set[:,-1], dim = 1)), dim = 1) torch.save(smallset, os.path.join(gan_out_folder, "chunk_" + str(chunk) + ".pt")) except KeyError: pass # Reading all the features and labels for the next chunk shared_list = [] p = threading.Thread(target=read_lab_fea, args=(next_config_file, is_production, shared_list, output_folder)) p.start() # Reading model and initialize networks inp_out_dict = fea_dict [nns, costs] = model_init(inp_out_dict, model, config, arch_dict, use_cuda, multi_gpu, to_do) if config["gan"]["arch_gan"] == "True": # Create Generator generator_class = getattr(gan_networks, config["generator"]["arch_name"]) generator = generator_class(nns[str(config["architecture1"]["arch_name"])].get_input_dim(), nns[str(config["architecture1"]["arch_name"])].get_output_dim(), config["generator"]) if use_cuda: generator = generator.cuda() directory_g = os.path.join(config["exp"]["out_folder"], config["gan"]["output_path_g"]) if os.path.exists(directory_g): try: if int(config["exp"]["cuda_device"]) == 0: generator.load_state_dict(torch.load(directory_g, map_location="cuda:0")) elif int(config["exp"]["cuda_device"]) == 1: generator.load_state_dict(torch.load(directory_g, map_location="cuda:1")) except RuntimeError: print("Load error loading G, network will be recreated.") # optimizers initialization optimizers = optimizer_init(nns, config, arch_dict) # pre-training and multi-gpu init for net in nns.keys(): pt_file_arch = config[arch_dict[net][0]]["arch_pretrain_file"] if pt_file_arch != "none": if use_cuda: try: if int(config["exp"]["cuda_device"]) == 0: checkpoint_load = torch.load(pt_file_arch, map_location="cuda:0") elif int(config["exp"]["cuda_device"]) == 1: checkpoint_load = torch.load(pt_file_arch, map_location="cuda:1") except FileNotFoundError: # File does not exist, load most recent model exp_file_names = os.path.dirname(pt_file_arch) if os.path.exists(exp_file_names): exp_file_list = os.listdir(exp_file_names) new_pt_file_arch = '' for exp_file in exp_file_list: if exp_file.__contains__('final') and exp_file.__contains__('.pkl'): new_pt_file_arch = os.path.join(exp_file_names, exp_file) break elif exp_file.__contains__('.pkl'): new_pt_file_arch = os.path.join(exp_file_names, exp_file) if int(config["exp"]["cuda_device"]) == 0: checkpoint_load = torch.load(new_pt_file_arch, map_location="cuda:0") elif int(config["exp"]["cuda_device"]) == 1: checkpoint_load = torch.load(new_pt_file_arch, map_location="cuda:1") except EOFError: if int(config["exp"]["cuda_device"]) == 0: checkpoint_load = torch.load(os.path.join(output_folder, "exp_files/backup.pkl"), map_location="cuda:0") elif int(config["exp"]["cuda_device"]) == 1: checkpoint_load = torch.load(os.path.join(output_folder, "exp_files/backup.pkl"), map_location="cuda:1") else: checkpoint_load = torch.load(pt_file_arch, map_location="cpu") nns[net].load_state_dict(checkpoint_load["model_par"]) optimizers[net].load_state_dict(checkpoint_load["optimizer_par"]) optimizers[net].param_groups[0]["lr"] = float( config[arch_dict[net][0]]["arch_lr"] ) # loading lr of the cfg file for pt if multi_gpu: nns[net] = torch.nn.DataParallel(nns[net]) if to_do == "forward": post_file = {} for out_id in range(len(forward_outs)): if require_decodings[out_id]: out_file = info_file.replace(".info", "_" + forward_outs[out_id] + "_to_decode.ark") else: out_file = info_file.replace(".info", "_" + forward_outs[out_id] + ".ark") post_file[forward_outs[out_id]] = open_or_fd(out_file, output_folder, "wb") # Save the model if to_do == "train": for net in nns.keys(): checkpoint = {} if multi_gpu: checkpoint["model_par"] = nns[net].module.state_dict() else: checkpoint["model_par"] = nns[net].state_dict() checkpoint["optimizer_par"] = optimizers[net].state_dict() torch.save(checkpoint, os.path.join(output_folder, "exp_files/backup.pkl")) # check automatically if the model is sequential seq_model = is_sequential_dict(config, arch_dict) # ***** Minibatch Processing loop******** if seq_model or to_do == "forward": N_snt = len(data_name) N_batches = int(N_snt / batch_size) else: N_ex_tr = data_set.shape[0] N_batches = int(N_ex_tr / batch_size) beg_batch = 0 end_batch = batch_size snt_index = 0 beg_snt = 0 start_time = time.time() # array of sentence lengths arr_snt_len = shift(shift(data_end_index, -1, 0) - data_end_index, 1, 0) arr_snt_len[0] = data_end_index[0] loss_sum = 0 err_sum = 0 inp_dim = data_set.shape[1] double_features = False try: if config["gan"]["double_features"] == "True": double_features = True except KeyError: pass for i in range(N_batches): max_len = 0 if seq_model: max_len = int(max(arr_snt_len[snt_index : snt_index + batch_size])) inp = torch.zeros(max_len, batch_size, inp_dim).contiguous() for k in range(batch_size): snt_len = data_end_index[snt_index] - beg_snt N_zeros = max_len - snt_len # Appending a random number of initial zeros, tge others are at the end. N_zeros_left = random.randint(0, N_zeros) # randomizing could have a regularization effect inp[N_zeros_left : N_zeros_left + snt_len, k, :] = data_set[beg_snt : beg_snt + snt_len, :] beg_snt = data_end_index[snt_index] snt_index = snt_index + 1 else: # features and labels for batch i if to_do != "forward": inp = data_set[beg_batch:end_batch, :].contiguous() else: snt_len = data_end_index[snt_index] - beg_snt inp = data_set[beg_snt : beg_snt + snt_len, :].contiguous() beg_snt = data_end_index[snt_index] snt_index = snt_index + 1 # use cuda if use_cuda: inp = inp.cuda() if to_do == "train": # Forward input, with autograd graph active if gan_on: outs_dict = forward_model( fea_dict, lab_dict, arch_dict, model, nns, costs, inp, inp_out_dict, max_len, batch_size, to_do, forward_outs, generator=generator, gan_on=True, double_features=double_features, ) else: outs_dict = forward_model( fea_dict, lab_dict, arch_dict, model, nns, costs, inp, inp_out_dict, max_len, batch_size, to_do, forward_outs, double_features = double_features, ) for opt in optimizers.keys(): optimizers[opt].zero_grad() outs_dict["loss_final"].backward() for opt in optimizers.keys(): if not (strtobool(config[arch_dict[opt][0]]["arch_freeze"])): optimizers[opt].step() else: with torch.no_grad(): # Forward input without autograd graph (save memory) if config["gan"]["arch_gan"] == "True": # Validation and forward outs_dict = forward_model( fea_dict, lab_dict, arch_dict, model, nns, costs, inp, inp_out_dict, max_len, batch_size, to_do, forward_outs, generator=generator, gan_on=True, double_features=double_features, ) else: outs_dict = forward_model( fea_dict, lab_dict, arch_dict, model, nns, costs, inp, inp_out_dict, max_len, batch_size, to_do, forward_outs, double_features = double_features, ) if to_do == "forward": for out_id in range(len(forward_outs)): out_save = outs_dict[forward_outs[out_id]].data.cpu().numpy() if forward_normalize_post[out_id]: # read the config file counts = load_counts(forward_count_files[out_id]) out_save = out_save - np.log(counts / np.sum(counts)) # save the output write_mat(output_folder, post_file[forward_outs[out_id]], out_save, data_name[i]) else: loss_sum = loss_sum + outs_dict["loss_final"].detach() err_sum = err_sum + outs_dict["err_final"].detach() # update it to the next batch beg_batch = end_batch end_batch = beg_batch + batch_size # Progress bar if to_do == "train": status_string = ( "Training | (Batch " + str(i + 1) + "/" + str(N_batches) + ")" + " | L:" + str(round(loss_sum.cpu().item() / (i + 1), 3)) ) if i == N_batches - 1: status_string = "Training | (Batch " + str(i + 1) + "/" + str(N_batches) + ")" if to_do == "valid": status_string = "Validating | (Batch " + str(i + 1) + "/" + str(N_batches) + ")" if to_do == "forward": status_string = "Forwarding | (Batch " + str(i + 1) + "/" + str(N_batches) + ")" progress(i, N_batches, status=status_string) elapsed_time_chunk = time.time() - start_time loss_tot = loss_sum / N_batches err_tot = err_sum / N_batches if wandb_on and to_do == "train" : wandb.quick_log("train_loss", loss_tot.cpu().numpy(), commit = False) wandb.quick_log("train_error", err_tot.cpu().numpy(), commit = False) # clearing memory del inp, outs_dict, data_set # save the model if to_do == "train": for net in nns.keys(): checkpoint = {} if multi_gpu: checkpoint["model_par"] = nns[net].module.state_dict() else: checkpoint["model_par"] = nns[net].state_dict() checkpoint["optimizer_par"] = optimizers[net].state_dict() out_file = info_file.replace(".info", "_" + arch_dict[net][0] + ".pkl") torch.save(checkpoint, out_file) if to_do == "forward": for out_name in forward_outs: post_file[out_name].close() # Write info file with open(info_file, "w") as text_file: text_file.write("[results]\n") if to_do != "forward": text_file.write("loss=%s\n" % loss_tot.cpu().numpy()) text_file.write("err=%s\n" % err_tot.cpu().numpy()) text_file.write("elapsed_time_chunk=%f\n" % elapsed_time_chunk) text_file.close() # Getting the data for the next chunk (read in parallel) p.join() data_name = shared_list[0] data_end_index = shared_list[1] fea_dict = shared_list[2] lab_dict = shared_list[3] arch_dict = shared_list[4] data_set = shared_list[5] # converting numpy tensors into pytorch tensors and put them on GPUs if specified if not (save_gpumem) and use_cuda: data_set = torch.from_numpy(data_set).float().cuda() else: data_set = torch.from_numpy(data_set).float() return [data_name, data_set, data_end_index, fea_dict, lab_dict, arch_dict]
22,371
33.793157
138
py
pytorch-kaldi-gan
pytorch-kaldi-gan-master/neural_networks.py
########################################################## # pytorch-kaldi v.0.1 # Mirco Ravanelli, Titouan Parcollet # Mila, University of Montreal # October 2018 ########################################################## import torch import torch.nn.functional as F import torch.nn as nn import numpy as np from distutils.util import strtobool import math import json # uncomment below if you want to use SRU # and you need to install SRU: pip install sru[cuda]. # or you can install it from source code: https://github.com/taolei87/sru. # import sru class LayerNorm(nn.Module): def __init__(self, features, eps=1e-6): super(LayerNorm, self).__init__() self.gamma = nn.Parameter(torch.ones(features)) self.beta = nn.Parameter(torch.zeros(features)) self.eps = eps def forward(self, x): mean = x.mean(-1, keepdim=True) std = x.std(-1, keepdim=True) return self.gamma * (x - mean) / (std + self.eps) + self.beta def act_fun(act_type): if act_type == "relu": return nn.ReLU() if act_type == "tanh": return nn.Tanh() if act_type == "sigmoid": return nn.Sigmoid() if act_type == "leaky_relu": return nn.LeakyReLU(0.2) if act_type == "elu": return nn.ELU() if act_type == "softmax": return nn.LogSoftmax(dim=1) if act_type == "linear": return nn.LeakyReLU(1) # initializzed like this, but not used in forward! class MLP(nn.Module): def __init__(self, options, inp_dim): super(MLP, self).__init__() self.input_dim = inp_dim self.dnn_lay = list(map(int, options["dnn_lay"].split(","))) self.dnn_drop = list(map(float, options["dnn_drop"].split(","))) self.dnn_use_batchnorm = list(map(strtobool, options["dnn_use_batchnorm"].split(","))) self.dnn_use_laynorm = list(map(strtobool, options["dnn_use_laynorm"].split(","))) self.dnn_use_laynorm_inp = strtobool(options["dnn_use_laynorm_inp"]) self.dnn_use_batchnorm_inp = strtobool(options["dnn_use_batchnorm_inp"]) self.dnn_act = options["dnn_act"].split(",") self.wx = nn.ModuleList([]) self.bn = nn.ModuleList([]) self.ln = nn.ModuleList([]) self.act = nn.ModuleList([]) self.drop = nn.ModuleList([]) # input layer normalization if self.dnn_use_laynorm_inp: self.ln0 = LayerNorm(self.input_dim) # input batch normalization if self.dnn_use_batchnorm_inp: self.bn0 = nn.BatchNorm1d(self.input_dim, momentum=0.05) self.N_dnn_lay = len(self.dnn_lay) current_input = self.input_dim # Initialization of hidden layers for i in range(self.N_dnn_lay): # dropout self.drop.append(nn.Dropout(p=self.dnn_drop[i])) # activation self.act.append(act_fun(self.dnn_act[i])) add_bias = True # layer norm initialization self.ln.append(LayerNorm(self.dnn_lay[i])) self.bn.append(nn.BatchNorm1d(self.dnn_lay[i], momentum=0.05)) if self.dnn_use_laynorm[i] or self.dnn_use_batchnorm[i]: add_bias = False # Linear operations self.wx.append(nn.Linear(current_input, self.dnn_lay[i], bias=add_bias)) # weight initialization self.wx[i].weight = torch.nn.Parameter( torch.Tensor(self.dnn_lay[i], current_input).uniform_( -np.sqrt(0.01 / (current_input + self.dnn_lay[i])), np.sqrt(0.01 / (current_input + self.dnn_lay[i])), ) ) self.wx[i].bias = torch.nn.Parameter(torch.zeros(self.dnn_lay[i])) current_input = self.dnn_lay[i] self.out_dim = current_input def forward(self, x): # Applying Layer/Batch Norm if bool(self.dnn_use_laynorm_inp): x = self.ln0((x)) if bool(self.dnn_use_batchnorm_inp): x = self.bn0((x)) for i in range(self.N_dnn_lay): if self.dnn_use_laynorm[i] and not (self.dnn_use_batchnorm[i]): x = self.drop[i](self.act[i](self.ln[i](self.wx[i](x)))) if self.dnn_use_batchnorm[i] and not (self.dnn_use_laynorm[i]): x = self.drop[i](self.act[i](self.bn[i](self.wx[i](x)))) if self.dnn_use_batchnorm[i] == True and self.dnn_use_laynorm[i] == True: x = self.drop[i](self.act[i](self.bn[i](self.ln[i](self.wx[i](x))))) if self.dnn_use_batchnorm[i] == False and self.dnn_use_laynorm[i] == False: x = self.drop[i](self.act[i](self.wx[i](x))) return x class LSTM_cudnn(nn.Module): def __init__(self, options, inp_dim): super(LSTM_cudnn, self).__init__() self.input_dim = inp_dim self.hidden_size = int(options["hidden_size"]) self.num_layers = int(options["num_layers"]) self.bias = bool(strtobool(options["bias"])) self.batch_first = bool(strtobool(options["batch_first"])) self.dropout = float(options["dropout"]) self.bidirectional = bool(strtobool(options["bidirectional"])) self.lstm = nn.ModuleList( [ nn.LSTM( self.input_dim, self.hidden_size, self.num_layers, bias=self.bias, dropout=self.dropout, bidirectional=self.bidirectional, ) ] ) for name,param in self.lstm[0].named_parameters(): if 'weight_hh' in name: if self.batch_first: nn.init.orthogonal_(param) elif 'bias' in name: nn.init.zeros_(param) self.out_dim = self.hidden_size + self.bidirectional * self.hidden_size def forward(self, x): if self.bidirectional: h0 = torch.zeros(self.num_layers * 2, x.shape[1], self.hidden_size) c0 = torch.zeros(self.num_layers * 2, x.shape[1], self.hidden_size) else: h0 = torch.zeros(self.num_layers, x.shape[1], self.hidden_size) c0 = torch.zeros(self.num_layers, x.shape[1], self.hidden_size) if x.is_cuda: h0 = h0.cuda() c0 = c0.cuda() output, (hn, cn) = self.lstm[0](x, (h0, c0)) return output class GRU_cudnn(nn.Module): def __init__(self, options, inp_dim): super(GRU_cudnn, self).__init__() self.input_dim = inp_dim self.hidden_size = int(options["hidden_size"]) self.num_layers = int(options["num_layers"]) self.bias = bool(strtobool(options["bias"])) self.batch_first = bool(strtobool(options["batch_first"])) self.dropout = float(options["dropout"]) self.bidirectional = bool(strtobool(options["bidirectional"])) self.gru = nn.ModuleList( [ nn.GRU( self.input_dim, self.hidden_size, self.num_layers, bias=self.bias, dropout=self.dropout, bidirectional=self.bidirectional, ) ] ) for name,param in self.gru[0].named_parameters(): if 'weight_hh' in name: nn.init.orthogonal_(param) elif 'weight_ih' in name: nn.init.xavier_uniform_(param) elif 'bias' in name: nn.init.zeros_(param) self.out_dim = self.hidden_size + self.bidirectional * self.hidden_size def forward(self, x): if self.bidirectional: h0 = torch.zeros(self.num_layers * 2, x.shape[1], self.hidden_size) else: h0 = torch.zeros(self.num_layers, x.shape[1], self.hidden_size) if x.is_cuda: h0 = h0.cuda() output, hn = self.gru[0](x, h0) return output class RNN_cudnn(nn.Module): def __init__(self, options, inp_dim): super(RNN_cudnn, self).__init__() self.input_dim = inp_dim self.hidden_size = int(options["hidden_size"]) self.num_layers = int(options["num_layers"]) self.nonlinearity = options["nonlinearity"] self.bias = bool(strtobool(options["bias"])) self.batch_first = bool(strtobool(options["batch_first"])) self.dropout = float(options["dropout"]) self.bidirectional = bool(strtobool(options["bidirectional"])) self.rnn = nn.ModuleList( [ nn.RNN( self.input_dim, self.hidden_size, self.num_layers, nonlinearity=self.nonlinearity, bias=self.bias, dropout=self.dropout, bidirectional=self.bidirectional, ) ] ) self.out_dim = self.hidden_size + self.bidirectional * self.hidden_size def forward(self, x): if self.bidirectional: h0 = torch.zeros(self.num_layers * 2, x.shape[1], self.hidden_size) else: h0 = torch.zeros(self.num_layers, x.shape[1], self.hidden_size) if x.is_cuda: h0 = h0.cuda() output, hn = self.rnn[0](x, h0) return output class LSTM(nn.Module): def __init__(self, options, inp_dim): super(LSTM, self).__init__() # Reading parameters self.input_dim = inp_dim self.lstm_lay = list(map(int, options["lstm_lay"].split(","))) self.lstm_drop = list(map(float, options["lstm_drop"].split(","))) self.lstm_use_batchnorm = list(map(strtobool, options["lstm_use_batchnorm"].split(","))) self.lstm_use_laynorm = list(map(strtobool, options["lstm_use_laynorm"].split(","))) self.lstm_use_laynorm_inp = strtobool(options["lstm_use_laynorm_inp"]) self.lstm_use_batchnorm_inp = strtobool(options["lstm_use_batchnorm_inp"]) self.lstm_act = options["lstm_act"].split(",") self.lstm_orthinit = strtobool(options["lstm_orthinit"]) self.bidir = strtobool(options["lstm_bidir"]) self.use_cuda = strtobool(options["use_cuda"]) self.to_do = options["to_do"] if self.to_do == "train": self.test_flag = False else: self.test_flag = True # List initialization self.wfx = nn.ModuleList([]) # Forget self.ufh = nn.ModuleList([]) # Forget self.wix = nn.ModuleList([]) # Input self.uih = nn.ModuleList([]) # Input self.wox = nn.ModuleList([]) # Output self.uoh = nn.ModuleList([]) # Output self.wcx = nn.ModuleList([]) # Cell state self.uch = nn.ModuleList([]) # Cell state self.ln = nn.ModuleList([]) # Layer Norm self.bn_wfx = nn.ModuleList([]) # Batch Norm self.bn_wix = nn.ModuleList([]) # Batch Norm self.bn_wox = nn.ModuleList([]) # Batch Norm self.bn_wcx = nn.ModuleList([]) # Batch Norm self.act = nn.ModuleList([]) # Activations # Input layer normalization if self.lstm_use_laynorm_inp: self.ln0 = LayerNorm(self.input_dim) # Input batch normalization if self.lstm_use_batchnorm_inp: self.bn0 = nn.BatchNorm1d(self.input_dim, momentum=0.05) self.N_lstm_lay = len(self.lstm_lay) current_input = self.input_dim # Initialization of hidden layers for i in range(self.N_lstm_lay): # Activations self.act.append(act_fun(self.lstm_act[i])) add_bias = True if self.lstm_use_laynorm[i] or self.lstm_use_batchnorm[i]: add_bias = False # Feed-forward connections self.wfx.append(nn.Linear(current_input, self.lstm_lay[i], bias=add_bias)) self.wix.append(nn.Linear(current_input, self.lstm_lay[i], bias=add_bias)) self.wox.append(nn.Linear(current_input, self.lstm_lay[i], bias=add_bias)) self.wcx.append(nn.Linear(current_input, self.lstm_lay[i], bias=add_bias)) # Recurrent connections self.ufh.append(nn.Linear(self.lstm_lay[i], self.lstm_lay[i], bias=False)) self.uih.append(nn.Linear(self.lstm_lay[i], self.lstm_lay[i], bias=False)) self.uoh.append(nn.Linear(self.lstm_lay[i], self.lstm_lay[i], bias=False)) self.uch.append(nn.Linear(self.lstm_lay[i], self.lstm_lay[i], bias=False)) if self.lstm_orthinit: nn.init.orthogonal_(self.ufh[i].weight) nn.init.orthogonal_(self.uih[i].weight) nn.init.orthogonal_(self.uoh[i].weight) nn.init.orthogonal_(self.uch[i].weight) # batch norm initialization self.bn_wfx.append(nn.BatchNorm1d(self.lstm_lay[i], momentum=0.05)) self.bn_wix.append(nn.BatchNorm1d(self.lstm_lay[i], momentum=0.05)) self.bn_wox.append(nn.BatchNorm1d(self.lstm_lay[i], momentum=0.05)) self.bn_wcx.append(nn.BatchNorm1d(self.lstm_lay[i], momentum=0.05)) self.ln.append(LayerNorm(self.lstm_lay[i])) if self.bidir: current_input = 2 * self.lstm_lay[i] else: current_input = self.lstm_lay[i] self.out_dim = self.lstm_lay[i] + self.bidir * self.lstm_lay[i] def forward(self, x): # Applying Layer/Batch Norm if bool(self.lstm_use_laynorm_inp): x = self.ln0((x)) if bool(self.lstm_use_batchnorm_inp): x_bn = self.bn0(x.view(x.shape[0] * x.shape[1], x.shape[2])) x = x_bn.view(x.shape[0], x.shape[1], x.shape[2]) for i in range(self.N_lstm_lay): # Initial state and concatenation if self.bidir: h_init = torch.zeros(2 * x.shape[1], self.lstm_lay[i]) x = torch.cat([x, flip(x, 0)], 1) else: h_init = torch.zeros(x.shape[1], self.lstm_lay[i]) # Drop mask initilization (same mask for all time steps) if self.test_flag == False: drop_mask = torch.bernoulli(torch.Tensor(h_init.shape[0], h_init.shape[1]).fill_(1 - self.lstm_drop[i])) else: drop_mask = torch.FloatTensor([1 - self.lstm_drop[i]]) if self.use_cuda: h_init = h_init.cuda() drop_mask = drop_mask.cuda() # Feed-forward affine transformations (all steps in parallel) wfx_out = self.wfx[i](x) wix_out = self.wix[i](x) wox_out = self.wox[i](x) wcx_out = self.wcx[i](x) # Apply batch norm if needed (all steos in parallel) if self.lstm_use_batchnorm[i]: wfx_out_bn = self.bn_wfx[i](wfx_out.view(wfx_out.shape[0] * wfx_out.shape[1], wfx_out.shape[2])) wfx_out = wfx_out_bn.view(wfx_out.shape[0], wfx_out.shape[1], wfx_out.shape[2]) wix_out_bn = self.bn_wix[i](wix_out.view(wix_out.shape[0] * wix_out.shape[1], wix_out.shape[2])) wix_out = wix_out_bn.view(wix_out.shape[0], wix_out.shape[1], wix_out.shape[2]) wox_out_bn = self.bn_wox[i](wox_out.view(wox_out.shape[0] * wox_out.shape[1], wox_out.shape[2])) wox_out = wox_out_bn.view(wox_out.shape[0], wox_out.shape[1], wox_out.shape[2]) wcx_out_bn = self.bn_wcx[i](wcx_out.view(wcx_out.shape[0] * wcx_out.shape[1], wcx_out.shape[2])) wcx_out = wcx_out_bn.view(wcx_out.shape[0], wcx_out.shape[1], wcx_out.shape[2]) # Processing time steps hiddens = [] ct = h_init ht = h_init for k in range(x.shape[0]): # LSTM equations ft = torch.sigmoid(wfx_out[k] + self.ufh[i](ht)) it = torch.sigmoid(wix_out[k] + self.uih[i](ht)) ot = torch.sigmoid(wox_out[k] + self.uoh[i](ht)) ct = it * self.act[i](wcx_out[k] + self.uch[i](ht)) * drop_mask + ft * ct ht = ot * self.act[i](ct) if self.lstm_use_laynorm[i]: ht = self.ln[i](ht) hiddens.append(ht) # Stacking hidden states h = torch.stack(hiddens) # Bidirectional concatenations if self.bidir: h_f = h[:, 0 : int(x.shape[1] / 2)] h_b = flip(h[:, int(x.shape[1] / 2) : x.shape[1]].contiguous(), 0) h = torch.cat([h_f, h_b], 2) # Setup x for the next hidden layer x = h return x class GRU(nn.Module): def __init__(self, options, inp_dim): super(GRU, self).__init__() # Reading parameters self.input_dim = inp_dim self.gru_lay = list(map(int, options["gru_lay"].split(","))) self.gru_drop = list(map(float, options["gru_drop"].split(","))) self.gru_use_batchnorm = list(map(strtobool, options["gru_use_batchnorm"].split(","))) self.gru_use_laynorm = list(map(strtobool, options["gru_use_laynorm"].split(","))) self.gru_use_laynorm_inp = strtobool(options["gru_use_laynorm_inp"]) self.gru_use_batchnorm_inp = strtobool(options["gru_use_batchnorm_inp"]) self.gru_orthinit = strtobool(options["gru_orthinit"]) self.gru_act = options["gru_act"].split(",") self.bidir = strtobool(options["gru_bidir"]) self.use_cuda = strtobool(options["use_cuda"]) self.to_do = options["to_do"] if self.to_do == "train": self.test_flag = False else: self.test_flag = True # List initialization self.wh = nn.ModuleList([]) self.uh = nn.ModuleList([]) self.wz = nn.ModuleList([]) # Update Gate self.uz = nn.ModuleList([]) # Update Gate self.wr = nn.ModuleList([]) # Reset Gate self.ur = nn.ModuleList([]) # Reset Gate self.ln = nn.ModuleList([]) # Layer Norm self.bn_wh = nn.ModuleList([]) # Batch Norm self.bn_wz = nn.ModuleList([]) # Batch Norm self.bn_wr = nn.ModuleList([]) # Batch Norm self.act = nn.ModuleList([]) # Activations # Input layer normalization if self.gru_use_laynorm_inp: self.ln0 = LayerNorm(self.input_dim) # Input batch normalization if self.gru_use_batchnorm_inp: self.bn0 = nn.BatchNorm1d(self.input_dim, momentum=0.05) self.N_gru_lay = len(self.gru_lay) current_input = self.input_dim # Initialization of hidden layers for i in range(self.N_gru_lay): # Activations self.act.append(act_fun(self.gru_act[i])) add_bias = True if self.gru_use_laynorm[i] or self.gru_use_batchnorm[i]: add_bias = False # Feed-forward connections self.wh.append(nn.Linear(current_input, self.gru_lay[i], bias=add_bias)) self.wz.append(nn.Linear(current_input, self.gru_lay[i], bias=add_bias)) self.wr.append(nn.Linear(current_input, self.gru_lay[i], bias=add_bias)) # Recurrent connections self.uh.append(nn.Linear(self.gru_lay[i], self.gru_lay[i], bias=False)) self.uz.append(nn.Linear(self.gru_lay[i], self.gru_lay[i], bias=False)) self.ur.append(nn.Linear(self.gru_lay[i], self.gru_lay[i], bias=False)) if self.gru_orthinit: nn.init.orthogonal_(self.uh[i].weight) nn.init.orthogonal_(self.uz[i].weight) nn.init.orthogonal_(self.ur[i].weight) # batch norm initialization self.bn_wh.append(nn.BatchNorm1d(self.gru_lay[i], momentum=0.05)) self.bn_wz.append(nn.BatchNorm1d(self.gru_lay[i], momentum=0.05)) self.bn_wr.append(nn.BatchNorm1d(self.gru_lay[i], momentum=0.05)) self.ln.append(LayerNorm(self.gru_lay[i])) if self.bidir: current_input = 2 * self.gru_lay[i] else: current_input = self.gru_lay[i] self.out_dim = self.gru_lay[i] + self.bidir * self.gru_lay[i] def forward(self, x): # Applying Layer/Batch Norm if bool(self.gru_use_laynorm_inp): x = self.ln0((x)) if bool(self.gru_use_batchnorm_inp): x_bn = self.bn0(x.view(x.shape[0] * x.shape[1], x.shape[2])) x = x_bn.view(x.shape[0], x.shape[1], x.shape[2]) for i in range(self.N_gru_lay): # Initial state and concatenation if self.bidir: h_init = torch.zeros(2 * x.shape[1], self.gru_lay[i]) x = torch.cat([x, flip(x, 0)], 1) else: h_init = torch.zeros(x.shape[1], self.gru_lay[i]) # Drop mask initilization (same mask for all time steps) if self.test_flag == False: drop_mask = torch.bernoulli(torch.Tensor(h_init.shape[0], h_init.shape[1]).fill_(1 - self.gru_drop[i])) else: drop_mask = torch.FloatTensor([1 - self.gru_drop[i]]) if self.use_cuda: h_init = h_init.cuda() drop_mask = drop_mask.cuda() # Feed-forward affine transformations (all steps in parallel) wh_out = self.wh[i](x) wz_out = self.wz[i](x) wr_out = self.wr[i](x) # Apply batch norm if needed (all steos in parallel) if self.gru_use_batchnorm[i]: wh_out_bn = self.bn_wh[i](wh_out.view(wh_out.shape[0] * wh_out.shape[1], wh_out.shape[2])) wh_out = wh_out_bn.view(wh_out.shape[0], wh_out.shape[1], wh_out.shape[2]) wz_out_bn = self.bn_wz[i](wz_out.view(wz_out.shape[0] * wz_out.shape[1], wz_out.shape[2])) wz_out = wz_out_bn.view(wz_out.shape[0], wz_out.shape[1], wz_out.shape[2]) wr_out_bn = self.bn_wr[i](wr_out.view(wr_out.shape[0] * wr_out.shape[1], wr_out.shape[2])) wr_out = wr_out_bn.view(wr_out.shape[0], wr_out.shape[1], wr_out.shape[2]) # Processing time steps hiddens = [] ht = h_init for k in range(x.shape[0]): # gru equation zt = torch.sigmoid(wz_out[k] + self.uz[i](ht)) rt = torch.sigmoid(wr_out[k] + self.ur[i](ht)) at = wh_out[k] + self.uh[i](rt * ht) hcand = self.act[i](at) * drop_mask ht = zt * ht + (1 - zt) * hcand if self.gru_use_laynorm[i]: ht = self.ln[i](ht) hiddens.append(ht) # Stacking hidden states h = torch.stack(hiddens) # Bidirectional concatenations if self.bidir: h_f = h[:, 0 : int(x.shape[1] / 2)] h_b = flip(h[:, int(x.shape[1] / 2) : x.shape[1]].contiguous(), 0) h = torch.cat([h_f, h_b], 2) # Setup x for the next hidden layer x = h return x class logMelFb(nn.Module): def __init__(self, options, inp_dim): super(logMelFb, self).__init__() import torchaudio self._sample_rate = int(options["logmelfb_nr_sample_rate"]) self._nr_of_filters = int(options["logmelfb_nr_filt"]) self._stft_window_size = int(options["logmelfb_stft_window_size"]) self._stft_window_shift = int(options["logmelfb_stft_window_shift"]) self._use_cuda = strtobool(options["use_cuda"]) self.out_dim = self._nr_of_filters self._mspec = torchaudio.transforms.MelSpectrogram( sr=self._sample_rate, n_fft=self._stft_window_size, ws=self._stft_window_size, hop=self._stft_window_shift, n_mels=self._nr_of_filters, ) def forward(self, x): def _safe_log(inp, epsilon=1e-20): eps = torch.FloatTensor([epsilon]) if self._use_cuda: eps = eps.cuda() log_inp = torch.log10(torch.max(inp, eps.expand_as(inp))) return log_inp assert x.shape[-1] == 1, "Multi channel time signal processing not suppored yet" x_reshape_for_stft = torch.squeeze(x, -1).transpose(0, 1) if self._use_cuda: window = self._mspec.window(self._stft_window_size).cuda() else: window = self._mspec.window(self._stft_window_size) x_stft = torch.stft( x_reshape_for_stft, self._stft_window_size, hop_length=self._stft_window_shift, center=False, window=window ) x_power_stft = x_stft.pow(2).sum(-1) x_power_stft_reshape_for_filterbank_mult = x_power_stft.transpose(1, 2) mel_spec = self._mspec.fm(x_power_stft_reshape_for_filterbank_mult).transpose(0, 1) log_mel_spec = _safe_log(mel_spec) out = log_mel_spec return out class channel_averaging(nn.Module): def __init__(self, options, inp_dim): super(channel_averaging, self).__init__() self._use_cuda = strtobool(options["use_cuda"]) channel_weights = [float(e) for e in options["chAvg_channelWeights"].split(",")] self._nr_of_channels = len(channel_weights) numpy_weights = np.asarray(channel_weights, dtype=np.float32) * 1.0 / np.sum(channel_weights) self._weights = torch.from_numpy(numpy_weights) if self._use_cuda: self._weights = self._weights.cuda() self.out_dim = 1 def forward(self, x): assert self._nr_of_channels == x.shape[-1] out = torch.einsum("tbc,c->tb", x, self._weights).unsqueeze(-1) return out class fusionRNN_jit(torch.jit.ScriptModule): def __init__(self, options, inp_dim): super(fusionRNN_jit, self).__init__() # Reading parameters input_size = inp_dim hidden_size = list(map(int, options["fusionRNN_lay"].split(",")))[0] dropout = list(map(float, options["fusionRNN_drop"].split(",")))[0] num_layers = len(list(map(int, options["fusionRNN_lay"].split(",")))) batch_size = int(options["batches"]) self.do_fusion = map(strtobool, options["fusionRNN_do_fusion"].split(",")) self.act = str(options["fusionRNN_fusion_act"]) self.reduce = str(options["fusionRNN_fusion_reduce"]) self.fusion_layer_size = int(options["fusionRNN_fusion_layer_size"]) self.to_do = options["to_do"] self.number_of_mic = int(options["fusionRNN_number_of_mic"]) self.save_mic = self.number_of_mic bidirectional = True self.out_dim = 2 * hidden_size current_dim = int(input_size) self.model = torch.nn.ModuleList([]) if self.to_do == "train": self.training = True else: self.training = False for i in range(num_layers): rnn_lay = liGRU_layer( current_dim, hidden_size, num_layers, batch_size, dropout=dropout, bidirectional=bidirectional, device="cuda", do_fusion=self.do_fusion, fusion_layer_size=self.fusion_layer_size, number_of_mic=self.number_of_mic, act=self.act, reduce=self.reduce ) if i == 0: if self.do_fusion: if bidirectional: current_dim = (self.fusion_layer_size // self.save_mic) * 2 else: current_dim = self.fusion_layer_size // self.save_mic #We need to reset the number of mic for the next layers so it is divided by 1 self.number_of_mic = 1 else: if bidirectional: current_dim = hidden_size * 2 else: current_dim = hidden_size self.do_fusion = False # DO NOT APPLY FUSION ON THE NEXT LAYERS else: if bidirectional: current_dim = hidden_size * 2 else: current_dim == hidden_size self.model.append(rnn_lay) @torch.jit.script_method def forward(self, x): # type: (Tensor) -> Tensor for ligru_lay in self.model: x = ligru_lay(x) return x class liGRU_layer(torch.jit.ScriptModule): def __init__( self, input_size, hidden_size, num_layers, batch_size, dropout=0.0, nonlinearity="relu", bidirectional=True, device="cuda", do_fusion=False, fusion_layer_size=64, number_of_mic=1, act="relu", reduce="mean", ): super(liGRU_layer, self).__init__() self.hidden_size = int(hidden_size) self.input_size = int(input_size) self.batch_size = batch_size self.bidirectional = bidirectional self.dropout = dropout self.device = device self.do_fusion = do_fusion self.fusion_layer_size = fusion_layer_size self.number_of_mic = number_of_mic self.act = act self.reduce = reduce if self.do_fusion: self.hidden_size = self.fusion_layer_size // self.number_of_mic if self.do_fusion: self.wz = FusionLinearConv( self.input_size, self.hidden_size, bias=True, number_of_mic = self.number_of_mic, act=self.act, reduce=self.reduce ).to(device) self.wh = FusionLinearConv( self.input_size, self.hidden_size, bias=True, number_of_mic = self.number_of_mic, act=self.act, reduce=self.reduce ).to(device) else: self.wz = nn.Linear( self.input_size, self.hidden_size, bias=True ).to(device) self.wh = nn.Linear( self.input_size, self.hidden_size, bias=True ).to(device) self.wz.bias.data.fill_(0) torch.nn.init.xavier_normal_(self.wz.weight.data) self.wh.bias.data.fill_(0) torch.nn.init.xavier_normal_(self.wh.weight.data) self.u = nn.Linear( self.hidden_size, 2 * self.hidden_size, bias=False ).to(device) # Adding orthogonal initialization for recurrent connection nn.init.orthogonal_(self.u.weight) self.bn_wh = nn.BatchNorm1d(self.hidden_size, momentum=0.05).to( device ) self.bn_wz = nn.BatchNorm1d(self.hidden_size, momentum=0.05).to( device ) self.drop = torch.nn.Dropout(p=self.dropout, inplace=False).to(device) self.drop_mask_te = torch.tensor([1.0], device=device).float() self.N_drop_masks = 100 self.drop_mask_cnt = 0 # Setting the activation function self.act = torch.nn.ReLU().to(device) @torch.jit.script_method def forward(self, x): # type: (Tensor) -> Tensor if self.bidirectional: x_flip = x.flip(0) x = torch.cat([x, x_flip], dim=1) # Feed-forward affine transformations (all steps in parallel) wz = self.wz(x) wh = self.wh(x) # Apply batch normalization wz_bn = self.bn_wz(wz.view(wz.shape[0] * wz.shape[1], wz.shape[2])) wh_bn = self.bn_wh(wh.view(wh.shape[0] * wh.shape[1], wh.shape[2])) wz = wz_bn.view(wz.shape[0], wz.shape[1], wz.shape[2]) wh = wh_bn.view(wh.shape[0], wh.shape[1], wh.shape[2]) # Processing time steps h = self.ligru_cell(wz, wh) if self.bidirectional: h_f, h_b = h.chunk(2, dim=1) h_b = h_b.flip(0) h = torch.cat([h_f, h_b], dim=2) return h @torch.jit.script_method def ligru_cell(self, wz, wh): # type: (Tensor, Tensor) -> Tensor if self.bidirectional: h_init = torch.zeros( 2 * self.batch_size, self.hidden_size, device="cuda", ) drop_masks_i = self.drop( torch.ones( self.N_drop_masks, 2 * self.batch_size, self.hidden_size, device="cuda", ) ).data else: h_init = torch.zeros( self.batch_size, self.hidden_size, device="cuda", ) drop_masks_i = self.drop( torch.ones( self.N_drop_masks, self.batch_size, self.hidden_size, device="cuda", ) ).data hiddens = [] ht = h_init if self.training: drop_mask = drop_masks_i[self.drop_mask_cnt] self.drop_mask_cnt = self.drop_mask_cnt + 1 if self.drop_mask_cnt >= self.N_drop_masks: self.drop_mask_cnt = 0 if self.bidirectional: drop_masks_i = ( self.drop( torch.ones( self.N_drop_masks, 2 * self.batch_size, self.hidden_size, ) ) .to(self.device) .data ) else: drop_masks_i = ( self.drop( torch.ones( self.N_drop_masks, self.batch_size, self.hidden_size, ) ) .to(self.device) .data ) else: drop_mask = self.drop_mask_te for k in range(wh.shape[0]): uz, uh = self.u(ht).chunk(2, 1) at = wh[k] + uh zt = wz[k] + uz # ligru equation zt = torch.sigmoid(zt) hcand = self.act(at) * drop_mask ht = zt * ht + (1 - zt) * hcand hiddens.append(ht) # Stacking hidden states h = torch.stack(hiddens) return h class liGRU(nn.Module): def __init__(self, options, inp_dim): super(liGRU, self).__init__() # Reading parameters self.input_dim = inp_dim self.ligru_lay = list(map(int, options["ligru_lay"].split(","))) self.ligru_drop = list(map(float, options["ligru_drop"].split(","))) self.ligru_use_batchnorm = list(map(strtobool, options["ligru_use_batchnorm"].split(","))) self.ligru_use_laynorm = list(map(strtobool, options["ligru_use_laynorm"].split(","))) self.ligru_use_laynorm_inp = strtobool(options["ligru_use_laynorm_inp"]) self.ligru_use_batchnorm_inp = strtobool(options["ligru_use_batchnorm_inp"]) self.ligru_orthinit = strtobool(options["ligru_orthinit"]) self.ligru_act = options["ligru_act"].split(",") self.bidir = strtobool(options["ligru_bidir"]) self.use_cuda = strtobool(options["use_cuda"]) self.to_do = options["to_do"] if self.to_do == "train": self.test_flag = False else: self.test_flag = True # List initialization self.wh = nn.ModuleList([]) self.uh = nn.ModuleList([]) self.wz = nn.ModuleList([]) # Update Gate self.uz = nn.ModuleList([]) # Update Gate self.ln = nn.ModuleList([]) # Layer Norm self.bn_wh = nn.ModuleList([]) # Batch Norm self.bn_wz = nn.ModuleList([]) # Batch Norm self.act = nn.ModuleList([]) # Activations # Input layer normalization if self.ligru_use_laynorm_inp: self.ln0 = LayerNorm(self.input_dim) # Input batch normalization if self.ligru_use_batchnorm_inp: self.bn0 = nn.BatchNorm1d(self.input_dim, momentum=0.05) self.N_ligru_lay = len(self.ligru_lay) current_input = self.input_dim # Initialization of hidden layers for i in range(self.N_ligru_lay): # Activations self.act.append(act_fun(self.ligru_act[i])) add_bias = True if self.ligru_use_laynorm[i] or self.ligru_use_batchnorm[i]: add_bias = False # Feed-forward connections self.wh.append(nn.Linear(current_input, self.ligru_lay[i], bias=add_bias)) self.wz.append(nn.Linear(current_input, self.ligru_lay[i], bias=add_bias)) # Recurrent connections self.uh.append(nn.Linear(self.ligru_lay[i], self.ligru_lay[i], bias=False)) self.uz.append(nn.Linear(self.ligru_lay[i], self.ligru_lay[i], bias=False)) if self.ligru_orthinit: nn.init.orthogonal_(self.uh[i].weight) nn.init.orthogonal_(self.uz[i].weight) # batch norm initialization self.bn_wh.append(nn.BatchNorm1d(self.ligru_lay[i], momentum=0.05)) self.bn_wz.append(nn.BatchNorm1d(self.ligru_lay[i], momentum=0.05)) self.ln.append(LayerNorm(self.ligru_lay[i])) if self.bidir: current_input = 2 * self.ligru_lay[i] else: current_input = self.ligru_lay[i] self.out_dim = self.ligru_lay[i] + self.bidir * self.ligru_lay[i] def forward(self, x): # Applying Layer/Batch Norm if bool(self.ligru_use_laynorm_inp): x = self.ln0((x)) if bool(self.ligru_use_batchnorm_inp): x_bn = self.bn0(x.view(x.shape[0] * x.shape[1], x.shape[2])) x = x_bn.view(x.shape[0], x.shape[1], x.shape[2]) for i in range(self.N_ligru_lay): # Initial state and concatenation if self.bidir: h_init = torch.zeros(2 * x.shape[1], self.ligru_lay[i]) x = torch.cat([x, flip(x, 0)], 1) else: h_init = torch.zeros(x.shape[1], self.ligru_lay[i]) # Drop mask initilization (same mask for all time steps) if self.test_flag == False: drop_mask = torch.bernoulli( torch.Tensor(h_init.shape[0], h_init.shape[1]).fill_(1 - self.ligru_drop[i]) ) else: drop_mask = torch.FloatTensor([1 - self.ligru_drop[i]]) if self.use_cuda: h_init = h_init.cuda() drop_mask = drop_mask.cuda() # Feed-forward affine transformations (all steps in parallel) wh_out = self.wh[i](x) wz_out = self.wz[i](x) # Apply batch norm if needed (all steos in parallel) if self.ligru_use_batchnorm[i]: wh_out_bn = self.bn_wh[i](wh_out.view(wh_out.shape[0] * wh_out.shape[1], wh_out.shape[2])) wh_out = wh_out_bn.view(wh_out.shape[0], wh_out.shape[1], wh_out.shape[2]) wz_out_bn = self.bn_wz[i](wz_out.view(wz_out.shape[0] * wz_out.shape[1], wz_out.shape[2])) wz_out = wz_out_bn.view(wz_out.shape[0], wz_out.shape[1], wz_out.shape[2]) # Processing time steps hiddens = [] ht = h_init for k in range(x.shape[0]): # ligru equation zt = torch.sigmoid(wz_out[k] + self.uz[i](ht)) at = wh_out[k] + self.uh[i](ht) hcand = self.act[i](at) * drop_mask ht = zt * ht + (1 - zt) * hcand if self.ligru_use_laynorm[i]: ht = self.ln[i](ht) hiddens.append(ht) # Stacking hidden states h = torch.stack(hiddens) # Bidirectional concatenations if self.bidir: h_f = h[:, 0 : int(x.shape[1] / 2)] h_b = flip(h[:, int(x.shape[1] / 2) : x.shape[1]].contiguous(), 0) h = torch.cat([h_f, h_b], 2) # Setup x for the next hidden layer x = h return x class minimalGRU(nn.Module): def __init__(self, options, inp_dim): super(minimalGRU, self).__init__() # Reading parameters self.input_dim = inp_dim self.minimalgru_lay = list(map(int, options["minimalgru_lay"].split(","))) self.minimalgru_drop = list(map(float, options["minimalgru_drop"].split(","))) self.minimalgru_use_batchnorm = list(map(strtobool, options["minimalgru_use_batchnorm"].split(","))) self.minimalgru_use_laynorm = list(map(strtobool, options["minimalgru_use_laynorm"].split(","))) self.minimalgru_use_laynorm_inp = strtobool(options["minimalgru_use_laynorm_inp"]) self.minimalgru_use_batchnorm_inp = strtobool(options["minimalgru_use_batchnorm_inp"]) self.minimalgru_orthinit = strtobool(options["minimalgru_orthinit"]) self.minimalgru_act = options["minimalgru_act"].split(",") self.bidir = strtobool(options["minimalgru_bidir"]) self.use_cuda = strtobool(options["use_cuda"]) self.to_do = options["to_do"] if self.to_do == "train": self.test_flag = False else: self.test_flag = True # List initialization self.wh = nn.ModuleList([]) self.uh = nn.ModuleList([]) self.wz = nn.ModuleList([]) # Update Gate self.uz = nn.ModuleList([]) # Update Gate self.ln = nn.ModuleList([]) # Layer Norm self.bn_wh = nn.ModuleList([]) # Batch Norm self.bn_wz = nn.ModuleList([]) # Batch Norm self.act = nn.ModuleList([]) # Activations # Input layer normalization if self.minimalgru_use_laynorm_inp: self.ln0 = LayerNorm(self.input_dim) # Input batch normalization if self.minimalgru_use_batchnorm_inp: self.bn0 = nn.BatchNorm1d(self.input_dim, momentum=0.05) self.N_minimalgru_lay = len(self.minimalgru_lay) current_input = self.input_dim # Initialization of hidden layers for i in range(self.N_minimalgru_lay): # Activations self.act.append(act_fun(self.minimalgru_act[i])) add_bias = True if self.minimalgru_use_laynorm[i] or self.minimalgru_use_batchnorm[i]: add_bias = False # Feed-forward connections self.wh.append(nn.Linear(current_input, self.minimalgru_lay[i], bias=add_bias)) self.wz.append(nn.Linear(current_input, self.minimalgru_lay[i], bias=add_bias)) # Recurrent connections self.uh.append(nn.Linear(self.minimalgru_lay[i], self.minimalgru_lay[i], bias=False)) self.uz.append(nn.Linear(self.minimalgru_lay[i], self.minimalgru_lay[i], bias=False)) if self.minimalgru_orthinit: nn.init.orthogonal_(self.uh[i].weight) nn.init.orthogonal_(self.uz[i].weight) # batch norm initialization self.bn_wh.append(nn.BatchNorm1d(self.minimalgru_lay[i], momentum=0.05)) self.bn_wz.append(nn.BatchNorm1d(self.minimalgru_lay[i], momentum=0.05)) self.ln.append(LayerNorm(self.minimalgru_lay[i])) if self.bidir: current_input = 2 * self.minimalgru_lay[i] else: current_input = self.minimalgru_lay[i] self.out_dim = self.minimalgru_lay[i] + self.bidir * self.minimalgru_lay[i] def forward(self, x): # Applying Layer/Batch Norm if bool(self.minimalgru_use_laynorm_inp): x = self.ln0((x)) if bool(self.minimalgru_use_batchnorm_inp): x_bn = self.bn0(x.view(x.shape[0] * x.shape[1], x.shape[2])) x = x_bn.view(x.shape[0], x.shape[1], x.shape[2]) for i in range(self.N_minimalgru_lay): # Initial state and concatenation if self.bidir: h_init = torch.zeros(2 * x.shape[1], self.minimalgru_lay[i]) x = torch.cat([x, flip(x, 0)], 1) else: h_init = torch.zeros(x.shape[1], self.minimalgru_lay[i]) # Drop mask initilization (same mask for all time steps) if self.test_flag == False: drop_mask = torch.bernoulli( torch.Tensor(h_init.shape[0], h_init.shape[1]).fill_(1 - self.minimalgru_drop[i]) ) else: drop_mask = torch.FloatTensor([1 - self.minimalgru_drop[i]]) if self.use_cuda: h_init = h_init.cuda() drop_mask = drop_mask.cuda() # Feed-forward affine transformations (all steps in parallel) wh_out = self.wh[i](x) wz_out = self.wz[i](x) # Apply batch norm if needed (all steos in parallel) if self.minimalgru_use_batchnorm[i]: wh_out_bn = self.bn_wh[i](wh_out.view(wh_out.shape[0] * wh_out.shape[1], wh_out.shape[2])) wh_out = wh_out_bn.view(wh_out.shape[0], wh_out.shape[1], wh_out.shape[2]) wz_out_bn = self.bn_wz[i](wz_out.view(wz_out.shape[0] * wz_out.shape[1], wz_out.shape[2])) wz_out = wz_out_bn.view(wz_out.shape[0], wz_out.shape[1], wz_out.shape[2]) # Processing time steps hiddens = [] ht = h_init for k in range(x.shape[0]): # minimalgru equation zt = torch.sigmoid(wz_out[k] + self.uz[i](ht)) at = wh_out[k] + self.uh[i](zt * ht) hcand = self.act[i](at) * drop_mask ht = zt * ht + (1 - zt) * hcand if self.minimalgru_use_laynorm[i]: ht = self.ln[i](ht) hiddens.append(ht) # Stacking hidden states h = torch.stack(hiddens) # Bidirectional concatenations if self.bidir: h_f = h[:, 0 : int(x.shape[1] / 2)] h_b = flip(h[:, int(x.shape[1] / 2) : x.shape[1]].contiguous(), 0) h = torch.cat([h_f, h_b], 2) # Setup x for the next hidden layer x = h return x class RNN(nn.Module): def __init__(self, options, inp_dim): super(RNN, self).__init__() # Reading parameters self.input_dim = inp_dim self.rnn_lay = list(map(int, options["rnn_lay"].split(","))) self.rnn_drop = list(map(float, options["rnn_drop"].split(","))) self.rnn_use_batchnorm = list(map(strtobool, options["rnn_use_batchnorm"].split(","))) self.rnn_use_laynorm = list(map(strtobool, options["rnn_use_laynorm"].split(","))) self.rnn_use_laynorm_inp = strtobool(options["rnn_use_laynorm_inp"]) self.rnn_use_batchnorm_inp = strtobool(options["rnn_use_batchnorm_inp"]) self.rnn_orthinit = strtobool(options["rnn_orthinit"]) self.rnn_act = options["rnn_act"].split(",") self.bidir = strtobool(options["rnn_bidir"]) self.use_cuda = strtobool(options["use_cuda"]) self.to_do = options["to_do"] if self.to_do == "train": self.test_flag = False else: self.test_flag = True # List initialization self.wh = nn.ModuleList([]) self.uh = nn.ModuleList([]) self.ln = nn.ModuleList([]) # Layer Norm self.bn_wh = nn.ModuleList([]) # Batch Norm self.act = nn.ModuleList([]) # Activations # Input layer normalization if self.rnn_use_laynorm_inp: self.ln0 = LayerNorm(self.input_dim) # Input batch normalization if self.rnn_use_batchnorm_inp: self.bn0 = nn.BatchNorm1d(self.input_dim, momentum=0.05) self.N_rnn_lay = len(self.rnn_lay) current_input = self.input_dim # Initialization of hidden layers for i in range(self.N_rnn_lay): # Activations self.act.append(act_fun(self.rnn_act[i])) add_bias = True if self.rnn_use_laynorm[i] or self.rnn_use_batchnorm[i]: add_bias = False # Feed-forward connections self.wh.append(nn.Linear(current_input, self.rnn_lay[i], bias=add_bias)) # Recurrent connections self.uh.append(nn.Linear(self.rnn_lay[i], self.rnn_lay[i], bias=False)) if self.rnn_orthinit: nn.init.orthogonal_(self.uh[i].weight) # batch norm initialization self.bn_wh.append(nn.BatchNorm1d(self.rnn_lay[i], momentum=0.05)) self.ln.append(LayerNorm(self.rnn_lay[i])) if self.bidir: current_input = 2 * self.rnn_lay[i] else: current_input = self.rnn_lay[i] self.out_dim = self.rnn_lay[i] + self.bidir * self.rnn_lay[i] def forward(self, x): # Applying Layer/Batch Norm if bool(self.rnn_use_laynorm_inp): x = self.ln0((x)) if bool(self.rnn_use_batchnorm_inp): x_bn = self.bn0(x.view(x.shape[0] * x.shape[1], x.shape[2])) x = x_bn.view(x.shape[0], x.shape[1], x.shape[2]) for i in range(self.N_rnn_lay): # Initial state and concatenation if self.bidir: h_init = torch.zeros(2 * x.shape[1], self.rnn_lay[i]) x = torch.cat([x, flip(x, 0)], 1) else: h_init = torch.zeros(x.shape[1], self.rnn_lay[i]) # Drop mask initilization (same mask for all time steps) if self.test_flag == False: drop_mask = torch.bernoulli(torch.Tensor(h_init.shape[0], h_init.shape[1]).fill_(1 - self.rnn_drop[i])) else: drop_mask = torch.FloatTensor([1 - self.rnn_drop[i]]) if self.use_cuda: h_init = h_init.cuda() drop_mask = drop_mask.cuda() # Feed-forward affine transformations (all steps in parallel) wh_out = self.wh[i](x) # Apply batch norm if needed (all steos in parallel) if self.rnn_use_batchnorm[i]: wh_out_bn = self.bn_wh[i](wh_out.view(wh_out.shape[0] * wh_out.shape[1], wh_out.shape[2])) wh_out = wh_out_bn.view(wh_out.shape[0], wh_out.shape[1], wh_out.shape[2]) # Processing time steps hiddens = [] ht = h_init for k in range(x.shape[0]): # rnn equation at = wh_out[k] + self.uh[i](ht) ht = self.act[i](at) * drop_mask if self.rnn_use_laynorm[i]: ht = self.ln[i](ht) hiddens.append(ht) # Stacking hidden states h = torch.stack(hiddens) # Bidirectional concatenations if self.bidir: h_f = h[:, 0 : int(x.shape[1] / 2)] h_b = flip(h[:, int(x.shape[1] / 2) : x.shape[1]].contiguous(), 0) h = torch.cat([h_f, h_b], 2) # Setup x for the next hidden layer x = h return x class CNN(nn.Module): def __init__(self, options, inp_dim): super(CNN, self).__init__() # Reading parameters self.input_dim = inp_dim self.cnn_N_filt = list(map(int, options["cnn_N_filt"].split(","))) self.cnn_len_filt = list(map(int, options["cnn_len_filt"].split(","))) self.cnn_max_pool_len = list(map(int, options["cnn_max_pool_len"].split(","))) self.cnn_act = options["cnn_act"].split(",") self.cnn_drop = list(map(float, options["cnn_drop"].split(","))) self.cnn_use_laynorm = list(map(strtobool, options["cnn_use_laynorm"].split(","))) self.cnn_use_batchnorm = list(map(strtobool, options["cnn_use_batchnorm"].split(","))) self.cnn_use_laynorm_inp = strtobool(options["cnn_use_laynorm_inp"]) self.cnn_use_batchnorm_inp = strtobool(options["cnn_use_batchnorm_inp"]) self.N_cnn_lay = len(self.cnn_N_filt) self.conv = nn.ModuleList([]) self.bn = nn.ModuleList([]) self.ln = nn.ModuleList([]) self.act = nn.ModuleList([]) self.drop = nn.ModuleList([]) if self.cnn_use_laynorm_inp: self.ln0 = LayerNorm(self.input_dim) if self.cnn_use_batchnorm_inp: self.bn0 = nn.BatchNorm1d([self.input_dim], momentum=0.05) current_input = self.input_dim for i in range(self.N_cnn_lay): N_filt = int(self.cnn_N_filt[i]) len_filt = int(self.cnn_len_filt[i]) # dropout self.drop.append(nn.Dropout(p=self.cnn_drop[i])) # activation self.act.append(act_fun(self.cnn_act[i])) # layer norm initialization self.ln.append( LayerNorm([N_filt, int((current_input - self.cnn_len_filt[i] + 1) / self.cnn_max_pool_len[i])]) ) self.bn.append( nn.BatchNorm1d( N_filt, int((current_input - self.cnn_len_filt[i] + 1) / self.cnn_max_pool_len[i]), momentum=0.05 ) ) if i == 0: self.conv.append(nn.Conv1d(1, N_filt, len_filt)) else: self.conv.append(nn.Conv1d(self.cnn_N_filt[i - 1], self.cnn_N_filt[i], self.cnn_len_filt[i])) current_input = int((current_input - self.cnn_len_filt[i] + 1) / self.cnn_max_pool_len[i]) self.out_dim = current_input * N_filt def forward(self, x): batch = x.shape[0] seq_len = x.shape[1] if bool(self.cnn_use_laynorm_inp): x = self.ln0((x)) if bool(self.cnn_use_batchnorm_inp): x = self.bn0((x)) x = x.view(batch, 1, seq_len) for i in range(self.N_cnn_lay): if self.cnn_use_laynorm[i]: x = self.drop[i](self.act[i](self.ln[i](F.max_pool1d(self.conv[i](x), self.cnn_max_pool_len[i])))) if self.cnn_use_batchnorm[i]: x = self.drop[i](self.act[i](self.bn[i](F.max_pool1d(self.conv[i](x), self.cnn_max_pool_len[i])))) if self.cnn_use_batchnorm[i] == False and self.cnn_use_laynorm[i] == False: x = self.drop[i](self.act[i](F.max_pool1d(self.conv[i](x), self.cnn_max_pool_len[i]))) x = x.view(batch, -1) return x class SincNet(nn.Module): def __init__(self, options, inp_dim): super(SincNet, self).__init__() # Reading parameters self.input_dim = inp_dim self.sinc_N_filt = list(map(int, options["sinc_N_filt"].split(","))) self.sinc_len_filt = list(map(int, options["sinc_len_filt"].split(","))) self.sinc_max_pool_len = list(map(int, options["sinc_max_pool_len"].split(","))) self.sinc_act = options["sinc_act"].split(",") self.sinc_drop = list(map(float, options["sinc_drop"].split(","))) self.sinc_use_laynorm = list(map(strtobool, options["sinc_use_laynorm"].split(","))) self.sinc_use_batchnorm = list(map(strtobool, options["sinc_use_batchnorm"].split(","))) self.sinc_use_laynorm_inp = strtobool(options["sinc_use_laynorm_inp"]) self.sinc_use_batchnorm_inp = strtobool(options["sinc_use_batchnorm_inp"]) self.N_sinc_lay = len(self.sinc_N_filt) self.sinc_sample_rate = int(options["sinc_sample_rate"]) self.sinc_min_low_hz = int(options["sinc_min_low_hz"]) self.sinc_min_band_hz = int(options["sinc_min_band_hz"]) self.conv = nn.ModuleList([]) self.bn = nn.ModuleList([]) self.ln = nn.ModuleList([]) self.act = nn.ModuleList([]) self.drop = nn.ModuleList([]) if self.sinc_use_laynorm_inp: self.ln0 = LayerNorm(self.input_dim) if self.sinc_use_batchnorm_inp: self.bn0 = nn.BatchNorm1d([self.input_dim], momentum=0.05) current_input = self.input_dim for i in range(self.N_sinc_lay): N_filt = int(self.sinc_N_filt[i]) len_filt = int(self.sinc_len_filt[i]) # dropout self.drop.append(nn.Dropout(p=self.sinc_drop[i])) # activation self.act.append(act_fun(self.sinc_act[i])) # layer norm initialization self.ln.append( LayerNorm([N_filt, int((current_input - self.sinc_len_filt[i] + 1) / self.sinc_max_pool_len[i])]) ) self.bn.append( nn.BatchNorm1d( N_filt, int((current_input - self.sinc_len_filt[i] + 1) / self.sinc_max_pool_len[i]), momentum=0.05 ) ) if i == 0: self.conv.append( SincConv( 1, N_filt, len_filt, sample_rate=self.sinc_sample_rate, min_low_hz=self.sinc_min_low_hz, min_band_hz=self.sinc_min_band_hz, ) ) else: self.conv.append(nn.Conv1d(self.sinc_N_filt[i - 1], self.sinc_N_filt[i], self.sinc_len_filt[i])) current_input = int((current_input - self.sinc_len_filt[i] + 1) / self.sinc_max_pool_len[i]) self.out_dim = current_input * N_filt def forward(self, x): batch = x.shape[0] seq_len = x.shape[1] if bool(self.sinc_use_laynorm_inp): x = self.ln0(x) if bool(self.sinc_use_batchnorm_inp): x = self.bn0(x) x = x.view(batch, 1, seq_len) for i in range(self.N_sinc_lay): if self.sinc_use_laynorm[i]: x = self.drop[i](self.act[i](self.ln[i](F.max_pool1d(self.conv[i](x), self.sinc_max_pool_len[i])))) if self.sinc_use_batchnorm[i]: x = self.drop[i](self.act[i](self.bn[i](F.max_pool1d(self.conv[i](x), self.sinc_max_pool_len[i])))) if self.sinc_use_batchnorm[i] == False and self.sinc_use_laynorm[i] == False: x = self.drop[i](self.act[i](F.max_pool1d(self.conv[i](x), self.sinc_max_pool_len[i]))) x = x.view(batch, -1) return x class SincConv(nn.Module): """Sinc-based convolution Parameters ---------- in_channels : `int` Number of input channels. Must be 1. out_channels : `int` Number of filters. kernel_size : `int` Filter length. sample_rate : `int`, optional Sample rate. Defaults to 16000. Usage ----- See `torch.nn.Conv1d` Reference --------- Mirco Ravanelli, Yoshua Bengio, "Speaker Recognition from raw waveform with SincNet". https://arxiv.org/abs/1808.00158 """ @staticmethod def to_mel(hz): return 2595 * np.log10(1 + hz / 700) @staticmethod def to_hz(mel): return 700 * (10 ** (mel / 2595) - 1) def __init__( self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, bias=False, groups=1, sample_rate=16000, min_low_hz=50, min_band_hz=50, ): super(SincConv, self).__init__() if in_channels != 1: # msg = (f'SincConv only support one input channel ' # f'(here, in_channels = {in_channels:d}).') msg = "SincConv only support one input channel (here, in_channels = {%i})" % (in_channels) raise ValueError(msg) self.out_channels = out_channels self.kernel_size = kernel_size # Forcing the filters to be odd (i.e, perfectly symmetrics) if kernel_size % 2 == 0: self.kernel_size = self.kernel_size + 1 self.stride = stride self.padding = padding self.dilation = dilation if bias: raise ValueError("SincConv does not support bias.") if groups > 1: raise ValueError("SincConv does not support groups.") self.sample_rate = sample_rate self.min_low_hz = min_low_hz self.min_band_hz = min_band_hz # initialize filterbanks such that they are equally spaced in Mel scale low_hz = 30 high_hz = self.sample_rate / 2 - (self.min_low_hz + self.min_band_hz) mel = np.linspace(self.to_mel(low_hz), self.to_mel(high_hz), self.out_channels + 1) hz = self.to_hz(mel) / self.sample_rate # filter lower frequency (out_channels, 1) self.low_hz_ = nn.Parameter(torch.Tensor(hz[:-1]).view(-1, 1)) # filter frequency band (out_channels, 1) self.band_hz_ = nn.Parameter(torch.Tensor(np.diff(hz)).view(-1, 1)) # Hamming window # self.window_ = torch.hamming_window(self.kernel_size) n_lin = torch.linspace(0, self.kernel_size, steps=self.kernel_size) self.window_ = 0.54 - 0.46 * torch.cos(2 * math.pi * n_lin / self.kernel_size) # (kernel_size, 1) n = (self.kernel_size - 1) / 2 self.n_ = torch.arange(-n, n + 1).view(1, -1) / self.sample_rate def sinc(self, x): # Numerically stable definition x_left = x[:, 0 : int((x.shape[1] - 1) / 2)] y_left = torch.sin(x_left) / x_left y_right = torch.flip(y_left, dims=[1]) sinc = torch.cat([y_left, torch.ones([x.shape[0], 1]).to(x.device), y_right], dim=1) return sinc def forward(self, waveforms): """ Parameters ---------- waveforms : `torch.Tensor` (batch_size, 1, n_samples) Batch of waveforms. Returns ------- features : `torch.Tensor` (batch_size, out_channels, n_samples_out) Batch of sinc filters activations. """ self.n_ = self.n_.to(waveforms.device) self.window_ = self.window_.to(waveforms.device) low = self.min_low_hz / self.sample_rate + torch.abs(self.low_hz_) high = low + self.min_band_hz / self.sample_rate + torch.abs(self.band_hz_) f_times_t = torch.matmul(low, self.n_) low_pass1 = 2 * low * self.sinc(2 * math.pi * f_times_t * self.sample_rate) f_times_t = torch.matmul(high, self.n_) low_pass2 = 2 * high * self.sinc(2 * math.pi * f_times_t * self.sample_rate) band_pass = low_pass2 - low_pass1 max_, _ = torch.max(band_pass, dim=1, keepdim=True) band_pass = band_pass / max_ self.filters = (band_pass * self.window_).view(self.out_channels, 1, self.kernel_size) return F.conv1d( waveforms, self.filters, stride=self.stride, padding=self.padding, dilation=self.dilation, bias=None, groups=1, ) class SincConv_fast(nn.Module): """Sinc-based convolution Parameters ---------- in_channels : `int` Number of input channels. Must be 1. out_channels : `int` Number of filters. kernel_size : `int` Filter length. sample_rate : `int`, optional Sample rate. Defaults to 16000. Usage ----- See `torch.nn.Conv1d` Reference --------- Mirco Ravanelli, Yoshua Bengio, "Speaker Recognition from raw waveform with SincNet". https://arxiv.org/abs/1808.00158 """ @staticmethod def to_mel(hz): return 2595 * np.log10(1 + hz / 700) @staticmethod def to_hz(mel): return 700 * (10 ** (mel / 2595) - 1) def __init__( self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, bias=False, groups=1, sample_rate=16000, min_low_hz=50, min_band_hz=50, ): super(SincConv_fast, self).__init__() if in_channels != 1: # msg = (f'SincConv only support one input channel ' # f'(here, in_channels = {in_channels:d}).') msg = "SincConv only support one input channel (here, in_channels = {%i})" % (in_channels) raise ValueError(msg) self.out_channels = out_channels self.kernel_size = kernel_size # Forcing the filters to be odd (i.e, perfectly symmetrics) if kernel_size % 2 == 0: self.kernel_size = self.kernel_size + 1 self.stride = stride self.padding = padding self.dilation = dilation if bias: raise ValueError("SincConv does not support bias.") if groups > 1: raise ValueError("SincConv does not support groups.") self.sample_rate = sample_rate self.min_low_hz = min_low_hz self.min_band_hz = min_band_hz # initialize filterbanks such that they are equally spaced in Mel scale low_hz = 30 high_hz = self.sample_rate / 2 - (self.min_low_hz + self.min_band_hz) mel = np.linspace(self.to_mel(low_hz), self.to_mel(high_hz), self.out_channels + 1) hz = self.to_hz(mel) # filter lower frequency (out_channels, 1) self.low_hz_ = nn.Parameter(torch.Tensor(hz[:-1]).view(-1, 1)) # filter frequency band (out_channels, 1) self.band_hz_ = nn.Parameter(torch.Tensor(np.diff(hz)).view(-1, 1)) # Hamming window # self.window_ = torch.hamming_window(self.kernel_size) n_lin = torch.linspace( 0, (self.kernel_size / 2) - 1, steps=int((self.kernel_size / 2)) ) # computing only half of the window self.window_ = 0.54 - 0.46 * torch.cos(2 * math.pi * n_lin / self.kernel_size) # (kernel_size, 1) n = (self.kernel_size - 1) / 2.0 self.n_ = ( 2 * math.pi * torch.arange(-n, 0).view(1, -1) / self.sample_rate ) # Due to symmetry, I only need half of the time axes def forward(self, waveforms): """ Parameters ---------- waveforms : `torch.Tensor` (batch_size, 1, n_samples) Batch of waveforms. Returns ------- features : `torch.Tensor` (batch_size, out_channels, n_samples_out) Batch of sinc filters activations. """ self.n_ = self.n_.to(waveforms.device) self.window_ = self.window_.to(waveforms.device) low = self.min_low_hz + torch.abs(self.low_hz_) high = torch.clamp(low + self.min_band_hz + torch.abs(self.band_hz_), self.min_low_hz, self.sample_rate / 2) band = (high - low)[:, 0] f_times_t_low = torch.matmul(low, self.n_) f_times_t_high = torch.matmul(high, self.n_) band_pass_left = ( (torch.sin(f_times_t_high) - torch.sin(f_times_t_low)) / (self.n_ / 2) ) * self.window_ # Equivalent of Eq.4 of the reference paper (SPEAKER RECOGNITION FROM RAW WAVEFORM WITH SINCNET). I just have expanded the sinc and simplified the terms. This way I avoid several useless computations. band_pass_center = 2 * band.view(-1, 1) band_pass_right = torch.flip(band_pass_left, dims=[1]) band_pass = torch.cat([band_pass_left, band_pass_center, band_pass_right], dim=1) band_pass = band_pass / (2 * band[:, None]) self.filters = (band_pass).view(self.out_channels, 1, self.kernel_size) return F.conv1d( waveforms, self.filters, stride=self.stride, padding=self.padding, dilation=self.dilation, bias=None, groups=1, ) def flip(x, dim): xsize = x.size() dim = x.dim() + dim if dim < 0 else dim x = x.contiguous() x = x.view(-1, *xsize[dim:]) x = x.view(x.size(0), x.size(1), -1)[ :, getattr(torch.arange(x.size(1) - 1, -1, -1), ("cpu", "cuda")[x.is_cuda])().long(), : ] return x.view(xsize) class SRU(nn.Module): def __init__(self, options, inp_dim): super(SRU, self).__init__() self.input_dim = inp_dim self.hidden_size = int(options["sru_hidden_size"]) self.num_layers = int(options["sru_num_layers"]) self.dropout = float(options["sru_dropout"]) self.rnn_dropout = float(options["sru_rnn_dropout"]) self.use_tanh = bool(strtobool(options["sru_use_tanh"])) self.use_relu = bool(strtobool(options["sru_use_relu"])) self.use_selu = bool(strtobool(options["sru_use_selu"])) self.weight_norm = bool(strtobool(options["sru_weight_norm"])) self.layer_norm = bool(strtobool(options["sru_layer_norm"])) self.bidirectional = bool(strtobool(options["sru_bidirectional"])) self.is_input_normalized = bool(strtobool(options["sru_is_input_normalized"])) self.has_skip_term = bool(strtobool(options["sru_has_skip_term"])) self.rescale = bool(strtobool(options["sru_rescale"])) self.highway_bias = float(options["sru_highway_bias"]) self.n_proj = int(options["sru_n_proj"]) self.sru = sru.SRU( self.input_dim, self.hidden_size, num_layers=self.num_layers, dropout=self.dropout, rnn_dropout=self.rnn_dropout, bidirectional=self.bidirectional, n_proj=self.n_proj, use_tanh=self.use_tanh, use_selu=self.use_selu, use_relu=self.use_relu, weight_norm=self.weight_norm, layer_norm=self.layer_norm, has_skip_term=self.has_skip_term, is_input_normalized=self.is_input_normalized, highway_bias=self.highway_bias, rescale=self.rescale, ) self.out_dim = self.hidden_size + self.bidirectional * self.hidden_size def forward(self, x): if self.bidirectional: h0 = torch.zeros(self.num_layers, x.shape[1], self.hidden_size * 2) else: h0 = torch.zeros(self.num_layers, x.shape[1], self.hidden_size) if x.is_cuda: h0 = h0.cuda() output, hn = self.sru(x, c0=h0) return output class PASE(nn.Module): def __init__(self, options, inp_dim): super(PASE, self).__init__() # To use PASE within PyTorch-Kaldi, please clone the current PASE repository: https://github.com/santi-pdp/pase # Note that you have to clone the dev branch. # Take a look into the requirements (requirements.txt) and install in your environment what is missing. An important requirement is QRNN (https://github.com/salesforce/pytorch-qrnn). # Before starting working with PASE, it could make sense to a quick test with QRNN independently (see “usage” section in the QRNN repository). # Remember to install pase. This way it can be used outside the pase folder directory. To do it, go into the pase folder and type: # "python setup.py install" from pase.models.frontend import wf_builder self.input_dim = inp_dim self.pase_cfg = options["pase_cfg"] self.pase_model = options["pase_model"] self.pase = wf_builder(self.pase_cfg) self.pase.load_pretrained(self.pase_model, load_last=True, verbose=True) # Reading the out_dim from the config file: with open(self.pase_cfg) as json_file: config = json.load(json_file) self.out_dim = int(config["emb_dim"]) def forward(self, x): x = x.unsqueeze(0).unsqueeze(0) output = self.pase(x) return output class FusionLinearConv(nn.Module): r"""Applies a FusionLayer as described in: 'FusionRNN: Shared Neural Parameters for Multi-Channel Distant Speech Recognition', Titouan P. et Al. Input channels are supposed to be concatenated along the last dimension """ def __init__(self, in_features, out_features, number_of_mic=1, bias=True,seed=None,act="leaky",reduce="sum"): super(FusionLinearConv, self).__init__() self.in_features = in_features // number_of_mic self.out_features = out_features self.number_of_mic = number_of_mic self.reduce = reduce if act == "leaky_relu": self.act_function = nn.LeakyReLU() elif act == "prelu": self.act_function = nn.PReLU() elif act == "relu": self.act_function = nn.ReLU() else: self.act_function = nn.Tanh() self.conv = nn.Conv1d(1, self.out_features, kernel_size=self.in_features, stride=self.in_features, bias=True, padding=0) self.conv.bias.data.fill_(0) torch.nn.init.xavier_normal_(self.conv.weight.data) def forward(self, input): orig_shape = input.shape out = self.act_function(self.conv(input.view(orig_shape[0]*orig_shape[1], 1, -1))) if self.reduce == "mean": out = torch.mean(out, dim=-1) else: out = torch.sum(out, dim=-1) return out.view(orig_shape[0],orig_shape[1], -1)
73,602
34.049048
226
py
pytorch-kaldi-gan
pytorch-kaldi-gan-master/multistyle_training.py
from augmentation_utils import * import configparser import sox import logging logging.getLogger('sox').setLevel(logging.ERROR) # Reading global cfg file (first argument-mandatory file) cfg_file = sys.argv[1] if not (os.path.exists(cfg_file)): sys.stderr.write("ERROR: The config file %s does not exist!\n" % (cfg_file)) sys.exit(0) else: config = configparser.ConfigParser() config.read(cfg_file) # Output folder creation out_folder = config["data"]["out_folder"] if not os.path.exists(out_folder): os.makedirs(out_folder) data_folder = config["data"]["data_folder"] # Read cfg file options snr_array = np.array(list(map(int, config["impulse"]["snrs"].split(",")))) snr_list = 10 ** (snr_array / 10) print("- Reading config file......OK!") if config["data"]["dataset"] == "librispeech": speaker_lst = os.listdir(data_folder) speaker_lst = validate_dir(speaker_lst) # Create parallel dataset print("\n- Starting dataset parallelization.\n") speaker_count = 1 for speaker in speaker_lst: print(" Speaker {} / {} ".format(speaker_count, len(speaker_lst)).center(40, "=")) speaker_count += 1 speaker_dir = os.path.join(data_folder, speaker) # Get chapters by speaker chapter_lst = os.listdir(speaker_dir) chapter_lst = validate_dir(chapter_lst) chapter_count = 1 for chap in chapter_lst: print("Chapter {} / {} \r".format(chapter_count, len(chapter_lst)), end = '') chapter_count += 1 chapter_dir = os.path.join(speaker_dir, chap) # Get utterances by speaker per chapter utterance_lst = os.listdir(chapter_dir) utt_transcripitons, utterance_lst = get_utterances(utterance_lst) output_dir = os.path.join(out_folder, speaker, chap) if not os.path.exists(output_dir): os.makedirs(output_dir) transcription_from_dir = os.path.join(chapter_dir, utt_transcripitons) transcription_to_dir = os.path.join(output_dir, utt_transcripitons) shutil.copyfile(transcription_from_dir, transcription_to_dir) for utt in utterance_lst: utterance_dir = os.path.join(chapter_dir, utt) utt_save_dir = os.path.join(output_dir, utt) if config["styles"]["change_speed"] == "True": random_number = random.randint(0, 1) if random_number == 1: vol_fraction = 1 + float(config["impulse"]["volume_change"]) else: vol_fraction = 1 - float(config["impulse"]["volume_change"]) else: vol_fraction = 1 if config["styles"]["change_volume"] == "True": random_number = random.randint(0, 1) if random_number == 1: speed_fraction = 1 + float(config["impulse"]["speed_change"]) else: speed_fraction = 1 - float(config["impulse"]["speed_change"]) else: speed_fraction = 1 if config["styles"]["change_speed"] == "True" or config["styles"]["change_volume"] == "True": # create a transformer tfm = sox.Transformer() tfm.tempo(speed_fraction, 's') tfm.vol(vol_fraction) tfm.build_file( input_filepath = utterance_dir, sample_rate_in = int(config["impulse"]["sample_rate"]), output_filepath = utt_save_dir ) if config["styles"]["add_impulse"] == "True": recording, sample_rate = torchaudio.load(utt_save_dir) noise = get_random_noise_file(config["impulse"]["impulse_dir"]) recording = normalize_tensor(recording) random_snr_value = random.randrange(len(snr_list)) recording = convolve_impulse(recording[0], noise[0], snr_list[random_snr_value]) recording = normalize_tensor(recording) torchaudio.save(utt_save_dir, recording, sample_rate = sample_rate) cmd = "kaldi_decoding_scripts/create_parallel_dataset.sh " \ + os.path.basename(config["data"]["out_folder"]) + " " \ + os.path.dirname(config["data"]["root_folder"]) invoke_process_popen_poll_live(cmd) print("\n\nDataset created successfully\n")
4,581
34.796875
111
py
pytorch-kaldi-gan
pytorch-kaldi-gan-master/utils.py
########################################################## # pytorch-kaldi-gan # Walter Heymans # North West University # 2020 # Adapted from: # pytorch-kaldi v.0.1 # Mirco Ravanelli, Titouan Parcollet # Mila, University of Montreal # October 2018 ########################################################## import configparser import sys import os.path import random import subprocess import numpy as np import re import glob from distutils.util import strtobool import importlib import torch import torch.nn as nn import torch.optim as optim import math import matplotlib.pyplot as plt import weights_and_biases as wandb import math from torch.optim.optimizer import Optimizer def run_command(cmd): """from http://blog.kagesenshi.org/2008/02/teeing-python-subprocesspopen-output.html """ p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) stdout = [] while True: line = p.stdout.readline() stdout.append(line) print(line.decode("utf-8")) if line == "" and p.poll() != None: break return "".join(stdout) def run_shell_display(cmd): p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) while True: out = p.stdout.read(1).decode("utf-8") if out == "" and p.poll() != None: break if out != "": sys.stdout.write(out) sys.stdout.flush() return def run_shell(cmd, log_file): p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) (output, err) = p.communicate() p.wait() with open(log_file, "a+") as logfile: logfile.write(output.decode("utf-8") + "\n") logfile.write(err.decode("utf-8") + "\n") # print(output.decode("utf-8")) return output def read_args_command_line(args, config): sections = [] fields = [] values = [] for i in range(2, len(args)): # check if the option is valid for second level r2 = re.compile("--.*,.*=.*") # check if the option is valid for 4 level r4 = re.compile('--.*,.*,.*,.*=".*"') if r2.match(args[i]) is None and r4.match(args[i]) is None: sys.stderr.write( 'ERROR: option "%s" from command line is not valid! (the format must be "--section,field=value")\n' % (args[i]) ) sys.exit(0) sections.append(re.search("--(.*),", args[i]).group(1)) fields.append(re.search(",(.*)", args[i].split("=")[0]).group(1)) values.append(re.search("=(.*)", args[i]).group(1)) # parsing command line arguments for i in range(len(sections)): # Remove multi level is level >= 2 sections[i] = sections[i].split(",")[0] if sections[i] in config.sections(): # Case of args level > than 2 like --sec,fields,0,field="value" if len(fields[i].split(",")) >= 2: splitted = fields[i].split(",") # Get the actual fields field = splitted[0] number = int(splitted[1]) f_name = splitted[2] if field in list(config[sections[i]]): # Get the current string of the corresponding field current_config_field = config[sections[i]][field] # Count the number of occurence of the required field matching = re.findall(f_name + ".", current_config_field) if number >= len(matching): sys.stderr.write( 'ERROR: the field number "%s" provided from command line is not valid, we found "%s" "%s" field(s) in section "%s"!\n' % (number, len(matching), f_name, field) ) sys.exit(0) else: # Now replace str_to_be_replaced = re.findall(f_name + ".*", current_config_field)[number] new_str = str(f_name + "=" + values[i]) replaced = nth_replace_string(current_config_field, str_to_be_replaced, new_str, number + 1) config[sections[i]][field] = replaced else: sys.stderr.write( 'ERROR: field "%s" of section "%s" from command line is not valid!")\n' % (field, sections[i]) ) sys.exit(0) else: if fields[i] in list(config[sections[i]]): config[sections[i]][fields[i]] = values[i] else: sys.stderr.write( 'ERROR: field "%s" of section "%s" from command line is not valid!")\n' % (fields[i], sections[i]) ) sys.exit(0) else: sys.stderr.write('ERROR: section "%s" from command line is not valid!")\n' % (sections[i])) sys.exit(0) return [sections, fields, values] def compute_avg_performance(info_lst): losses = [] errors = [] times = [] for tr_info_file in info_lst: config_res = configparser.ConfigParser() config_res.read(tr_info_file) losses.append(float(config_res["results"]["loss"])) errors.append(float(config_res["results"]["err"])) times.append(float(config_res["results"]["elapsed_time_chunk"])) loss = np.mean(losses) error = np.mean(errors) time = np.sum(times) return [loss, error, time] def check_field(inp, type_inp, field): valid_field = True if inp == "" and field != "cmd": sys.stderr.write('ERROR: The the field "%s" of the config file is empty! \n' % (field)) valid_field = False sys.exit(0) if type_inp == "path": if not (os.path.isfile(inp)) and not (os.path.isdir(inp)) and inp != "none": sys.stderr.write( 'ERROR: The path "%s" specified in the field "%s" of the config file does not exists! \n' % (inp, field) ) valid_field = False sys.exit(0) if "{" and "}" in type_inp: arg_list = type_inp[1:-1].split(",") if inp not in arg_list: sys.stderr.write('ERROR: The field "%s" can only contain %s arguments \n' % (field, arg_list)) valid_field = False sys.exit(0) if "int(" in type_inp: try: int(inp) except ValueError: sys.stderr.write('ERROR: The field "%s" can only contain an integer (got "%s") \n' % (field, inp)) valid_field = False sys.exit(0) # Check if the value if within the expected range lower_bound = type_inp.split(",")[0][4:] upper_bound = type_inp.split(",")[1][:-1] if lower_bound != "-inf": if int(inp) < int(lower_bound): sys.stderr.write( 'ERROR: The field "%s" can only contain an integer greater than %s (got "%s") \n' % (field, lower_bound, inp) ) valid_field = False sys.exit(0) if upper_bound != "inf": if int(inp) > int(upper_bound): sys.stderr.write( 'ERROR: The field "%s" can only contain an integer smaller than %s (got "%s") \n' % (field, upper_bound, inp) ) valid_field = False sys.exit(0) if "float(" in type_inp: try: float(inp) except ValueError: sys.stderr.write('ERROR: The field "%s" can only contain a float (got "%s") \n' % (field, inp)) valid_field = False sys.exit(0) # Check if the value if within the expected range lower_bound = type_inp.split(",")[0][6:] upper_bound = type_inp.split(",")[1][:-1] if lower_bound != "-inf": if float(inp) < float(lower_bound): sys.stderr.write( 'ERROR: The field "%s" can only contain a float greater than %s (got "%s") \n' % (field, lower_bound, inp) ) valid_field = False sys.exit(0) if upper_bound != "inf": if float(inp) > float(upper_bound): sys.stderr.write( 'ERROR: The field "%s" can only contain a float smaller than %s (got "%s") \n' % (field, upper_bound, inp) ) valid_field = False sys.exit(0) if type_inp == "bool": lst = {"True", "true", "1", "False", "false", "0"} if not (inp in lst): sys.stderr.write('ERROR: The field "%s" can only contain a boolean (got "%s") \n' % (field, inp)) valid_field = False sys.exit(0) if "int_list(" in type_inp: lst = inp.split(",") try: list(map(int, lst)) except ValueError: sys.stderr.write( 'ERROR: The field "%s" can only contain a list of integer (got "%s"). Make also sure there aren\'t white spaces between commas.\n' % (field, inp) ) valid_field = False sys.exit(0) # Check if the value if within the expected range lower_bound = type_inp.split(",")[0][9:] upper_bound = type_inp.split(",")[1][:-1] for elem in lst: if lower_bound != "-inf": if int(elem) < int(lower_bound): sys.stderr.write( 'ERROR: The field "%s" can only contain an integer greater than %s (got "%s") \n' % (field, lower_bound, elem) ) valid_field = False sys.exit(0) if upper_bound != "inf": if int(elem) > int(upper_bound): sys.stderr.write( 'ERROR: The field "%s" can only contain an integer smaller than %s (got "%s") \n' % (field, upper_bound, elem) ) valid_field = False sys.exit(0) if "float_list(" in type_inp: lst = inp.split(",") try: list(map(float, lst)) except ValueError: sys.stderr.write( 'ERROR: The field "%s" can only contain a list of floats (got "%s"). Make also sure there aren\'t white spaces between commas. \n' % (field, inp) ) valid_field = False sys.exit(0) # Check if the value if within the expected range lower_bound = type_inp.split(",")[0][11:] upper_bound = type_inp.split(",")[1][:-1] for elem in lst: if lower_bound != "-inf": if float(elem) < float(lower_bound): sys.stderr.write( 'ERROR: The field "%s" can only contain a float greater than %s (got "%s") \n' % (field, lower_bound, elem) ) valid_field = False sys.exit(0) if upper_bound != "inf": if float(elem) > float(upper_bound): sys.stderr.write( 'ERROR: The field "%s" can only contain a float smaller than %s (got "%s") \n' % (field, upper_bound, elem) ) valid_field = False sys.exit(0) if type_inp == "bool_list": lst = {"True", "true", "1", "False", "false", "0"} inps = inp.split(",") for elem in inps: if not (elem in lst): sys.stderr.write( 'ERROR: The field "%s" can only contain a list of boolean (got "%s"). Make also sure there aren\'t white spaces between commas.\n' % (field, inp) ) valid_field = False sys.exit(0) return valid_field def get_all_archs(config): arch_lst = [] for sec in config.sections(): if "architecture" in sec: arch_lst.append(sec) return arch_lst def expand_section(config_proto, config): # expands config_proto with fields in prototype files name_data = [] name_arch = [] for sec in config.sections(): if "dataset" in sec: config_proto.add_section(sec) config_proto[sec] = config_proto["dataset"] name_data.append(config[sec]["data_name"]) if "architecture" in sec: name_arch.append(config[sec]["arch_name"]) config_proto.add_section(sec) config_proto[sec] = config_proto["architecture"] proto_file = config[sec]["arch_proto"] # Reading proto file (architecture) config_arch = configparser.ConfigParser() config_arch.read(proto_file) # Reading proto options fields_arch = list(dict(config_arch.items("proto")).keys()) fields_arch_type = list(dict(config_arch.items("proto")).values()) for i in range(len(fields_arch)): config_proto.set(sec, fields_arch[i], fields_arch_type[i]) # Reading proto file (architecture_optimizer) opt_type = config[sec]["arch_opt"] if opt_type == "sgd": proto_file = "proto/sgd.proto" if opt_type == "rmsprop": proto_file = "proto/rmsprop.proto" if opt_type == "adam": proto_file = "proto/adam.proto" config_arch = configparser.ConfigParser() config_arch.read(proto_file) # Reading proto options fields_arch = list(dict(config_arch.items("proto")).keys()) fields_arch_type = list(dict(config_arch.items("proto")).values()) for i in range(len(fields_arch)): config_proto.set(sec, fields_arch[i], fields_arch_type[i]) config_proto.remove_section("dataset") config_proto.remove_section("architecture") return [config_proto, name_data, name_arch] def expand_section_proto(config_proto, config): # Read config proto file config_proto_optim_file = config["optimization"]["opt_proto"] config_proto_optim = configparser.ConfigParser() config_proto_optim.read(config_proto_optim_file) for optim_par in list(config_proto_optim["proto"]): config_proto.set("optimization", optim_par, config_proto_optim["proto"][optim_par]) def check_cfg_fields(config_proto, config, cfg_file): # Check mandatory sections and fields sec_parse = True for sec in config_proto.sections(): if any(sec in s for s in config.sections()): # Check fields for field in list(dict(config_proto.items(sec)).keys()): if not (field in config[sec]): sys.stderr.write( 'ERROR: The confg file %s does not contain the field "%s=" in section "[%s]" (mandatory)!\n' % (cfg_file, field, sec) ) sec_parse = False else: field_type = config_proto[sec][field] if not (check_field(config[sec][field], field_type, field)): sec_parse = False # If a mandatory section doesn't exist... else: sys.stderr.write( 'ERROR: The confg file %s does not contain "[%s]" section (mandatory)!\n' % (cfg_file, sec) ) sec_parse = False if sec_parse == False: sys.stderr.write("ERROR: Revise the confg file %s \n" % (cfg_file)) sys.exit(0) return sec_parse def check_consistency_with_proto(cfg_file, cfg_file_proto): sec_parse = True # Check if cfg file exists try: open(cfg_file, "r") except IOError: sys.stderr.write("ERROR: The confg file %s does not exist!\n" % (cfg_file)) sys.exit(0) # Check if cfg proto file exists try: open(cfg_file_proto, "r") except IOError: sys.stderr.write("ERROR: The confg file %s does not exist!\n" % (cfg_file_proto)) sys.exit(0) # Parser Initialization config = configparser.ConfigParser() # Reading the cfg file config.read(cfg_file) # Reading proto cfg file config_proto = configparser.ConfigParser() config_proto.read(cfg_file_proto) # Adding the multiple entries in data and architecture sections [config_proto, name_data, name_arch] = expand_section(config_proto, config) # Check mandatory sections and fields sec_parse = check_cfg_fields(config_proto, config, cfg_file) if sec_parse == False: sys.exit(0) return [config_proto, name_data, name_arch] def check_cfg(cfg_file, config, cfg_file_proto): # Check consistency between cfg_file and cfg_file_proto [config_proto, name_data, name_arch] = check_consistency_with_proto(cfg_file, cfg_file_proto) # Reload data_name because they might be altered by arguments name_data = [] for sec in config.sections(): if "dataset" in sec: name_data.append(config[sec]["data_name"]) # check consistency between [data_use] vs [data*] sec_parse = True data_use_with = [] for data in list(dict(config.items("data_use")).values()): data_use_with.append(data.split(",")) data_use_with = sum(data_use_with, []) if not (set(data_use_with).issubset(name_data)): sys.stderr.write("ERROR: in [data_use] you are using a dataset not specified in [dataset*] %s \n" % (cfg_file)) sec_parse = False sys.exit(0) # Set to false the first layer norm layer if the architecture is sequential (to avoid numerical instabilities) seq_model = False for sec in config.sections(): if "architecture" in sec: if strtobool(config[sec]["arch_seq_model"]): seq_model = True break if seq_model: for item in list(config["architecture1"].items()): if "use_laynorm" in item[0] and "_inp" not in item[0]: ln_list = item[1].split(",") if ln_list[0] == "True": ln_list[0] = "False" config["architecture1"][item[0]] = ",".join(ln_list) # Production case (We don't have the alignement for the forward_with), by default the prod # Flag is set to False, and the dataset prod number to 1, corresponding to no prod dataset config["exp"]["production"] = str("False") prod_dataset_number = "dataset1" for data in name_data: [lab_names, _, _] = parse_lab_field(config[cfg_item2sec(config, "data_name", data)]["lab"]) if "none" in lab_names and data == config["data_use"]["forward_with"]: config["exp"]["production"] = str("True") prod_data_name = data for sec in config.sections(): if "dataset" in sec: if config[sec]["data_name"] == data: prod_dataset_number = sec else: continue # If production case is detected, remove all the other datasets except production if config["exp"]["production"] == str("True"): name_data = [elem for elem in name_data if elem == prod_data_name] # Parse fea and lab fields in datasets* cnt = 0 fea_names_lst = [] lab_names_lst = [] for data in name_data: [lab_names, _, _] = parse_lab_field(config[cfg_item2sec(config, "data_name", data)]["lab"]) if "none" in lab_names: continue [fea_names, fea_lsts, fea_opts, cws_left, cws_right] = parse_fea_field( config[cfg_item2sec(config, "data_name", data)]["fea"] ) [lab_names, lab_folders, lab_opts] = parse_lab_field(config[cfg_item2sec(config, "data_name", data)]["lab"]) fea_names_lst.append(sorted(fea_names)) lab_names_lst.append(sorted(lab_names)) # Check that fea_name doesn't contain special characters for name_features in fea_names_lst[cnt]: if not (re.match("^[a-zA-Z0-9]*$", name_features)): sys.stderr.write( 'ERROR: features names (fea_name=) must contain only letters or numbers (no special characters as "_,$,..") \n' ) sec_parse = False sys.exit(0) if cnt > 0: if fea_names_lst[cnt - 1] != fea_names_lst[cnt]: sys.stderr.write("ERROR: features name (fea_name) must be the same of all the datasets! \n") sec_parse = False sys.exit(0) if lab_names_lst[cnt - 1] != lab_names_lst[cnt]: sys.stderr.write("ERROR: labels name (lab_name) must be the same of all the datasets! \n") sec_parse = False sys.exit(0) cnt = cnt + 1 # Create the output folder out_folder = config["exp"]["out_folder"] if not os.path.exists(out_folder) or not (os.path.exists(out_folder + "/exp_files")): os.makedirs(out_folder + "/exp_files") # Parsing forward field model = config["model"]["model"] possible_outs = list(re.findall("(.*)=", model.replace(" ", ""))) forward_out_lst = config["forward"]["forward_out"].split(",") forward_norm_lst = config["forward"]["normalize_with_counts_from"].split(",") forward_norm_bool_lst = config["forward"]["normalize_posteriors"].split(",") lab_lst = list(re.findall("lab_name=(.*)\n", config[prod_dataset_number]["lab"].replace(" ", ""))) lab_folders = list(re.findall("lab_folder=(.*)\n", config[prod_dataset_number]["lab"].replace(" ", ""))) N_out_lab = ["none"] * len(lab_lst) if config["exp"]["production"] == str("False"): for i in range(len(lab_opts)): # Compute number of monophones if needed if "ali-to-phones" in lab_opts[i]: log_file = config["exp"]["out_folder"] + "/log.log" folder_lab_count = lab_folders[i] cmd = "hmm-info " + folder_lab_count + "/final.mdl | awk '/phones/{print $4}'" output = run_shell(cmd, log_file) if output.decode().rstrip() == "": sys.stderr.write( "ERROR: hmm-info command doesn't exist. Make sure your .bashrc contains the Kaldi paths and correctly exports it.\n" ) sys.exit(0) N_out = int(output.decode().rstrip()) N_out_lab[i] = N_out for i in range(len(forward_out_lst)): if forward_out_lst[i] not in possible_outs: sys.stderr.write( 'ERROR: the output "%s" in the section "forward_out" is not defined in section model)\n' % (forward_out_lst[i]) ) sys.exit(0) if strtobool(forward_norm_bool_lst[i]): if forward_norm_lst[i] not in lab_lst: if not os.path.exists(forward_norm_lst[i]): sys.stderr.write( 'ERROR: the count_file "%s" in the section "forward_out" does not exist)\n' % (forward_norm_lst[i]) ) sys.exit(0) else: # Check if the specified file is in the right format f = open(forward_norm_lst[i], "r") cnts = f.read() if not (bool(re.match("(.*)\[(.*)\]", cnts))): sys.stderr.write( 'ERROR: the count_file "%s" in the section "forward_out" not in the right format)\n' % (forward_norm_lst[i]) ) else: # Try to automatically retrieve the count file from the config file # Compute the number of context-dependent phone states if "ali-to-pdf" in lab_opts[lab_lst.index(forward_norm_lst[i])]: log_file = config["exp"]["out_folder"] + "/log.log" folder_lab_count = lab_folders[lab_lst.index(forward_norm_lst[i])] cmd = "hmm-info " + folder_lab_count + "/final.mdl | awk '/pdfs/{print $4}'" output = run_shell(cmd, log_file) if output.decode().rstrip() == "": sys.stderr.write( "ERROR: hmm-info command doesn't exist. Make sure your .bashrc contains the Kaldi paths and correctly exports it.\n" ) sys.exit(0) N_out = int(output.decode().rstrip()) N_out_lab[lab_lst.index(forward_norm_lst[i])] = N_out count_file_path = ( out_folder + "/exp_files/forward_" + forward_out_lst[i] + "_" + forward_norm_lst[i] + ".count" ) cmd = ( "analyze-counts --print-args=False --verbose=0 --binary=false --counts-dim=" + str(N_out) + ' "ark:ali-to-pdf ' + folder_lab_count + '/final.mdl \\"ark:gunzip -c ' + folder_lab_count + '/ali.*.gz |\\" ark:- |" ' + count_file_path ) run_shell(cmd, log_file) forward_norm_lst[i] = count_file_path else: sys.stderr.write( 'ERROR: Not able to automatically retrieve count file for the label "%s". Please add a valid count file path in "normalize_with_counts_from" or set normalize_posteriors=False \n' % (forward_norm_lst[i]) ) sys.exit(0) # Update the config file with the count_file paths config["forward"]["normalize_with_counts_from"] = ",".join(forward_norm_lst) # When possible replace the pattern "N_out_lab*" with the detected number of output for sec in config.sections(): for field in list(config[sec]): for i in range(len(lab_lst)): pattern = "N_out_" + lab_lst[i] if pattern in config[sec][field]: if N_out_lab[i] != "none": config[sec][field] = config[sec][field].replace(pattern, str(N_out_lab[i])) else: sys.stderr.write( "ERROR: Cannot automatically retrieve the number of output in %s. Please, add manually the number of outputs \n" % (pattern) ) sys.exit(0) # Check the model field parse_model_field(cfg_file) # Create block diagram picture of the model create_block_diagram(cfg_file) if sec_parse == False: sys.exit(0) return [config, name_data, name_arch] def cfg_item2sec(config, field, value): for sec in config.sections(): if field in list(dict(config.items(sec)).keys()): if value in list(dict(config.items(sec)).values()): return sec sys.stderr.write("ERROR: %s=%s not found in config file \n" % (field, value)) sys.exit(0) return -1 def split_chunks(seq, size): newseq = [] splitsize = 1.0 / size * len(seq) for i in range(size): newseq.append(seq[int(round(i * splitsize)) : int(round((i + 1) * splitsize))]) return newseq def get_chunks_after_which_to_validate(N_ck_tr, nr_of_valid_per_epoch): def _partition_chunks(N_ck_tr, nr_of_valid_per_epoch): chunk_part = list() chunk_size = int(np.ceil(N_ck_tr / float(nr_of_valid_per_epoch))) for i1 in range(nr_of_valid_per_epoch): chunk_part.append(range(0, N_ck_tr)[i1 * chunk_size : (i1 + 1) * chunk_size]) return chunk_part part_chunk_ids = _partition_chunks(N_ck_tr, nr_of_valid_per_epoch) chunk_ids = list() for l in part_chunk_ids: chunk_ids.append(l[-1]) return chunk_ids def do_validation_after_chunk(ck, N_ck_tr, config): def _get_nr_of_valid_per_epoch_from_config(config): if not "nr_of_valid_per_epoch" in config["exp"]: return 1 return int(config["exp"]["nr_of_valid_per_epoch"]) nr_of_valid_per_epoch = _get_nr_of_valid_per_epoch_from_config(config) valid_chunks = get_chunks_after_which_to_validate(N_ck_tr, nr_of_valid_per_epoch) if ck in valid_chunks: return True else: return False def _get_val_file_name_base(dataset, ep, ck, ck_val, N_ep_str_format, N_ck_str_format, N_ck_str_format_val): file_name = "valid_" + dataset + "_ep" + format(ep, N_ep_str_format) + "_trCk" + format(ck, N_ck_str_format) if ck_val is None: file_name += "*" else: file_name += "_ck" + format(ck_val, N_ck_str_format_val) return file_name def get_val_lst_file_path( out_folder, valid_data, ep, ck, ck_val, fea_name, N_ep_str_format, N_ck_str_format, N_ck_str_format_val ): def _get_val_lst_file_name( dataset, ep, ck, ck_val, fea_name, N_ep_str_format, N_ck_str_format, N_ck_str_format_val ): file_name = _get_val_file_name_base( dataset, ep, ck, ck_val, N_ep_str_format, N_ck_str_format, N_ck_str_format_val ) file_name += "_" if not fea_name is None: file_name += fea_name else: file_name += "*" file_name += ".lst" return file_name lst_file_name = _get_val_lst_file_name( valid_data, ep, ck, ck_val, fea_name, N_ep_str_format, N_ck_str_format, N_ck_str_format_val ) lst_file = out_folder + "/exp_files/" + lst_file_name return lst_file def get_val_info_file_path( out_folder, valid_data, ep, ck, ck_val, N_ep_str_format, N_ck_str_format, N_ck_str_format_val ): def _get_val_info_file_name(dataset, ep, ck, ck_val, N_ep_str_format, N_ck_str_format, N_ck_str_format_val): file_name = _get_val_file_name_base( dataset, ep, ck, ck_val, N_ep_str_format, N_ck_str_format, N_ck_str_format_val ) file_name += ".info" return file_name info_file_name = _get_val_info_file_name( valid_data, ep, ck, ck_val, N_ep_str_format, N_ck_str_format, N_ck_str_format_val ) info_file = out_folder + "/exp_files/" + info_file_name return info_file def get_val_cfg_file_path( out_folder, valid_data, ep, ck, ck_val, N_ep_str_format, N_ck_str_format, N_ck_str_format_val ): def _get_val_cfg_file_name(dataset, ep, ck, ck_val, N_ep_str_format, N_ck_str_format, N_ck_str_format_val): file_name = _get_val_file_name_base( dataset, ep, ck, ck_val, N_ep_str_format, N_ck_str_format, N_ck_str_format_val ) file_name += ".cfg" return file_name cfg_file_name = _get_val_cfg_file_name( valid_data, ep, ck, ck_val, N_ep_str_format, N_ck_str_format, N_ck_str_format_val ) config_chunk_file = out_folder + "/exp_files/" + cfg_file_name return config_chunk_file def create_configs(config): # This function create the chunk-specific config files cfg_file_proto_chunk = config["cfg_proto"]["cfg_proto_chunk"] N_ep = int(config["exp"]["N_epochs_tr"]) N_ep_str_format = "0" + str(max(math.ceil(np.log10(N_ep)), 1)) + "d" tr_data_lst = config["data_use"]["train_with"].split(",") valid_data_lst = config["data_use"]["valid_with"].split(",") max_seq_length_train = config["batches"]["max_seq_length_train"] forward_data_lst = config["data_use"]["forward_with"].split(",") is_production = strtobool(config["exp"]["production"]) out_folder = config["exp"]["out_folder"] cfg_file = out_folder + "/conf.cfg" chunk_lst = out_folder + "/exp_files/list_chunks.txt" lst_chunk_file = open(chunk_lst, "w") # Read the batch size string batch_size_tr_str = config["batches"]["batch_size_train"] batch_size_tr_arr = expand_str_ep(batch_size_tr_str, "int", N_ep, "|", "*") # Read the max_seq_length_train if len(max_seq_length_train.split(",")) == 1: max_seq_length_tr_arr = expand_str_ep(max_seq_length_train, "int", N_ep, "|", "*") else: max_seq_length_tr_arr = [max_seq_length_train] * N_ep cfg_file_proto = config["cfg_proto"]["cfg_proto"] [config, name_data, name_arch] = check_cfg(cfg_file, config, cfg_file_proto) arch_lst = get_all_archs(config) lr = {} improvement_threshold = {} halving_factor = {} pt_files = {} drop_rates = {} for arch in arch_lst: lr_arr = expand_str_ep(config[arch]["arch_lr"], "float", N_ep, "|", "*") lr[arch] = lr_arr improvement_threshold[arch] = float(config[arch]["arch_improvement_threshold"]) halving_factor[arch] = float(config[arch]["arch_halving_factor"]) pt_files[arch] = config[arch]["arch_pretrain_file"] # Loop over all the sections and look for a "_drop" field (to perform dropout scheduling for (field_key, field_val) in config.items(arch): if "_drop" in field_key: drop_lay = field_val.split(",") N_lay = len(drop_lay) drop_rates[arch] = [] for lay_id in range(N_lay): drop_rates[arch].append(expand_str_ep(drop_lay[lay_id], "float", N_ep, "|", "*")) # Check dropout factors for dropout_factor in drop_rates[arch][0]: if float(dropout_factor) < 0.0 or float(dropout_factor) > 1.0: sys.stderr.write( "The dropout rate should be between 0 and 1. Got %s in %s.\n" % (dropout_factor, field_key) ) sys.exit(0) # Production case, we don't want to train, only forward without labels if is_production: ep = N_ep - 1 N_ep = 0 model_files = {} max_seq_length_train_curr = max_seq_length_train for arch in pt_files.keys(): model_files[arch] = out_folder + "/exp_files/final_" + arch + ".pkl" if strtobool(config["batches"]["increase_seq_length_train"]): max_seq_length_train_curr = config["batches"]["start_seq_len_train"] if len(max_seq_length_train.split(",")) == 1: max_seq_length_train_curr = int(max_seq_length_train_curr) else: # TODO: add support for increasing seq length when fea and lab have different time dimensionality pass for ep in range(N_ep): for tr_data in tr_data_lst: # Compute the total number of chunks for each training epoch N_ck_tr = compute_n_chunks(out_folder, tr_data, ep, N_ep_str_format, "train") N_ck_str_format = "0" + str(max(math.ceil(np.log10(N_ck_tr)), 1)) + "d" # ***Epoch training*** for ck in range(N_ck_tr): # path of the list of features for this chunk lst_file = ( out_folder + "/exp_files/train_" + tr_data + "_ep" + format(ep, N_ep_str_format) + "_ck" + format(ck, N_ck_str_format) + "_*.lst" ) # paths of the output files (info,model,chunk_specific cfg file) info_file = ( out_folder + "/exp_files/train_" + tr_data + "_ep" + format(ep, N_ep_str_format) + "_ck" + format(ck, N_ck_str_format) + ".info" ) if ep + ck == 0: model_files_past = {} else: model_files_past = model_files model_files = {} for arch in pt_files.keys(): model_files[arch] = info_file.replace(".info", "_" + arch + ".pkl") config_chunk_file = ( out_folder + "/exp_files/train_" + tr_data + "_ep" + format(ep, N_ep_str_format) + "_ck" + format(ck, N_ck_str_format) + ".cfg" ) lst_chunk_file.write(config_chunk_file + "\n") if strtobool(config["batches"]["increase_seq_length_train"]) == False: if len(max_seq_length_train.split(",")) == 1: max_seq_length_train_curr = int(max_seq_length_tr_arr[ep]) else: max_seq_length_train_curr = max_seq_length_tr_arr[ep] # Write chunk-specific cfg file write_cfg_chunk( cfg_file, config_chunk_file, cfg_file_proto_chunk, pt_files, lst_file, info_file, "train", tr_data, lr, max_seq_length_train_curr, name_data, ep, ck, batch_size_tr_arr[ep], drop_rates, ) # update pt_file (used to initialized the DNN for the next chunk) for pt_arch in pt_files.keys(): pt_files[pt_arch] = ( out_folder + "/exp_files/train_" + tr_data + "_ep" + format(ep, N_ep_str_format) + "_ck" + format(ck, N_ck_str_format) + "_" + pt_arch + ".pkl" ) if do_validation_after_chunk(ck, N_ck_tr, config) and tr_data == tr_data_lst[-1]: for valid_data in valid_data_lst: N_ck_valid = compute_n_chunks(out_folder, valid_data, ep, N_ep_str_format, "valid") N_ck_str_format_val = "0" + str(max(math.ceil(np.log10(N_ck_valid)), 1)) + "d" for ck_val in range(N_ck_valid): lst_file = get_val_lst_file_path( out_folder, valid_data, ep, ck, ck_val, None, N_ep_str_format, N_ck_str_format, N_ck_str_format_val, ) info_file = get_val_info_file_path( out_folder, valid_data, ep, ck, ck_val, N_ep_str_format, N_ck_str_format, N_ck_str_format_val, ) config_chunk_file = get_val_cfg_file_path( out_folder, valid_data, ep, ck, ck_val, N_ep_str_format, N_ck_str_format, N_ck_str_format_val, ) lst_chunk_file.write(config_chunk_file + "\n") write_cfg_chunk( cfg_file, config_chunk_file, cfg_file_proto_chunk, model_files, lst_file, info_file, "valid", valid_data, lr, max_seq_length_train_curr, name_data, ep, ck_val, batch_size_tr_arr[ep], drop_rates, ) if strtobool(config["batches"]["increase_seq_length_train"]): if len(max_seq_length_train.split(",")) == 1: max_seq_length_train_curr = max_seq_length_train_curr * int( config["batches"]["multply_factor_seq_len_train"] ) if max_seq_length_train_curr > int(max_seq_length_tr_arr[ep]): max_seq_length_train_curr = int(max_seq_length_tr_arr[ep]) else: # TODO: add support for increasing seq length when fea and lab have different time dimensionality pass # Create GAN LST files try: if config["gan"]["arch_gan"] == "True": clean_gan_data_name = config["data_use"]["clean_gan_with"].split(",") for dataset in clean_gan_data_name: # Compute the total number of chunks for each training epoch N_ck_tr = compute_n_chunks(out_folder, dataset, ep, N_ep_str_format, "gan") # ***Epoch training*** for ck in range(N_ck_tr): # path of the list of features for this chunk lst_file = ( out_folder + "/exp_files/gan_" + dataset + "_ep" + format(ep, N_ep_str_format) + "_ck" + format(ck, N_ck_str_format) + "_*.lst" ) # paths of the output files (info,model,chunk_specific cfg file) info_file = ( out_folder + "/exp_files/gan_" + dataset + "_ep" + format(ep, N_ep_str_format) + "_ck" + format(ck, N_ck_str_format) + ".info" ) config_chunk_file = ( out_folder + "/exp_files/gan_" + dataset + "_ep" + format(ep, N_ep_str_format) + "_ck" + format(ck, N_ck_str_format) + ".cfg" ) if strtobool(config["batches"]["increase_seq_length_train"]) == False: if len(max_seq_length_train.split(",")) == 1: max_seq_length_train_curr = int(max_seq_length_tr_arr[ep]) else: max_seq_length_train_curr = max_seq_length_tr_arr[ep] # Write chunk-specific cfg file write_cfg_chunk( cfg_file, config_chunk_file, cfg_file_proto_chunk, pt_files, lst_file, info_file, "train", dataset, lr, max_seq_length_train_curr, name_data, ep, ck, batch_size_tr_arr[ep], drop_rates, ) except KeyError: pass for forward_data in forward_data_lst: # Compute the number of chunks N_ck_forward = compute_n_chunks(out_folder, forward_data, ep, N_ep_str_format, "forward") N_ck_str_format = "0" + str(max(math.ceil(np.log10(N_ck_forward)), 1)) + "d" for ck in range(N_ck_forward): # path of the list of features for this chunk lst_file = ( out_folder + "/exp_files/forward_" + forward_data + "_ep" + format(ep, N_ep_str_format) + "_ck" + format(ck, N_ck_str_format) + "_*.lst" ) # output file info_file = ( out_folder + "/exp_files/forward_" + forward_data + "_ep" + format(ep, N_ep_str_format) + "_ck" + format(ck, N_ck_str_format) + ".info" ) config_chunk_file = ( out_folder + "/exp_files/forward_" + forward_data + "_ep" + format(ep, N_ep_str_format) + "_ck" + format(ck, N_ck_str_format) + ".cfg" ) lst_chunk_file.write(config_chunk_file + "\n") # Write chunk-specific cfg file write_cfg_chunk( cfg_file, config_chunk_file, cfg_file_proto_chunk, model_files, lst_file, info_file, "forward", forward_data, lr, max_seq_length_train_curr, name_data, ep, ck, batch_size_tr_arr[ep], drop_rates, ) lst_chunk_file.close() def create_lists(config): def _get_validation_data_for_chunks(fea_names, list_fea, N_chunks): full_list = [] for i in range(len(fea_names)): full_list.append([line.rstrip("\n") + "," for line in open(list_fea[i])]) full_list[i] = sorted(full_list[i]) full_list_fea_conc = full_list[0] for i in range(1, len(full_list)): full_list_fea_conc = list(map(str.__add__, full_list_fea_conc, full_list[i])) ganset = True try: if str(config["ganset"]["create_set"]) == "True": ganset = False except KeyError: pass if ganset: random.shuffle(full_list_fea_conc) valid_chunks_fea = list(split_chunks(full_list_fea_conc, N_chunks)) return valid_chunks_fea def _shuffle_forward_data(config): if "shuffle_forwarding_data" in config["forward"]: suffle_on_forwarding = strtobool(config["forward"]["shuffle_forwarding_data"]) if not suffle_on_forwarding: return False return True # splitting data into chunks (see out_folder/additional_files) out_folder = config["exp"]["out_folder"] seed = int(config["exp"]["seed"]) N_ep = int(config["exp"]["N_epochs_tr"]) N_ep_str_format = "0" + str(max(math.ceil(np.log10(N_ep)), 1)) + "d" # Setting the random seed random.seed(seed) # training chunk lists creation tr_data_name = config["data_use"]["train_with"].split(",") # Reading validation feature lists for dataset in tr_data_name: sec_data = cfg_item2sec(config, "data_name", dataset) [fea_names, list_fea, fea_opts, cws_left, cws_right] = parse_fea_field( config[cfg_item2sec(config, "data_name", dataset)]["fea"] ) N_chunks = int(config[sec_data]["N_chunks"]) N_ck_str_format = "0" + str(max(math.ceil(np.log10(N_chunks)), 1)) + "d" full_list = [] for i in range(len(fea_names)): full_list.append([line.rstrip("\n") + "," for line in open(list_fea[i])]) full_list[i] = sorted(full_list[i]) # concatenating all the featues in a single file (useful for shuffling consistently) full_list_fea_conc = full_list[0] for i in range(1, len(full_list)): full_list_fea_conc = list(map(str.__add__, full_list_fea_conc, full_list[i])) for ep in range(N_ep): # randomize the list ganset = True try: if str(config["ganset"]["create_set"]) == "True": ganset = False except KeyError: pass if ganset: random.shuffle(full_list_fea_conc) tr_chunks_fea = list(split_chunks(full_list_fea_conc, N_chunks)) tr_chunks_fea.reverse() for ck in range(N_chunks): for i in range(len(fea_names)): tr_chunks_fea_split = [] for snt in tr_chunks_fea[ck]: # print(snt.split(',')[i]) tr_chunks_fea_split.append(snt.split(",")[i]) output_lst_file = ( out_folder + "/exp_files/train_" + dataset + "_ep" + format(ep, N_ep_str_format) + "_ck" + format(ck, N_ck_str_format) + "_" + fea_names[i] + ".lst" ) f = open(output_lst_file, "w") tr_chunks_fea_wr = map(lambda x: x + "\n", tr_chunks_fea_split) f.writelines(tr_chunks_fea_wr) f.close() if do_validation_after_chunk(ck, N_chunks, config): valid_data_name = config["data_use"]["valid_with"].split(",") for dataset_val in valid_data_name: sec_data = cfg_item2sec(config, "data_name", dataset_val) fea_names, list_fea, fea_opts, cws_left, cws_right = parse_fea_field( config[cfg_item2sec(config, "data_name", dataset_val)]["fea"] ) N_chunks_val = int(config[sec_data]["N_chunks"]) N_ck_str_format_val = "0" + str(max(math.ceil(np.log10(N_chunks_val)), 1)) + "d" valid_chunks_fea = _get_validation_data_for_chunks(fea_names, list_fea, N_chunks_val) for ck_val in range(N_chunks_val): for fea_idx in range(len(fea_names)): valid_chunks_fea_split = [] for snt in valid_chunks_fea[ck_val]: valid_chunks_fea_split.append(snt.split(",")[fea_idx]) output_lst_file = get_val_lst_file_path( out_folder, dataset_val, ep, ck, ck_val, fea_names[fea_idx], N_ep_str_format, N_ck_str_format, N_ck_str_format_val, ) f = open(output_lst_file, "w") valid_chunks_fea_wr = map(lambda x: x + "\n", valid_chunks_fea_split) f.writelines(valid_chunks_fea_wr) f.close() # Create GAN LST files try: if config["gan"]["arch_gan"] == "True": clean_gan_data_name = config["data_use"]["clean_gan_with"].split(",") # Feature lists for clean GAN dataset for dataset in clean_gan_data_name: sec_data = cfg_item2sec(config, "data_name", dataset) [fea_names, list_fea, fea_opts, cws_left, cws_right] = parse_fea_field( config[cfg_item2sec(config, "data_name", dataset)]["fea"] ) N_chunks = int(config[sec_data]["N_chunks"]) full_list = [] for i in range(len(fea_names)): full_list.append([line.rstrip("\n") + "," for line in open(list_fea[i])]) full_list[i] = sorted(full_list[i]) # concatenating all the featues in a single file (useful for shuffling consistently) full_list_fea_conc = full_list[0] for i in range(1, len(full_list)): full_list_fea_conc = list(map(str.__add__, full_list_fea_conc, full_list[i])) for ep in range(N_ep): # randomize the list ganset = True try: if str(config["ganset"]["create_set"]) == "True": ganset = False except KeyError: pass if ganset: random.shuffle(full_list_fea_conc) tr_chunks_fea = list(split_chunks(full_list_fea_conc, N_chunks)) tr_chunks_fea.reverse() for ck in range(N_chunks): for i in range(len(fea_names)): tr_chunks_fea_split = [] for snt in tr_chunks_fea[ck]: # print(snt.split(',')[i]) tr_chunks_fea_split.append(snt.split(",")[i]) output_lst_file = ( out_folder + "/exp_files/gan_" + dataset + "_ep" + format(ep, N_ep_str_format) + "_ck" + format(ck, N_ck_str_format) + "_" + fea_names[i] + ".lst" ) f = open(output_lst_file, "w") tr_chunks_fea_wr = map(lambda x: x + "\n", tr_chunks_fea_split) f.writelines(tr_chunks_fea_wr) f.close() except KeyError: pass # forward chunk lists creation forward_data_name = config["data_use"]["forward_with"].split(",") # Reading validation feature lists for dataset in forward_data_name: sec_data = cfg_item2sec(config, "data_name", dataset) [fea_names, list_fea, fea_opts, cws_left, cws_right] = parse_fea_field( config[cfg_item2sec(config, "data_name", dataset)]["fea"] ) N_chunks = int(config[sec_data]["N_chunks"]) N_ck_str_format = "0" + str(max(math.ceil(np.log10(N_chunks)), 1)) + "d" full_list = [] for i in range(len(fea_names)): full_list.append([line.rstrip("\n") + "," for line in open(list_fea[i])]) full_list[i] = sorted(full_list[i]) # concatenating all the featues in a single file (useful for shuffling consistently) full_list_fea_conc = full_list[0] for i in range(1, len(full_list)): full_list_fea_conc = list(map(str.__add__, full_list_fea_conc, full_list[i])) # randomize the list if _shuffle_forward_data(config): random.shuffle(full_list_fea_conc) forward_chunks_fea = list(split_chunks(full_list_fea_conc, N_chunks)) for ck in range(N_chunks): for i in range(len(fea_names)): forward_chunks_fea_split = [] for snt in forward_chunks_fea[ck]: # print(snt.split(',')[i]) forward_chunks_fea_split.append(snt.split(",")[i]) output_lst_file = ( out_folder + "/exp_files/forward_" + dataset + "_ep" + format(ep, N_ep_str_format) + "_ck" + format(ck, N_ck_str_format) + "_" + fea_names[i] + ".lst" ) f = open(output_lst_file, "w") forward_chunks_fea_wr = map(lambda x: x + "\n", forward_chunks_fea_split) f.writelines(forward_chunks_fea_wr) f.close() def write_cfg_chunk( cfg_file, config_chunk_file, cfg_file_proto_chunk, pt_files, lst_file, info_file, to_do, data_set_name, lr, max_seq_length_train_curr, name_data, ep, ck, batch_size, drop_rates, ): # writing the chunk-specific cfg file config = configparser.ConfigParser() config.read(cfg_file) config_chunk = configparser.ConfigParser() config_chunk.read(cfg_file) # Exp section config_chunk["exp"]["to_do"] = to_do config_chunk["exp"]["out_info"] = info_file # change seed for randomness config_chunk["exp"]["seed"] = str(int(config_chunk["exp"]["seed"]) + ep + ck) config_chunk["batches"]["batch_size_train"] = batch_size for arch in pt_files.keys(): config_chunk[arch]["arch_pretrain_file"] = pt_files[arch] # writing the current learning rate for lr_arch in lr.keys(): config_chunk[lr_arch]["arch_lr"] = str(lr[lr_arch][ep]) for (field_key, field_val) in config.items(lr_arch): if "_drop" in field_key: N_lay = len(drop_rates[lr_arch]) drop_arr = [] for lay in range(N_lay): drop_arr.append(drop_rates[lr_arch][lay][ep]) config_chunk[lr_arch][field_key] = str(",".join(drop_arr)) # Data_chunk section config_chunk.add_section("data_chunk") config_chunk["data_chunk"] = config[cfg_item2sec(config, "data_name", data_set_name)] lst_files = sorted(glob.glob(lst_file)) current_fea = config_chunk["data_chunk"]["fea"] list_current_fea = re.findall("fea_name=(.*)\nfea_lst=(.*)\n", current_fea) for (fea, path) in list_current_fea: for path_cand in lst_files: fea_type_cand = re.findall("_(.*).lst", path_cand)[0].split("_")[-1] if fea_type_cand == fea: config_chunk["data_chunk"]["fea"] = config_chunk["data_chunk"]["fea"].replace(path, path_cand) config_chunk.remove_option("data_chunk", "data_name") config_chunk.remove_option("data_chunk", "N_chunks") config_chunk.remove_section("decoding") config_chunk.remove_section("data_use") data_to_del = [] for sec in config.sections(): if "dataset" in sec: data_to_del.append(config[sec]["data_name"]) for dataset in data_to_del: config_chunk.remove_section(cfg_item2sec(config_chunk, "data_name", dataset)) # Create batche section config_chunk.remove_option("batches", "increase_seq_length_train") config_chunk.remove_option("batches", "start_seq_len_train") config_chunk.remove_option("batches", "multply_factor_seq_len_train") config_chunk["batches"]["max_seq_length_train"] = str(max_seq_length_train_curr) # Write cfg_file_chunk with open(config_chunk_file, "w") as configfile: config_chunk.write(configfile) # Check cfg_file_chunk [config_proto_chunk, name_data_ck, name_arch_ck] = check_consistency_with_proto( config_chunk_file, cfg_file_proto_chunk ) def parse_fea_field(fea): # Adding the required fields into a list fea_names = [] fea_lsts = [] fea_opts = [] cws_left = [] cws_right = [] for line in fea.split("\n"): line = re.sub(" +", " ", line) if "fea_name=" in line: fea_names.append(line.split("=")[1]) if "fea_lst=" in line: fea_lsts.append(line.split("=")[1]) if "fea_opts=" in line: fea_opts.append(line.split("fea_opts=")[1]) if "cw_left=" in line: cws_left.append(line.split("=")[1]) if not (check_field(line.split("=")[1], "int(0,inf)", "cw_left")): sys.exit(0) if "cw_right=" in line: cws_right.append(line.split("=")[1]) if not (check_field(line.split("=")[1], "int(0,inf)", "cw_right")): sys.exit(0) # Check features names if not (sorted(fea_names) == sorted(list(set(fea_names)))): sys.stderr.write("ERROR fea_names must be different! (got %s)" % (fea_names)) sys.exit(0) snt_lst = [] cnt = 0 # Check consistency of feature lists for fea_lst in fea_lsts: if not (os.path.isfile(fea_lst)): sys.stderr.write( 'ERROR: The path "%s" specified in the field "fea_lst" of the config file does not exists! \n' % (fea_lst) ) sys.exit(0) else: snts = sorted([line.rstrip("\n").split(" ")[0] for line in open(fea_lst)]) snt_lst.append(snts) # Check if all the sentences are present in all the list files if cnt > 0: if snt_lst[cnt - 1] != snt_lst[cnt]: sys.stderr.write( "ERROR: the files %s in fea_lst contain a different set of sentences! \n" % (fea_lst) ) sys.exit(0) cnt = cnt + 1 return [fea_names, fea_lsts, fea_opts, cws_left, cws_right] def parse_lab_field(lab): # Adding the required fields into a list lab_names = [] lab_folders = [] lab_opts = [] for line in lab.split("\n"): line = re.sub(" +", " ", line) if "lab_name=" in line: lab_names.append(line.split("=")[1]) if "lab_folder=" in line: lab_folders.append(line.split("=")[1]) if "lab_opts=" in line: lab_opts.append(line.split("lab_opts=")[1]) # Check features names if not (sorted(lab_names) == sorted(list(set(lab_names)))): sys.stderr.write("ERROR lab_names must be different! (got %s)" % (lab_names)) sys.exit(0) # Check consistency of feature lists for lab_fold in lab_folders: if not (os.path.isdir(lab_fold)): sys.stderr.write( 'ERROR: The path "%s" specified in the field "lab_folder" of the config file does not exists! \n' % (lab_fold) ) sys.exit(0) return [lab_names, lab_folders, lab_opts] def compute_n_chunks(out_folder, data_list, ep, N_ep_str_format, step): list_ck = sorted( glob.glob(out_folder + "/exp_files/" + step + "_" + data_list + "_ep" + format(ep, N_ep_str_format) + "*.lst") ) last_ck = list_ck[-1] N_ck = int(re.findall("_ck(.+)_", last_ck)[-1].split("_")[0]) + 1 return N_ck def parse_model_field(cfg_file): # Reading the config file config = configparser.ConfigParser() config.read(cfg_file) # reading the proto file model_proto_file = config["model"]["model_proto"] f = open(model_proto_file, "r") proto_model = f.read() # readiing the model string model = config["model"]["model"] # Reading fea,lab arch architectures from the cfg file fea_lst = list(re.findall("fea_name=(.*)\n", config["dataset1"]["fea"].replace(" ", ""))) lab_lst = list(re.findall("lab_name=(.*)\n", config["dataset1"]["lab"].replace(" ", ""))) arch_lst = list(re.findall("arch_name=(.*)\n", open(cfg_file, "r").read().replace(" ", ""))) possible_operations = re.findall("(.*)\((.*),(.*)\)\n", proto_model) possible_inputs = fea_lst model_arch = list(filter(None, model.replace(" ", "").split("\n"))) # Reading the model field line by line for line in model_arch: pattern = "(.*)=(.*)\((.*),(.*)\)" if not re.match(pattern, line): sys.stderr.write( "ERROR: all the entries must be of the following type: output=operation(str,str), got (%s)\n" % (line) ) sys.exit(0) else: # Analyze line and chech if it is compliant with proto_model [out_name, operation, inp1, inp2] = list(re.findall(pattern, line)[0]) inps = [inp1, inp2] found = False for i in range(len(possible_operations)): if operation == possible_operations[i][0]: found = True for k in range(1, 3): if possible_operations[i][k] == "architecture": if inps[k - 1] not in arch_lst: sys.stderr.write( 'ERROR: the architecture "%s" is not in the architecture lists of the config file (possible architectures are %s)\n' % (inps[k - 1], arch_lst) ) sys.exit(0) if possible_operations[i][k] == "label": if inps[k - 1] not in lab_lst: sys.stderr.write( 'ERROR: the label "%s" is not in the label lists of the config file (possible labels are %s)\n' % (inps[k - 1], lab_lst) ) sys.exit(0) if possible_operations[i][k] == "input": if inps[k - 1] not in possible_inputs: sys.stderr.write( 'ERROR: the input "%s" is not defined before (possible inputs are %s)\n' % (inps[k - 1], possible_inputs) ) sys.exit(0) if possible_operations[i][k] == "float": try: float(inps[k - 1]) except ValueError: sys.stderr.write( 'ERROR: the input "%s" must be a float, got %s\n' % (inps[k - 1], line) ) sys.exit(0) # Update the list of possible inpus possible_inputs.append(out_name) break if found == False: sys.stderr.write( ('ERROR: operation "%s" does not exists (not defined into the model proto file)\n' % (operation)) ) sys.exit(0) # Check for the mandatory fiels if "loss_final" not in "".join(model_arch): sys.stderr.write("ERROR: the variable loss_final should be defined in model\n") sys.exit(0) if "err_final" not in "".join(model_arch): sys.stderr.write("ERROR: the variable err_final should be defined in model\n") sys.exit(0) def terminal_node_detection(model_arch, node): terminal = True pattern = "(.*)=(.*)\((.*),(.*)\)" for line in model_arch: [out_name, operation, inp1, inp2] = list(re.findall(pattern, line)[0]) if inp1 == node or inp2 == node: terminal = False return terminal def create_block_connection(lst_inp, model_arch, diag_lines, cnt_names, arch_dict): if lst_inp == []: return [[], [], diag_lines] pattern = "(.*)=(.*)\((.*),(.*)\)" arch_current = [] output_conn = [] current_inp = [] for input_element in lst_inp: for l in range(len(model_arch)): [out_name, operation, inp1, inp2] = list(re.findall(pattern, model_arch[l])[0]) if inp1 == input_element or inp2 == input_element: if operation == "compute": arch_current.append(inp1) output_conn.append(out_name) current_inp.append(inp2) model_arch[l] = "processed" + "=" + operation + "(" + inp1 + ",processed)" else: arch_current.append(out_name) output_conn.append(out_name) if inp1 == input_element: current_inp.append(inp1) model_arch[l] = out_name + "=" + operation + "(processed," + inp2 + ")" if inp2 == input_element: current_inp.append(inp2) model_arch[l] = out_name + "=" + operation + "(" + inp1 + ",processed)" for i in range(len(arch_current)): # Create connections diag_lines = ( diag_lines + str(cnt_names.index(arch_dict[current_inp[i]])) + " -> " + str(cnt_names.index(arch_current[i])) + ' [label = "' + current_inp[i] + '"]\n' ) # remove terminal nodes from output list output_conn_pruned = [] for node in output_conn: if not (terminal_node_detection(model_arch, node)): output_conn_pruned.append(node) [arch_current, output_conn, diag_lines] = create_block_connection( output_conn, model_arch, diag_lines, cnt_names, arch_dict ) return [arch_current, output_conn_pruned, diag_lines] def create_block_diagram(cfg_file): # Reading the config file config = configparser.ConfigParser() config.read(cfg_file) # readiing the model string model = config["model"]["model"] # Reading fea,lab arch architectures from the cfg file pattern = "(.*)=(.*)\((.*),(.*)\)" fea_lst = list(re.findall("fea_name=(.*)\n", config["dataset1"]["fea"].replace(" ", ""))) lab_lst = list(re.findall("lab_name=(.*)\n", config["dataset1"]["lab"].replace(" ", ""))) arch_lst = list(re.findall("arch_name=(.*)\n", open(cfg_file, "r").read().replace(" ", ""))) out_diag_file = config["exp"]["out_folder"] + "/model.diag" model_arch = list(filter(None, model.replace(" ", "").split("\n"))) diag_lines = "blockdiag {\n" cnt = 0 cnt_names = [] arch_lst = [] fea_lst_used = [] lab_lst_used = [] for line in model_arch: if "err_final=" in line: model_arch.remove(line) # Initializations of the blocks for line in model_arch: [out_name, operation, inp1, inp2] = list(re.findall(pattern, line)[0]) if operation != "compute": # node architecture diag_lines = diag_lines + str(cnt) + ' [label="' + operation + '",shape = roundedbox];\n' arch_lst.append(out_name) cnt_names.append(out_name) cnt = cnt + 1 # labels if inp2 in lab_lst: diag_lines = diag_lines + str(cnt) + ' [label="' + inp2 + '",shape = roundedbox];\n' if inp2 not in lab_lst_used: lab_lst_used.append(inp2) cnt_names.append(inp2) cnt = cnt + 1 # features if inp1 in fea_lst: diag_lines = diag_lines + str(cnt) + ' [label="' + inp1 + '",shape = circle];\n' if inp1 not in fea_lst_used: fea_lst_used.append(inp1) cnt_names.append(inp1) cnt = cnt + 1 if inp2 in fea_lst: diag_lines = diag_lines + str(cnt) + ' [label="' + inp2 + '",shape = circle];\n' if inp2 not in fea_lst_used: fea_lst_used.append(inp2) cnt_names.append(inp2) cnt = cnt + 1 else: # architecture diag_lines = diag_lines + str(cnt) + ' [label="' + inp1 + '",shape = box];\n' arch_lst.append(inp1) cnt_names.append(inp1) cnt = cnt + 1 # feature if inp2 in fea_lst: diag_lines = diag_lines + str(cnt) + ' [label="' + inp2 + '",shape = circle];\n' if inp2 not in fea_lst_used: fea_lst_used.append(inp2) cnt_names.append(inp2) cnt = cnt + 1 # Connections across blocks lst_conc = fea_lst_used + lab_lst_used arch_dict = {} for elem in lst_conc: arch_dict[elem] = elem for model_line in model_arch: [out_name, operation, inp1, inp2] = list(re.findall(pattern, model_line)[0]) if operation == "compute": arch_dict[out_name] = inp1 else: arch_dict[out_name] = out_name output_conn = lst_conc [arch_current, output_conn, diag_lines] = create_block_connection( output_conn, model_arch, diag_lines, cnt_names, arch_dict ) diag_lines = diag_lines + "}" # Write the diag file describing the model with open(out_diag_file, "w") as text_file: text_file.write("%s" % diag_lines) # Create image from the diag file log_file = config["exp"]["out_folder"] + "/log.log" cmd = "blockdiag -Tsvg " + out_diag_file + " -o " + config["exp"]["out_folder"] + "/model.svg" run_shell(cmd, log_file) def list_fea_lab_arch(config): # cancel model = config["model"]["model"].split("\n") fea_lst = list(re.findall("fea_name=(.*)\n", config["data_chunk"]["fea"].replace(" ", ""))) lab_lst = list(re.findall("lab_name=(.*)\n", config["data_chunk"]["lab"].replace(" ", ""))) fea_lst_used = [] lab_lst_used = [] arch_lst_used = [] fea_dict_used = {} lab_dict_used = {} arch_dict_used = {} fea_lst_used_name = [] lab_lst_used_name = [] arch_lst_used_name = [] fea_field = config["data_chunk"]["fea"] lab_field = config["data_chunk"]["lab"] pattern = "(.*)=(.*)\((.*),(.*)\)" for line in model: [out_name, operation, inp1, inp2] = list(re.findall(pattern, line)[0]) if inp1 in fea_lst and inp1 not in fea_lst_used_name: pattern_fea = "fea_name=" + inp1 + "\nfea_lst=(.*)\nfea_opts=(.*)\ncw_left=(.*)\ncw_right=(.*)" fea_lst_used.append((inp1 + "," + ",".join(list(re.findall(pattern_fea, fea_field)[0]))).split(",")) fea_dict_used[inp1] = (inp1 + "," + ",".join(list(re.findall(pattern_fea, fea_field)[0]))).split(",") fea_lst_used_name.append(inp1) if inp2 in fea_lst and inp2 not in fea_lst_used_name: pattern_fea = "fea_name=" + inp2 + "\nfea_lst=(.*)\nfea_opts=(.*)\ncw_left=(.*)\ncw_right=(.*)" fea_lst_used.append((inp2 + "," + ",".join(list(re.findall(pattern_fea, fea_field)[0]))).split(",")) fea_dict_used[inp2] = (inp2 + "," + ",".join(list(re.findall(pattern_fea, fea_field)[0]))).split(",") fea_lst_used_name.append(inp2) if inp1 in lab_lst and inp1 not in lab_lst_used_name: pattern_lab = "lab_name=" + inp1 + "\nlab_folder=(.*)\nlab_opts=(.*)" lab_lst_used.append((inp1 + "," + ",".join(list(re.findall(pattern_lab, lab_field)[0]))).split(",")) lab_dict_used[inp1] = (inp1 + "," + ",".join(list(re.findall(pattern_lab, lab_field)[0]))).split(",") lab_lst_used_name.append(inp1) if inp2 in lab_lst and inp2 not in lab_lst_used_name: pattern_lab = "lab_name=" + inp2 + "\nlab_folder=(.*)\nlab_opts=(.*)" lab_lst_used.append((inp2 + "," + ",".join(list(re.findall(pattern_lab, lab_field)[0]))).split(",")) lab_dict_used[inp2] = (inp2 + "," + ",".join(list(re.findall(pattern_lab, lab_field)[0]))).split(",") lab_lst_used_name.append(inp2) if operation == "compute" and inp1 not in arch_lst_used_name: arch_id = cfg_item2sec(config, "arch_name", inp1) arch_seq_model = strtobool(config[arch_id]["arch_seq_model"]) arch_lst_used.append([arch_id, inp1, arch_seq_model]) arch_dict_used[inp1] = [arch_id, inp1, arch_seq_model] arch_lst_used_name.append(inp1) # convert to unicode (for python 2) for i in range(len(fea_lst_used)): fea_lst_used[i] = list(map(str, fea_lst_used[i])) for i in range(len(lab_lst_used)): lab_lst_used[i] = list(map(str, lab_lst_used[i])) for i in range(len(arch_lst_used)): arch_lst_used[i] = list(map(str, arch_lst_used[i])) return [fea_lst_used, lab_lst_used, arch_lst_used] def dict_fea_lab_arch(config, fea_only): model = config["model"]["model"].split("\n") fea_lst = list(re.findall("fea_name=(.*)\n", config["data_chunk"]["fea"].replace(" ", ""))) lab_lst = list(re.findall("lab_name=(.*)\n", config["data_chunk"]["lab"].replace(" ", ""))) fea_lst_used = [] lab_lst_used = [] arch_lst_used = [] fea_dict_used = {} lab_dict_used = {} arch_dict_used = {} fea_lst_used_name = [] lab_lst_used_name = [] arch_lst_used_name = [] fea_field = config["data_chunk"]["fea"] lab_field = config["data_chunk"]["lab"] pattern = "(.*)=(.*)\((.*),(.*)\)" for line in model: [out_name, operation, inp1, inp2] = list(re.findall(pattern, line)[0]) if inp1 in fea_lst and inp1 not in fea_lst_used_name: pattern_fea = "fea_name=" + inp1 + "\nfea_lst=(.*)\nfea_opts=(.*)\ncw_left=(.*)\ncw_right=(.*)" if sys.version_info[0] == 2: fea_lst_used.append( (inp1 + "," + ",".join(list(re.findall(pattern_fea, fea_field)[0]))).encode("utf8").split(",") ) fea_dict_used[inp1] = ( (inp1 + "," + ",".join(list(re.findall(pattern_fea, fea_field)[0]))).encode("utf8").split(",") ) else: fea_lst_used.append((inp1 + "," + ",".join(list(re.findall(pattern_fea, fea_field)[0]))).split(",")) fea_dict_used[inp1] = (inp1 + "," + ",".join(list(re.findall(pattern_fea, fea_field)[0]))).split(",") fea_lst_used_name.append(inp1) if inp2 in fea_lst and inp2 not in fea_lst_used_name: pattern_fea = "fea_name=" + inp2 + "\nfea_lst=(.*)\nfea_opts=(.*)\ncw_left=(.*)\ncw_right=(.*)" if sys.version_info[0] == 2: fea_lst_used.append( (inp2 + "," + ",".join(list(re.findall(pattern_fea, fea_field)[0]))).encode("utf8").split(",") ) fea_dict_used[inp2] = ( (inp2 + "," + ",".join(list(re.findall(pattern_fea, fea_field)[0]))).encode("utf8").split(",") ) else: fea_lst_used.append((inp2 + "," + ",".join(list(re.findall(pattern_fea, fea_field)[0]))).split(",")) fea_dict_used[inp2] = (inp2 + "," + ",".join(list(re.findall(pattern_fea, fea_field)[0]))).split(",") fea_lst_used_name.append(inp2) if inp1 in lab_lst and inp1 not in lab_lst_used_name and not fea_only: pattern_lab = "lab_name=" + inp1 + "\nlab_folder=(.*)\nlab_opts=(.*)" if sys.version_info[0] == 2: lab_lst_used.append( (inp1 + "," + ",".join(list(re.findall(pattern_lab, lab_field)[0]))).encode("utf8").split(",") ) lab_dict_used[inp1] = ( (inp1 + "," + ",".join(list(re.findall(pattern_lab, lab_field)[0]))).encode("utf8").split(",") ) else: lab_lst_used.append((inp1 + "," + ",".join(list(re.findall(pattern_lab, lab_field)[0]))).split(",")) lab_dict_used[inp1] = (inp1 + "," + ",".join(list(re.findall(pattern_lab, lab_field)[0]))).split(",") lab_lst_used_name.append(inp1) if inp2 in lab_lst and inp2 not in lab_lst_used_name and not fea_only: # Testing production case (no labels) pattern_lab = "lab_name=" + inp2 + "\nlab_folder=(.*)\nlab_opts=(.*)" if sys.version_info[0] == 2: lab_lst_used.append( (inp2 + "," + ",".join(list(re.findall(pattern_lab, lab_field)[0]))).encode("utf8").split(",") ) lab_dict_used[inp2] = ( (inp2 + "," + ",".join(list(re.findall(pattern_lab, lab_field)[0]))).encode("utf8").split(",") ) else: lab_lst_used.append((inp2 + "," + ",".join(list(re.findall(pattern_lab, lab_field)[0]))).split(",")) lab_dict_used[inp2] = (inp2 + "," + ",".join(list(re.findall(pattern_lab, lab_field)[0]))).split(",") lab_lst_used_name.append(inp2) if operation == "compute" and inp1 not in arch_lst_used_name: arch_id = cfg_item2sec(config, "arch_name", inp1) arch_seq_model = strtobool(config[arch_id]["arch_seq_model"]) arch_lst_used.append([arch_id, inp1, arch_seq_model]) arch_dict_used[inp1] = [arch_id, inp1, arch_seq_model] arch_lst_used_name.append(inp1) # convert to unicode (for python 2) for i in range(len(fea_lst_used)): fea_lst_used[i] = list(map(str, fea_lst_used[i])) for i in range(len(lab_lst_used)): lab_lst_used[i] = list(map(str, lab_lst_used[i])) for i in range(len(arch_lst_used)): arch_lst_used[i] = list(map(str, arch_lst_used[i])) return [fea_dict_used, lab_dict_used, arch_dict_used] def is_sequential(config, arch_lst): # To cancel seq_model = False for [arch_id, arch_name, arch_seq] in arch_lst: if strtobool(config[arch_id]["arch_seq_model"]): seq_model = True break return seq_model def is_sequential_dict(config, arch_dict): seq_model = False for arch in arch_dict.keys(): arch_id = arch_dict[arch][0] if strtobool(config[arch_id]["arch_seq_model"]): seq_model = True break return seq_model def compute_cw_max(fea_dict): cw_left_arr = [] cw_right_arr = [] for fea in fea_dict.keys(): cw_left_arr.append(int(fea_dict[fea][3])) cw_right_arr.append(int(fea_dict[fea][4])) cw_left_max = max(cw_left_arr) cw_right_max = max(cw_right_arr) return [cw_left_max, cw_right_max] def model_init(inp_out_dict, model, config, arch_dict, use_cuda, multi_gpu, to_do): pattern = "(.*)=(.*)\((.*),(.*)\)" nns = {} costs = {} for line in model: [out_name, operation, inp1, inp2] = list(re.findall(pattern, line)[0]) if operation == "compute": # computing input dim inp_dim = inp_out_dict[inp2][-1] # import the class module = importlib.import_module(config[arch_dict[inp1][0]]["arch_library"]) nn_class = getattr(module, config[arch_dict[inp1][0]]["arch_class"]) # add use cuda and todo options config.set(arch_dict[inp1][0], "use_cuda", config["exp"]["use_cuda"]) config.set(arch_dict[inp1][0], "to_do", config["exp"]["to_do"]) arch_freeze_flag = strtobool(config[arch_dict[inp1][0]]["arch_freeze"]) # initialize the neural network double_features = False try: if config["gan"]["double_features"] == "True": double_features = True except KeyError: pass if double_features: net = nn_class(config[arch_dict[inp1][0]], (inp_dim*2)) else: net = nn_class(config[arch_dict[inp1][0]], inp_dim) if use_cuda: net.cuda() if to_do == "train": if not (arch_freeze_flag): net.train() else: # Switch to eval modality if architecture is frozen (mainly for batch_norm/dropout functions) net.eval() else: net.eval() # addigng nn into the nns dict nns[arch_dict[inp1][1]] = net out_dim = net.out_dim # updating output dim inp_out_dict[out_name] = [out_dim] if operation == "concatenate": inp_dim1 = inp_out_dict[inp1][-1] inp_dim2 = inp_out_dict[inp2][-1] inp_out_dict[out_name] = [inp_dim1 + inp_dim2] if operation == "cost_nll": costs[out_name] = nn.NLLLoss() inp_out_dict[out_name] = [1] if operation == "cost_err": inp_out_dict[out_name] = [1] if ( operation == "mult" or operation == "sum" or operation == "mult_constant" or operation == "sum_constant" or operation == "avg" or operation == "mse" ): inp_out_dict[out_name] = inp_out_dict[inp1] return [nns, costs] def optimizer_init(nns, config, arch_dict): # optimizer init optimizers = {} for net in nns.keys(): lr = float(config[arch_dict[net][0]]["arch_lr"]) if config[arch_dict[net][0]]["arch_opt"] == "sgd": opt_momentum = float(config[arch_dict[net][0]]["opt_momentum"]) opt_weight_decay = float(config[arch_dict[net][0]]["opt_weight_decay"]) opt_dampening = float(config[arch_dict[net][0]]["opt_dampening"]) opt_nesterov = strtobool(config[arch_dict[net][0]]["opt_nesterov"]) optimizers[net] = optim.SGD( nns[net].parameters(), lr=lr, momentum=opt_momentum, weight_decay=opt_weight_decay, dampening=opt_dampening, nesterov=opt_nesterov, ) if config[arch_dict[net][0]]["arch_opt"] == "adam": opt_betas = list(map(float, (config[arch_dict[net][0]]["opt_betas"].split(",")))) opt_eps = float(config[arch_dict[net][0]]["opt_eps"]) opt_weight_decay = float(config[arch_dict[net][0]]["opt_weight_decay"]) opt_amsgrad = strtobool(config[arch_dict[net][0]]["opt_amsgrad"]) optimizers[net] = optim.Adam( nns[net].parameters(), lr=lr, betas=opt_betas, eps=opt_eps, weight_decay=opt_weight_decay, amsgrad=opt_amsgrad, ) if config[arch_dict[net][0]]["arch_opt"] == "rmsprop": opt_momentum = float(config[arch_dict[net][0]]["opt_momentum"]) opt_alpha = float(config[arch_dict[net][0]]["opt_alpha"]) opt_eps = float(config[arch_dict[net][0]]["opt_eps"]) opt_centered = strtobool(config[arch_dict[net][0]]["opt_centered"]) opt_weight_decay = float(config[arch_dict[net][0]]["opt_weight_decay"]) optimizers[net] = optim.RMSprop( nns[net].parameters(), lr=lr, momentum=opt_momentum, alpha=opt_alpha, eps=opt_eps, centered=opt_centered, weight_decay=opt_weight_decay, ) return optimizers def forward_model_refac01( fea_dict, lab_dict, arch_dict, model, nns, costs, inp, ref, inp_out_dict, max_len_fea, max_len_lab, batch_size, to_do, forward_outs, ): def _add_input_features_to_outs_dict(fea_dict, outs_dict, inp): for fea in fea_dict.keys(): if len(inp.shape) == 3 and len(fea_dict[fea]) > 1: outs_dict[fea] = inp[:, :, fea_dict[fea][5] : fea_dict[fea][6]] if len(inp.shape) == 2 and len(fea_dict[fea]) > 1: outs_dict[fea] = inp[:, fea_dict[fea][5] : fea_dict[fea][6]] return outs_dict def _compute_layer_values( inp_out_dict, inp2, inp, inp1, max_len, batch_size, arch_dict, out_name, nns, outs_dict, to_do ): def _is_input_feature(inp_out_dict, inp2): if len(inp_out_dict[inp2]) > 1: return True return False def _extract_respective_feature_from_input(inp, inp_out_dict, inp2, arch_dict, inp1, max_len, batch_size): if len(inp.shape) == 3: inp_dnn = inp if not (bool(arch_dict[inp1][2])): inp_dnn = inp_dnn.view(max_len * batch_size, -1) if len(inp.shape) == 2: inp_dnn = inp if bool(arch_dict[inp1][2]): inp_dnn = inp_dnn.view(max_len, batch_size, -1) return inp_dnn do_break = False if _is_input_feature(inp_out_dict, inp2): inp_dnn = _extract_respective_feature_from_input( inp, inp_out_dict, inp2, arch_dict, inp1, max_len, batch_size ) outs_dict[out_name] = nns[inp1](inp_dnn) else: if not (bool(arch_dict[inp1][2])) and len(outs_dict[inp2].shape) == 3: outs_dict[inp2] = outs_dict[inp2].view(outs_dict[inp2].shape[0] * outs_dict[inp2].shape[1], -1) if bool(arch_dict[inp1][2]) and len(outs_dict[inp2].shape) == 2: # TODO: This computation needs to be made independent of max_len in case the network is performing sub sampling in time outs_dict[inp2] = outs_dict[inp2].view(max_len, batch_size, -1) outs_dict[out_name] = nns[inp1](outs_dict[inp2]) if to_do == "forward" and out_name == forward_outs[-1]: do_break = True return outs_dict, do_break def _get_labels_from_input(ref, inp2, lab_dict): if len(inp.shape) == 3: lab_dnn = ref if len(inp.shape) == 2: lab_dnn = ref lab_dnn = lab_dnn.view(-1).long() return lab_dnn def _get_network_output(outs_dict, inp1, max_len, batch_size): out = outs_dict[inp1] if len(out.shape) == 3: out = out.view(max_len * batch_size, -1) return out outs_dict = {} _add_input_features_to_outs_dict(fea_dict, outs_dict, inp) layer_string_pattern = "(.*)=(.*)\((.*),(.*)\)" for line in model: out_name, operation, inp1, inp2 = list(re.findall(layer_string_pattern, line)[0]) if operation == "compute": outs_dict, do_break = _compute_layer_values( inp_out_dict, inp2, inp, inp1, max_len_fea, batch_size, arch_dict, out_name, nns, outs_dict, to_do ) if do_break: break elif operation == "cost_nll": lab_dnn = _get_labels_from_input(ref, inp2, lab_dict) out = _get_network_output(outs_dict, inp1, max_len_lab, batch_size) if to_do != "forward": outs_dict[out_name] = costs[out_name](out, lab_dnn) elif operation == "cost_err": lab_dnn = _get_labels_from_input(ref, inp2, lab_dict) out = _get_network_output(outs_dict, inp1, max_len_lab, batch_size) if to_do != "forward": pred = torch.max(out, dim=1)[1] err = torch.mean((pred != lab_dnn).float()) outs_dict[out_name] = err elif operation == "concatenate": dim_conc = len(outs_dict[inp1].shape) - 1 outs_dict[out_name] = torch.cat((outs_dict[inp1], outs_dict[inp2]), dim_conc) # check concat axis if to_do == "forward" and out_name == forward_outs[-1]: break elif operation == "mult": outs_dict[out_name] = outs_dict[inp1] * outs_dict[inp2] if to_do == "forward" and out_name == forward_outs[-1]: break elif operation == "sum": outs_dict[out_name] = outs_dict[inp1] + outs_dict[inp2] if to_do == "forward" and out_name == forward_outs[-1]: break elif operation == "mult_constant": outs_dict[out_name] = outs_dict[inp1] * float(inp2) if to_do == "forward" and out_name == forward_outs[-1]: break elif operation == "sum_constant": outs_dict[out_name] = outs_dict[inp1] + float(inp2) if to_do == "forward" and out_name == forward_outs[-1]: break elif operation == "avg": outs_dict[out_name] = (outs_dict[inp1] + outs_dict[inp2]) / 2 if to_do == "forward" and out_name == forward_outs[-1]: break elif operation == "mse": outs_dict[out_name] = torch.mean((outs_dict[inp1] - outs_dict[inp2]) ** 2) if to_do == "forward" and out_name == forward_outs[-1]: break return outs_dict def plot_waveforms(waveform_tensor): with torch.no_grad(): if len(waveform_tensor) > 1: plt.figure() for i in range(len(waveform_tensor)): plt.subplot(len(waveform_tensor), 1, (i + 1)) plt.plot(waveform_tensor[i].t().detach().to("cpu").numpy()) plt.show() else: plt.figure() plt.plot(waveform_tensor.t().detach().to("cpu").numpy()) plt.show() def forward_model( fea_dict, lab_dict, arch_dict, model, nns, costs, inp, inp_out_dict, max_len, batch_size, to_do, forward_outs, generator = None, discriminator = None, gan_on = False, double_features = False, ): # Forward Step outs_dict = {} pattern = "(.*)=(.*)\((.*),(.*)\)" # adding input features to out_dict: for fea in fea_dict.keys(): if len(inp.shape) == 3 and len(fea_dict[fea]) > 1: outs_dict[fea] = inp[:, :, fea_dict[fea][5] : fea_dict[fea][6]] if len(inp.shape) == 2 and len(fea_dict[fea]) > 1: outs_dict[fea] = inp[:, fea_dict[fea][5] : fea_dict[fea][6]] for line in model: [out_name, operation, inp1, inp2] = list(re.findall(pattern, line)[0]) if operation == "compute": if len(inp_out_dict[inp2]) > 1: # if it is an input feature # Selection of the right feature in the inp tensor if len(inp.shape) == 3: inp_dnn = inp[:, :, inp_out_dict[inp2][-3] : inp_out_dict[inp2][-2]] if not (bool(arch_dict[inp1][2])): inp_dnn = inp_dnn.view(max_len * batch_size, -1) if len(inp.shape) == 2: inp_dnn = inp[:, inp_out_dict[inp2][-3] : inp_out_dict[inp2][-2]] if bool(arch_dict[inp1][2]): inp_dnn = inp_dnn.view(max_len, batch_size, -1) # Run features trough generator network if gan_on and to_do == "train": # Using GAN on raw features outs_dict["inp_dnn"] = inp_dnn outs_dict["gan_training"] = True # Use gan for Acoustic model training with torch.no_grad(): outs_dict["generator_output"] = generator(inp_dnn) if discriminator is not None: d_output = discriminator(inp_dnn) pred = d_output.data.max(1, keepdim=True)[1] for i in range(d_output.shape[0]): if pred[i] == 1: # Replace clean samples with original outs_dict["generator_output"][i] = inp_dnn[i] if double_features: outs_dict[out_name] = nns[inp1](torch.cat((inp_dnn, outs_dict["generator_output"]), dim = 1)) else: outs_dict[out_name] = nns[inp1](outs_dict["generator_output"]) elif gan_on: # Validation and forward with GAN # Use GAN for evaluation outs_dict["inp_dnn"] = inp_dnn outs_dict["generator_output"] = generator(inp_dnn) if discriminator is not None: d_output = discriminator(inp_dnn) pred = d_output.data.max(1, keepdim=True)[1] for i in range(d_output.shape[0]): if pred[i] == 1: # Replace clean samples with original outs_dict["generator_output"][i] = inp_dnn[i] if double_features: outs_dict[out_name] = nns[inp1]( torch.cat((inp_dnn, outs_dict["generator_output"].detach()), dim = 1)) else: outs_dict[out_name] = nns[inp1](outs_dict["generator_output"].detach()) outs_dict["gan_training"] = False else: # Do not use GAN at all if double_features: inp_dnn = torch.cat((inp_dnn, inp_dnn), dim = 1) outs_dict["inp_dnn"] = inp_dnn outs_dict[out_name] = nns[inp1](inp_dnn) outs_dict["gan_training"] = False else: if not (bool(arch_dict[inp1][2])) and len(outs_dict[inp2].shape) == 3: outs_dict[inp2] = outs_dict[inp2].view(max_len * batch_size, -1) if bool(arch_dict[inp1][2]) and len(outs_dict[inp2].shape) == 2: outs_dict[inp2] = outs_dict[inp2].view(max_len, batch_size, -1) outs_dict[out_name] = nns[inp1](outs_dict[inp2]) if to_do == "forward" and out_name == forward_outs[-1]: break if operation == "cost_nll": # Put labels in the right format if len(inp.shape) == 3: lab_dnn = inp[:, :, lab_dict[inp2][3]] if len(inp.shape) == 2: lab_dnn = inp[:, lab_dict[inp2][3]] lab_dnn = lab_dnn.view(-1).long() # put output in the right format out = outs_dict[inp1] if len(out.shape) == 3: out = out.view(max_len * batch_size, -1) if to_do != "forward": outs_dict[out_name] = costs[out_name](out, lab_dnn) outs_dict["lab_dnn"] = lab_dnn if operation == "cost_err": if len(inp.shape) == 3: lab_dnn = inp[:, :, lab_dict[inp2][3]] if len(inp.shape) == 2: lab_dnn = inp[:, lab_dict[inp2][3]] lab_dnn = lab_dnn.view(-1).long() # put output in the right format out = outs_dict[inp1] if len(out.shape) == 3: out = out.view(max_len * batch_size, -1) if to_do != "forward": pred = torch.max(out, dim=1)[1] err = torch.mean((pred != lab_dnn).float()) outs_dict[out_name] = err if operation == "concatenate": dim_conc = len(outs_dict[inp1].shape) - 1 outs_dict[out_name] = torch.cat((outs_dict[inp1], outs_dict[inp2]), dim_conc) # check concat axis if to_do == "forward" and out_name == forward_outs[-1]: break if operation == "mult": outs_dict[out_name] = outs_dict[inp1] * outs_dict[inp2] if to_do == "forward" and out_name == forward_outs[-1]: break if operation == "sum": outs_dict[out_name] = outs_dict[inp1] + outs_dict[inp2] if to_do == "forward" and out_name == forward_outs[-1]: break if operation == "mult_constant": outs_dict[out_name] = outs_dict[inp1] * float(inp2) if to_do == "forward" and out_name == forward_outs[-1]: break if operation == "sum_constant": outs_dict[out_name] = outs_dict[inp1] + float(inp2) if to_do == "forward" and out_name == forward_outs[-1]: break if operation == "avg": outs_dict[out_name] = (outs_dict[inp1] + outs_dict[inp2]) / 2 if to_do == "forward" and out_name == forward_outs[-1]: break if operation == "mse": outs_dict[out_name] = torch.mean((outs_dict[inp1] - outs_dict[inp2]) ** 2) if to_do == "forward" and out_name == forward_outs[-1]: break return outs_dict def dump_epoch_results( res_file_path, ep, tr_data_lst, tr_loss_tot, tr_error_tot, tot_time, valid_data_lst, valid_peformance_dict, lr, N_ep ): # # Default terminal line size is 80 characters, try new dispositions to fit this limit # N_ep_str_format = "0" + str(max(math.ceil(np.log10(N_ep)), 1)) + "d" res_file = open(res_file_path, "a") res_file.write( "ep=%s tr=%s loss=%s err=%s " % ( format(ep, N_ep_str_format), tr_data_lst, format(tr_loss_tot / len(tr_data_lst), "0.3f"), format(tr_error_tot / len(tr_data_lst), "0.3f"), ) ) print(" ") print("----- Summary epoch %s / %s" % (format(ep+1, N_ep_str_format), format(N_ep, N_ep_str_format))) print("Training on %s" % (tr_data_lst)) print( "Loss = %s | err = %s " % (format(tr_loss_tot / len(tr_data_lst), "0.3f"), format(tr_error_tot / len(tr_data_lst), "0.3f")) ) print("-----") for valid_data in valid_data_lst: res_file.write( "valid=%s loss=%s err=%s " % ( valid_data, format(valid_peformance_dict[valid_data][0], "0.3f"), format(valid_peformance_dict[valid_data][1], "0.3f"), ) ) print("Validating on %s" % (valid_data)) print( "Loss = %s | err = %s " % ( format(valid_peformance_dict[valid_data][0], "0.3f"), format(valid_peformance_dict[valid_data][1], "0.3f"), ) ) print("-----") for lr_arch in lr.keys(): res_file.write("lr_%s=%s " % (lr_arch, lr[lr_arch][ep])) print("Learning rate on %s = %s " % (lr_arch, lr[lr_arch][ep])) print("-----") res_file.write("time(s)=%i\n" % (int(tot_time))) print("Elapsed time (s) = %i\n" % (int(tot_time))) print(" ") res_file.close() def progress(count, total, status=""): bar_len = 30 filled_len = int(round(bar_len * count / float(total))) percents = round(100.0 * count / float(total), 1) bar = "=" * filled_len + "-" * (bar_len - filled_len) if count == total - 1: sys.stdout.write("[%s] %s%s %s \r" % (bar, 100, "%", status)) sys.stdout.write("\n") else: sys.stdout.write("[%s] %s%s %s\r" % (bar, percents, "%", status)) sys.stdout.flush() def export_loss_acc_to_txt(out_folder, N_ep, val_lst): if not os.path.exists(out_folder + "/generated_outputs"): os.makedirs(out_folder + "/generated_outputs") nb_val = len(val_lst) res = open(out_folder + "/res.res", "r").readlines() tr_loss = [] tr_acc = [] val_loss = np.ndarray((nb_val, N_ep)) val_acc = np.ndarray((nb_val, N_ep)) line_cpt = 0 for i in range(N_ep): splitted = res[i].split(" ") # Getting uniq training loss and acc tr_loss.append(float(splitted[2].split("=")[1])) tr_acc.append(1 - float(splitted[3].split("=")[1])) # Getting multiple or uniq val loss and acc # +5 to avoird the 6 first columns of the res.res file for i in range(nb_val): val_loss[i][line_cpt] = float(splitted[(i * 3) + 5].split("=")[1]) val_acc[i][line_cpt] = 1 - float(splitted[(i * 3) + 6].split("=")[1]) line_cpt += 1 # Saving to files np.savetxt(out_folder + "/generated_outputs/tr_loss.txt", np.asarray(tr_loss), "%0.3f", delimiter=",") np.savetxt(out_folder + "/generated_outputs/tr_acc.txt", np.asarray(tr_acc), "%0.3f", delimiter=",") for i in range(nb_val): np.savetxt(out_folder + "/generated_outputs/val_" + str(i) + "_loss.txt", val_loss[i], "%0.5f", delimiter=",") np.savetxt(out_folder + "/generated_outputs/val_" + str(i) + "_acc.txt", val_acc[i], "%0.5f", delimiter=",") def create_curves(out_folder, N_ep, val_lst): try: import matplotlib as mpl mpl.use("Agg") import matplotlib.pyplot as plt except ValueError: print("WARNING: matplotlib is not installed. The plots of the training curves have not been created.") sys.exit(0) print(" ") print("-----") print("Generating output files and plots ... ") export_loss_acc_to_txt(out_folder, N_ep, val_lst) if not os.path.exists(out_folder + "/generated_outputs"): sys.stdacc.write("accOR: No results generated please call export_loss_err_to_txt() before") sys.exit(0) nb_epoch = len(open(out_folder + "/generated_outputs/tr_loss.txt", "r").readlines()) x = np.arange(nb_epoch) nb_val = len(val_lst) # Loading train Loss and acc tr_loss = np.loadtxt(out_folder + "/generated_outputs/tr_loss.txt") tr_acc = np.loadtxt(out_folder + "/generated_outputs/tr_acc.txt") # Loading val loss and acc val_loss = [] val_acc = [] for i in range(nb_val): val_loss.append(np.loadtxt(out_folder + "/generated_outputs/val_" + str(i) + "_loss.txt")) val_acc.append(np.loadtxt(out_folder + "/generated_outputs/val_" + str(i) + "_acc.txt")) # # LOSS PLOT # # Getting maximum values max_loss = np.amax(tr_loss) for i in range(nb_val): if np.amax(val_loss[i]) > max_loss: max_loss = np.amax(val_loss[i]) # Plot train loss and acc plt.plot(x, tr_loss, label="train_loss") # Plot val loss and acc for i in range(nb_val): plt.plot(x, val_loss[i], label="val_" + str(i) + "_loss") plt.ylabel("Loss") plt.xlabel("Epoch") plt.title("Evolution of the loss function") plt.axis([0, nb_epoch - 1, 0, max_loss + 1]) plt.legend() plt.savefig(out_folder + "/generated_outputs/loss.png") # Clear plot plt.gcf().clear() # # ACC PLOT # # Plot train loss and acc plt.plot(x, tr_acc, label="train_acc") # Plot val loss and acc for i in range(nb_val): plt.plot(x, val_acc[i], label="val_" + str(i) + "_acc") plt.ylabel("Accuracy") plt.xlabel("Epoch") plt.title("Evolution of the accuracy") plt.axis([0, nb_epoch - 1, 0, 1]) plt.legend() plt.savefig(out_folder + "/generated_outputs/acc.png") print("OK") # Replace the nth pattern in a string def nth_replace_string(s, sub, repl, nth): find = s.find(sub) # if find is not p1 we have found at least one match for the substring i = find != -1 # loop util we find the nth or we find no match while find != -1 and i != nth: # find + 1 means we start at the last match start index + 1 find = s.find(sub, find + 1) i += 1 # if i is equal to nth we found nth matches so replace if i == nth: return s[:find] + repl + s[find + len(sub) :] return s def change_lr_cfg(cfg_file, lr, ep): config = configparser.ConfigParser() config.read(cfg_file) field = "arch_lr" for lr_arch in lr.keys(): config.set(lr_arch, field, str(lr[lr_arch][ep])) # Write cfg_file_chunk with open(cfg_file, "w") as configfile: config.write(configfile) def shift(arr, num, fill_value=np.nan): if num >= 0: return np.concatenate((np.full(num, fill_value), arr[:-num])) else: return np.concatenate((arr[-num:], np.full(-num, fill_value))) def expand_str_ep(str_compact, type_inp, N_ep, split_elem, mult_elem): lst_out = [] str_compact_lst = str_compact.split(split_elem) for elem in str_compact_lst: elements = elem.split(mult_elem) if type_inp == "int": try: int(elements[0]) except ValueError: sys.stderr.write('The string "%s" must contain integers. Got %s.\n' % (str_compact, elements[0])) sys.exit(0) if type_inp == "float": try: float(elements[0]) except ValueError: sys.stderr.write('The string "%s" must contain floats. Got %s.\n' % (str_compact, elements[0])) sys.exit(0) if len(elements) == 2: try: int(elements[1]) lst_out.extend([elements[0] for i in range(int(elements[1]))]) except ValueError: sys.stderr.write('The string "%s" must contain integers. Got %s\n' % (str_compact, elements[1])) sys.exit(0) if len(elements) == 1: lst_out.append(elements[0]) if len(str_compact_lst) == 1 and len(elements) == 1: lst_out.extend([elements[0] for i in range(N_ep - 1)]) # Final check if len(lst_out) != N_ep: sys.stderr.write( 'The total number of elements specified in the string "%s" is equal to %i not equal to the total number of epochs %s.\n' % (str_compact, len(lst_out), N_ep) ) sys.exit(0) return lst_out
110,615
36.598912
206
py
pytorch-kaldi-gan
pytorch-kaldi-gan-master/train_gan.py
########################################################## # pytorch-kaldi-gan # Walter Heymans # North West University # 2020 ########################################################## import sys import configparser import os import time import numpy import numpy as np import random import torch import torch.nn.functional as functional from torch.optim.optimizer import Optimizer import gan_networks import itertools from shutil import copyfile import math import matplotlib.pyplot as plt import weights_and_biases as wandb import importlib import warnings warnings.filterwarnings("ignore", '', UserWarning) def print_version_info(): print("") print("".center(40, "#")) print(" Pytorch-Kaldi-GAN ".center(38, " ").center(40, "#")) print(" Walter Heymans ".center(38, " ").center(40, "#")) print(" North West University ".center(38, " ").center(40, "#")) print(" 2020 ".center(38, " ").center(40, "#")) print("".center(40, "#"), end="\n\n") def save_tensor_list_to_png(array, titles=[], fig_name="tensor.png"): plt.figure(figsize=(8, 6), dpi=300) for i in range(1, len(array) + 1): plt.subplot(len(array), 1, i) if len(array) == 4 and i <= 2: graph_colour = "b" elif len(array) == 4: graph_colour = "r" elif i == 2: graph_colour = "r" else: graph_colour = "b" plt.plot(array[i - 1].detach().numpy(), graph_colour) if len(titles) == len(array): plt.title(titles[i - 1]) plt.tight_layout() plt.savefig(fig_name) plt.close() def format_time(time_in_seconds): hours_remaining = math.floor(time_in_seconds / 3600) minutes_remaining = math.floor(time_in_seconds / 60) - (hours_remaining * 60) seconds_remaining = math.floor(time_in_seconds) - (minutes_remaining * 60) - (hours_remaining * 3600) if hours_remaining > 0: return "{}h {}m {}s ".format(hours_remaining, minutes_remaining, seconds_remaining) elif minutes_remaining > 0: return "{}m {}s ".format(minutes_remaining, seconds_remaining) else: return "{}s ".format(seconds_remaining) def get_labels(bs, label): return torch.ones((bs, 1)) * label def get_pearson_correlation(tensor1, tensor2): from scipy.stats import pearsonr output1 = tensor1.detach().cpu().numpy() output2 = tensor2.detach().cpu().numpy() if output1.shape == output2.shape: # calculate Pearson's correlation if len(output1.shape) > 1: correlation = 0 for i in range(output1.shape[0]): try: temp_corr, _ = pearsonr(output1[i], output2[i]) except: temp_corr = 0 correlation += temp_corr if output1.shape[0] > 0: correlation = correlation / output1.shape[0] else: correlation, _ = pearsonr(output1, output2) return correlation else: return 0 def get_mean_squared_error(tensor1, tensor2): output1 = tensor1.detach().cpu() output2 = tensor2.detach().cpu() if output1.shape == output2.shape: if len(output1.shape) > 1: error = 0 for i in range(output1.shape[0]): error += torch.mean(torch.abs(torch.abs(output1) - torch.abs(output2))) if output1.shape[0] > 0: error = error / output1.shape[0] else: error = torch.mean(torch.abs(torch.abs(output1) - torch.abs(output2))) return error.numpy() else: return 0 def get_g_performance(clean, noisy, generated): ''' Performance metric using Pearson correlation, mean squared error and L1 loss. Metric is comparing generator relative to noisy signal. Higher is better. ''' l1_loss_noisy = torch.nn.functional.l1_loss(clean, noisy).item() l1_loss_gen = torch.nn.functional.l1_loss(clean, generated).item() r_clean_noisy = get_pearson_correlation(clean, noisy) r_clean_gen = get_pearson_correlation(clean, generated) mse_clean_noisy = get_mean_squared_error(clean, noisy) mse_clean_gen = get_mean_squared_error(clean, generated) l1_performance = l1_loss_noisy - l1_loss_gen r_performance = r_clean_gen - r_clean_noisy mse_performance = mse_clean_noisy - mse_clean_gen performance_metric = r_performance + mse_performance + l1_performance return performance_metric def compute_gradient_penalty(D, real_samples, fake_samples): Tensor = torch.cuda.FloatTensor from torch.autograd import Variable """Calculates the gradient penalty loss for WGAN GP""" # Random weight term for interpolation between real and fake samples alpha = Tensor(np.random.random((real_samples.size(0), 440))) # Get random interpolation between real and fake samples interpolates = (alpha * real_samples + ((1 - alpha) * fake_samples)).requires_grad_(True) d_interpolates = D(interpolates) fake = Variable(Tensor(real_samples.shape[0], 1).fill_(1.0), requires_grad=False) # Get gradient w.r.t. interpolates gradients = torch.autograd.grad( outputs=d_interpolates, inputs=interpolates, grad_outputs=fake, create_graph=True, retain_graph=True, only_inputs=True, )[0] gradients = gradients.view(gradients.size(0), -1) gradient_penalty = ((gradients.norm(2, dim=1) - 1) ** 2).mean() return gradient_penalty script_start_time = time.time() print_version_info() # Reading global cfg file (first argument-mandatory file) cfg_file = sys.argv[1] if not (os.path.exists(cfg_file)): sys.stderr.write("ERROR: The config file %s does not exist!\n" % (cfg_file)) sys.exit(0) else: config = configparser.ConfigParser() config.read(cfg_file) # Output folder creation out_folder = config["exp"]["out_folder"] if not os.path.exists(out_folder): os.makedirs(out_folder) # Copy the global cfg file into the output folder cfg_file = out_folder + "/conf.cfg" with open(cfg_file, "w") as configfile: config.write(configfile) # Read hyper-parameters from config file seed = int(config['hyperparameters']['seed']) max_epochs = int(config['hyperparameters']['max_epochs']) batch_size = int(config['hyperparameters']['batch_size']) lr_g = float(config['hyperparameters']['lr_g']) lr_d = float(config['hyperparameters']['lr_d']) try: d_updates = int(config['hyperparameters']['d_updates']) except KeyError: d_updates = 1 real_label = float(config['hyperparameters']['real_label']) criterion = str(config['hyperparameters']['criterion']) optimizer = str(config['hyperparameters']['optimizer']) cycle_consistency_lambda = int(config['hyperparameters']['cycle_consistency_lambda']) acoustic_model_lambda = float(config['hyperparameters']['acoustic_model_lambda']) gp_lambda = int(config['hyperparameters']['gp_lambda']) try: l1_lambda = int(config['hyperparameters']['l1_lambda']) l2_lambda = int(config['hyperparameters']['l2_lambda']) except KeyError: pass if config.getboolean("exp", "use_cuda"): try: cuda_device = int(config['exp']['cuda_device']) except ValueError: cuda_device = 'cpu' else: cuda_device = 'cpu' if config["wandb"]["wandb"] == "True": wandb_on = True else: wandb_on = False torch.manual_seed(seed = seed) random.seed(seed) clean_dataset_path = str(config['datasets']['clean_dataset']) noisy_dataset_path = str(config['datasets']['noisy_dataset']) valid_dataset_path = str(config['datasets']['valid_dataset']) cw_left = int(config['datasets']['cw_left']) cw_right = int(config['datasets']['cw_right']) frames_per_sample = cw_left + cw_right + 1 double_features = False try: if config["hyperparameters"]["double_features"] == "True": double_features = True except KeyError: pass early_stopping = False try: if config["hyperparameters"]["early_stopping"] == "True": early_stopping = True except KeyError: pass train_d_with_noisy = False try: if config["hyperparameters"]["train_d_with_noisy"] == "True": train_d_with_noisy = True except KeyError: pass print("@ Progress: Reading config complete\n") def print_settings(): print_width = 64 print(" Hyper-parameters ".center(print_width, "=")) print("# Seed:\t\t\t", seed) print("# Epochs:\t\t", max_epochs) print("# Batch size:\t\t", batch_size) print("# Learning rate G:\t", lr_g) print("# Learning rate D:\t", lr_d) print("# Acoustic model lambda:", acoustic_model_lambda) print("# Gradient penalty lambda:", gp_lambda) print("# Real label:\t\t", real_label) print("# Criterion:\t\t", criterion) print("# Optimizer:\t\t", optimizer) print("# Cuda device:\t\t", cuda_device) print("# Weights and Biases:\t", wandb_on) print("# Output directory:\t", out_folder) print("# Double features:\t", double_features) print("# Early stopping:\t", early_stopping) print("=".center(print_width, "="), end = "\n\n") print_settings() class Dataset(torch.utils.data.Dataset): 'Characterizes a dataset for PyTorch' def __init__(self, dataset_path_clean, dataset_path_noisy, chunk): self.validation_set = False if not os.path.exists(dataset_path_noisy) or dataset_path_noisy == "": self.validation_set = True 'Initialization' self.dataset_path_clean = dataset_path_clean files = sorted(os.listdir(self.dataset_path_clean)) if chunk <= len(files): self.dataset_object = torch.load(os.path.join(self.dataset_path_clean, ("chunk_" + str(chunk) + ".pt")), map_location = 'cpu') clean_length = int(math.floor(self.dataset_object.shape[0] / frames_per_sample)) if not self.validation_set: # Noisy dataset self.dataset_path_noisy = dataset_path_noisy files = sorted(os.listdir(self.dataset_path_noisy)) if chunk <= len(files): self.dataset_object_noisy = torch.load(os.path.join(self.dataset_path_noisy, ("chunk_" + str(chunk) + ".pt")), map_location = 'cpu') noisy_lenght = int(math.floor(self.dataset_object_noisy.shape[0] / frames_per_sample)) self.dataset_len = min([clean_length, noisy_lenght]) else: self.dataset_len = clean_length def __len__(self): 'Denotes the total number of samples' return self.dataset_len def __getitem__(self, index): 'Generates one sample of data' for frame in range(frames_per_sample): label = self.dataset_object[index,-1] if frame == 0: clean = self.dataset_object[index + frame, :40] else: clean = torch.cat((clean, self.dataset_object[index + frame, :40]), dim = 0) if not self.validation_set: for frame in range(frames_per_sample): label_noisy = self.dataset_object_noisy[index, -1] if frame == 0: noisy = self.dataset_object_noisy[index + frame, :40] else: noisy = torch.cat((noisy, self.dataset_object_noisy[index + frame, :40]), dim = 0) return clean, noisy, label, label_noisy else: return clean, label def getbatch(self, index, batch_size): clean, noisy, _, _ = self.__getitem__(index) clean = torch.unsqueeze(clean, dim = 0) noisy = torch.unsqueeze(noisy, dim = 0) for bs in range(batch_size-1): tempclean, tempnoisy, _, _ = self.__getitem__(index+bs+1) tempclean = torch.unsqueeze(tempclean, dim = 0) tempnoisy = torch.unsqueeze(tempnoisy, dim = 0) clean = torch.cat((clean, tempclean), dim = 0) noisy = torch.cat((noisy, tempnoisy), dim = 0) return clean, noisy number_of_chunks = len(os.listdir(clean_dataset_path)) train_set = Dataset(clean_dataset_path, noisy_dataset_path, 1) train_loader = torch.utils.data.DataLoader(train_set, batch_size = batch_size, shuffle = True, num_workers = 4) validation_set = Dataset(valid_dataset_path, "", 1) valid_loader = torch.utils.data.DataLoader(validation_set, batch_size = batch_size, shuffle = True, num_workers = 4) print("@ Progress: Dataset loaded") if cuda_device != 'cpu': torch.cuda.set_device(cuda_device) print("@ Progress: Cuda device set to", cuda_device) # Create acoustic model acoustic_model_path = str(config["acoustic_model"]["pretrained_file"]) train_with_am = False use_external_model = False try: if str(config["acoustic_model"]["use_external_model"]) == "True": use_external_model = True except KeyError: pass if use_external_model: if os.path.exists(acoustic_model_path): def get_number_hidden_layers(dictionary_keys): layer_count = 0 for key in dictionary_keys: if 'wx' in key: layer_count += 1 layer_count /= 2 return int(layer_count) def get_n_out_dim(dictionary): num_layers = get_number_hidden_layers(dictionary.keys()) last_layer_key = 'wx.' + str(num_layers - 1) + '.weight' for key in dictionary.keys(): if last_layer_key == key: return dictionary[key].shape[0] return 0 try: if cuda_device != 'cpu': if int(config["exp"]["cuda_device"]) == 0: checkpoint_load = torch.load(acoustic_model_path, map_location="cuda:0") elif int(config["exp"]["cuda_device"]) == 1: checkpoint_load = torch.load(acoustic_model_path, map_location="cuda:1") else: checkpoint_load = torch.load(acoustic_model_path, map_location="cpu") N_out_lab_cd = get_n_out_dim(checkpoint_load["model_par"]) # import the class module = importlib.import_module(config["acoustic_model"]["arch_library"]) nn_class = getattr(module, config["acoustic_model"]["arch_class"]) config["acoustic_model"]["dnn_lay"] = config["acoustic_model"]["dnn_lay"].replace('N_out_lab_cd', str(N_out_lab_cd)) if double_features: acoustic_model = nn_class(config["acoustic_model"], int(2 * frames_per_sample * 40)) else: acoustic_model = nn_class(config["acoustic_model"], int(frames_per_sample * 40)) acoustic_model.load_state_dict(checkpoint_load["model_par"]) acoustic_model = acoustic_model.cuda() except RuntimeError: print("Error loading acoustic model! Check that models in config file match.") else: if os.path.exists(acoustic_model_path): def get_number_hidden_layers(dictionary_keys): layer_count = 0 for key in dictionary_keys: if 'wx' in key: layer_count += 1 layer_count /= 2 return int(layer_count) def get_n_out_dim(dictionary): num_layers = get_number_hidden_layers(dictionary.keys()) last_layer_key = 'wx.' + str(num_layers - 1) + '.weight' for key in dictionary.keys(): if last_layer_key == key: return dictionary[key].shape[0] return 0 try: if cuda_device != 'cpu': if int(config["exp"]["cuda_device"]) == 0: checkpoint_load = torch.load(acoustic_model_path, map_location="cuda:0") elif int(config["exp"]["cuda_device"]) == 1: checkpoint_load = torch.load(acoustic_model_path, map_location="cuda:1") else: checkpoint_load = torch.load(acoustic_model_path, map_location="cpu") N_out_lab_cd = get_n_out_dim(checkpoint_load["model_par"]) # import the class module = importlib.import_module(config["acoustic_model"]["arch_library"]) nn_class = getattr(module, config["acoustic_model"]["arch_class"]) config["acoustic_model"]["dnn_lay"] = config["acoustic_model"]["dnn_lay"].replace('N_out_lab_cd', str(N_out_lab_cd)) if double_features: acoustic_model = nn_class(config["acoustic_model"], int(2 * frames_per_sample * 40)) else: acoustic_model = nn_class(config["acoustic_model"], int(frames_per_sample * 40)) acoustic_model.load_state_dict(checkpoint_load["model_par"]) acoustic_model = acoustic_model.cuda() train_with_am = True except RuntimeError: print("Error loading acoustic model! Check that models in config file match.") else: print("Acoustic model path doesnt exist!") # Create networks and optimizers # Create Generator input_dim = train_set.__getitem__(0)[0].shape[0] generator_class = getattr(gan_networks, config["generator"]["arch_name"]) generator = generator_class(input_dim, input_dim, config["generator"]) if config["hyperparameters"]["criterion"] == "cycle": generator_f = generator_class(input_dim, input_dim, config["generator"]) # Create Discriminator discriminator_class = getattr(gan_networks, config["discriminator"]["arch_name"]) discriminator = discriminator_class(input_dim, config["discriminator"]) if config["hyperparameters"]["criterion"] == "cycle": discriminator_h = discriminator_class(input_dim, config["discriminator"]) generator = generator.cuda() discriminator = discriminator.cuda() if config["hyperparameters"]["criterion"] == "cycle": generator_f = generator_f.cuda() discriminator_h = discriminator_h.cuda() # Creating directories directory_g = os.path.join(out_folder, config["gan"]["output_path_g"]) directory_d = os.path.join(out_folder, config["gan"]["output_path_d"]) gan_dir = os.path.dirname(directory_g) if not os.path.exists(gan_dir): os.mkdir(gan_dir) if not os.path.exists(gan_dir + "/images"): os.mkdir(gan_dir + "/images") # Copy pretrained models into directory if it is set try: if str(config["generator"]["pretrained_file"]) != "none": if os.path.exists(str(config["generator"]["pretrained_file"])): copyfile(str(config["generator"]["pretrained_file"]), directory_g) print("Loaded pretrained G.") except KeyError: pass try: if str(config["discriminator"]["pretrained_file"]) != "none": if os.path.exists(str(config["discriminator"]["pretrained_file"])): copyfile(str(config["discriminator"]["pretrained_file"]), directory_d) print("Loaded pretrained D.") except KeyError: pass # Load pretrained models if os.path.exists(directory_g): try: generator.load_state_dict(torch.load(directory_g)) if criterion == "cycle": generator_f.load_state_dict(torch.load(os.path.dirname(directory_g) + "/generator_f.pt")) except RuntimeError: print("Load error loading G, network will be recreated.") if os.path.exists(directory_d): try: discriminator.load_state_dict(torch.load(directory_d)) if criterion == "cycle": discriminator_h.load_state_dict(torch.load(os.path.dirname(directory_d) + "/discriminator_h.pt")) except RuntimeError: print("Load error loading D, network will be recreated.") # Optimizer initialization if config["hyperparameters"]["optimizer"] == "adam": if criterion == "cycle": optimizer_g = torch.optim.Adam(itertools.chain(generator.parameters(), generator_f.parameters()), lr = lr_g) optimizer_d = torch.optim.Adam(discriminator.parameters(), lr = lr_d) optimizer_h = torch.optim.Adam(discriminator_h.parameters(), lr = lr_d) else: optimizer_g = torch.optim.Adam(generator.parameters(), lr = lr_g, betas = (0.5, 0.999), weight_decay = 0.001) optimizer_d = torch.optim.Adam(discriminator.parameters(), lr = lr_d, betas = (0.5, 0.999), weight_decay = 0.001) elif config["hyperparameters"]["optimizer"] == "rmsprop": if criterion == "cycle": optimizer_g = torch.optim.RMSprop(itertools.chain(generator.parameters(), generator_f.parameters()), lr = lr_g) optimizer_d = torch.optim.RMSprop(discriminator.parameters(), lr = lr_d) optimizer_h = torch.optim.RMSprop(discriminator_h.parameters(), lr = lr_d) else: optimizer_g = torch.optim.RMSprop(generator.parameters(), lr = lr_g) optimizer_d = torch.optim.RMSprop(discriminator.parameters(), lr = lr_d) elif config["hyperparameters"]["optimizer"] == "sgd": if criterion == "cycle": optimizer_g = torch.optim.SGD(itertools.chain(generator.parameters(), generator_f.parameters()), lr = lr_g) optimizer_d = torch.optim.SGD(discriminator.parameters(), lr = lr_d) optimizer_h = torch.optim.SGD(discriminator_h.parameters(), lr = lr_d) else: optimizer_g = torch.optim.SGD(generator.parameters(), lr = lr_g) optimizer_d = torch.optim.SGD(discriminator.parameters(), lr = lr_d) # Start training print("\n@ Progress: Starting training") train_start_time = time.time() number_of_batches = len(train_loader) if str(config["wandb"]["wandb"]) == "True": wandb_cfg = wandb.load_cfg_dict_from_yaml(str(config["wandb"]["config"])) # UPDATE config file if Weights and Biases file is different wandb_cfg["max_epochs"] = max_epochs wandb_cfg["seed"] = seed wandb_cfg["batch_size"] = batch_size wandb_cfg["lr_g"] = lr_g wandb_cfg["lr_d"] = lr_d wandb_cfg["criterion"] = criterion wandb_cfg["optimizer"] = optimizer wandb_cfg["generator"] = str(config["generator"]["arch_name"]) wandb_cfg["discriminator"] = str(config["discriminator"]["arch_name"]) wandb_cfg["dataset"] = str(config["exp"]["dataset_name"]) wandb_cfg["acoustic_model_lambda"] = acoustic_model_lambda wandb_cfg["cycle_consistency_lambda"] = cycle_consistency_lambda wandb_cfg["gp_lambda"] = gp_lambda wandb_details = os.path.join(out_folder, "wandb_details.txt") if not os.path.exists(wandb_details): wandb_details_file = open(wandb_details, "w") wandb.initialize_wandb(project = str(config["wandb"]["project"]), config = wandb_cfg, directory = out_folder, resume = False) try: wandb_details_file.write(wandb.get_run_id() + '\n') wandb_details_file.write(wandb.get_run_name()) except TypeError: pass wandb_details_file.close() else: wandb_details_file = open(wandb_details, "r") try: file_content = wandb_details_file.read().splitlines() wandb_run_id = file_content[0] wandb_run_name = file_content[1] except IndexError: pass wandb_details_file.close() try: wandb.initialize_wandb(project = str(config["wandb"]["project"]), config = wandb_cfg, directory = out_folder, resume = True, identity = wandb_run_id, name = wandb_run_name) except NameError: wandb.initialize_wandb(project = str(config["wandb"]["project"]), config = wandb_cfg, directory = out_folder, resume = True) def create_log_file(): if not os.path.exists(os.path.join(out_folder, 'log.log')): log_file = open(os.path.join(out_folder, 'log.log'), "w") log_file.close() def update_log_file(text_str): log_file = open(os.path.join(out_folder, 'log.log'), "a") log_file.write(text_str + "\n") log_file.close() def get_last_trained_epoch(): log_file = open(os.path.join(out_folder, 'log.log'), "r") file_lines = log_file.readlines() log_file.close() if len(file_lines) > 0: epoch_last, chunk_last = (file_lines[-1].replace("epoch_", "")).split("_") return int(epoch_last), int(chunk_last) else: return 0, 0 def validate_generator_results(): with torch.no_grad(): number_of_valid_batches = len(valid_loader) validation_loss = 0 correct = 0 total_samples = 0 for valid_batch, valid_label_batch in valid_loader: valid_batch = valid_batch.cuda() valid_label_batch = valid_label_batch.cuda() if criterion == "am-gan": gen_output, _ = generator(valid_batch) else: gen_output = generator(valid_batch) if g_output.shape[0] > 1: if double_features: am_evaluation = acoustic_model(torch.cat((valid_batch, gen_output), dim = 1)) else: am_evaluation = acoustic_model(gen_output) validation_loss += functional.nll_loss(am_evaluation, valid_label_batch.long()).item() pred = am_evaluation.data.max(1, keepdim = True)[1] correct += torch.sum(pred.eq(valid_label_batch.data.view_as(pred))).item() total_samples += valid_label_batch.shape[0] validation_loss = validation_loss / number_of_valid_batches validation_error = 1 - (correct / total_samples) return validation_loss, validation_error def check_discriminator_classification(): with torch.no_grad(): v_set = Dataset(clean_dataset_path, noisy_dataset_path, chunk) v_loader = torch.utils.data.DataLoader(v_set, batch_size=batch_size, shuffle=True, num_workers=4) nob = len(v_loader) validation_loss = 0 correct = 0 total_samples = 0 for v_clean_batch, v_noisy_batch, _, _ in v_loader: nob += 1 v_clean_batch, v_noisy_batch = v_clean_batch.cuda(), v_noisy_batch.cuda() v_input = torch.cat((v_clean_batch, v_noisy_batch), dim=0) v_target = torch.cat((torch.ones(v_clean_batch.shape[0]).long(), torch.zeros(v_noisy_batch.shape[0]).long()), dim=0).to(cuda_device) v_output = discriminator(v_input) validation_loss += functional.cross_entropy(v_output, v_target).item() pred = v_output.data.max(1, keepdim=True)[1] correct += torch.sum(pred.eq(v_target.data.view_as(pred))).item() total_samples += v_target.shape[0] validation_loss = validation_loss / nob validation_error = 1 - (correct / total_samples) return validation_loss, validation_error create_log_file() if wandb_on: wandb.quick_log("status", "training", commit = False) epochs_skipped = 0 lowest_valid_error = 1 early_stopping_epoch = 0 file_loss = open(os.path.join(out_folder, "losses"), "w") file_loss.close() for epoch in range(1, max_epochs+1): # Check if epoch has been processed last_ep, last_ch = get_last_trained_epoch() if (epoch < last_ep) or (last_ep == epoch and last_ch == number_of_chunks): print("") print(" Previously completed epoch: {} ".format(epoch).center(64, "#")) epochs_skipped += 1 continue if wandb_on: wandb.quick_log("epoch", epoch, commit = False) # Training epoch_start_time = time.time() print("") print(" Optimizing epoch: {}/{} ".format(epoch, max_epochs).center(64, "#")) for chunk in range(1, number_of_chunks + 1): # Check if chunk has been processed if (last_ep == epoch) and (chunk <= last_ch): continue if wandb_on: wandb.quick_log("chunk", chunk, commit = True) current_batch = 0 g_loss = 0 d_loss = 0 tot_am_loss = 0 train_set = Dataset(clean_dataset_path, noisy_dataset_path, chunk) train_loader = torch.utils.data.DataLoader(train_set, batch_size = batch_size, shuffle = True, num_workers = 6) number_of_batches = len(train_loader) print(" Chunk: {}/{} ".format(chunk, number_of_chunks).center(64, "-")) for clean_batch, noisy_batch, label_batch, label_noisy_batch in train_loader: current_batch += 1 # Transfer to GPU clean_batch, noisy_batch = clean_batch.cuda(), noisy_batch.cuda() label_batch, label_noisy_batch = label_batch.cuda(), label_noisy_batch.cuda() d_clean_batch = clean_batch d_noisy_batch = noisy_batch if d_clean_batch.shape[0] > 1 and d_noisy_batch.shape[0] > 1: for k in range(d_updates): # TRAIN DISCRIMINATOR optimizer_d.zero_grad() d_output_clean = discriminator(d_clean_batch) if criterion == "am-gan": g_output, am_gan_output = generator(d_noisy_batch) g_output = g_output.detach() else: g_output = generator(d_noisy_batch).detach() d_output_g = discriminator(g_output) real_labels = get_labels(d_clean_batch.shape[0], real_label).cuda() fake_labels = get_labels(d_clean_batch.shape[0], 0).cuda() if criterion == "bce" or criterion == "bce-l1" or criterion == "bce-l2" or criterion == "bce-all" or criterion == "am-gan": loss_clean = functional.binary_cross_entropy(d_output_clean, real_labels) loss_noisy = functional.binary_cross_entropy(d_output_g, fake_labels) loss_discriminator = loss_clean + loss_noisy loss_discriminator.backward() optimizer_d.step() d_loss += loss_discriminator.item() file_loss = open(os.path.join(out_folder, "losses"), "a") file_loss.write(str(epoch) + "," + str(chunk) + "," + str(loss_discriminator.item()) + ",") file_loss.close() elif criterion == "wgan": if gp_lambda > 0: gp_loss = compute_gradient_penalty(discriminator, d_clean_batch, g_output) else: gp_loss = 0 if train_d_with_noisy: loss_discriminator = - torch.mean(d_output_clean) + torch.mean(d_output_g) + (0.1*torch.mean(discriminator(d_noisy_batch))) + (gp_lambda * gp_loss) else: loss_discriminator = - torch.mean(d_output_clean) + torch.mean(d_output_g) + (gp_lambda * gp_loss) loss_discriminator.backward() optimizer_d.step() d_loss += loss_discriminator.item() temp_d_loss = - torch.mean(d_output_clean) + torch.mean(d_output_g) if gp_lambda > 0: file_loss = open(os.path.join(out_folder, "losses"), "a") file_loss.write(str(epoch) + "," + str(chunk) + "," + str(temp_d_loss.item()) + "," + str(gp_loss.item()) + ",") file_loss.close() elif criterion == "cycle": optimizer_h.zero_grad() h_output_noisy = discriminator_h(d_noisy_batch) # H_f output of noisy signal h_output_f = discriminator_h(generator_f(d_clean_batch)) # H_f output of F criterion_GAN = torch.nn.MSELoss() criterion_GAN = criterion_GAN.cuda() # TRAIN Discriminator D # Real loss loss_real = criterion_GAN(d_output_clean, real_labels) # Fake loss loss_fake = criterion_GAN(d_output_g, fake_labels) # Total loss loss_d = loss_real + loss_fake loss_d.backward() optimizer_d.step() # TRAIN Discriminator H # Real loss loss_real = criterion_GAN(h_output_noisy, real_labels) # Fake loss loss_fake = criterion_GAN(h_output_f, fake_labels) # Total loss loss_h = loss_real + loss_fake loss_h.backward() optimizer_h.step() d_loss += (loss_d.item() + loss_h.item()) / 2 if k < (d_updates - 1): d_clean_batch, d_noisy_batch = train_set.getbatch(random.randint(0, train_set.__len__() - batch_size - 1), batch_size) d_clean_batch = d_clean_batch.to(cuda_device) d_noisy_batch = d_noisy_batch.to(cuda_device) # TRAIN GENERATOR optimizer_g.zero_grad() if criterion == "am-gan": g_output, am_gan_output = generator(noisy_batch) else: g_output = generator(noisy_batch) d_verdict = discriminator(g_output) am_loss = 0 if train_with_am: if g_output.shape[0] > 1: if double_features: am_output = acoustic_model(torch.cat((noisy_batch, g_output), dim = 1)) else: am_output = acoustic_model(g_output) am_loss = functional.nll_loss(am_output, label_noisy_batch.long()) f = open(os.path.join(out_folder, "am_loss.txt"), 'a') f.writelines(str(am_loss)) f.close() tot_am_loss += am_loss.item() else: am_loss = 0 elif use_external_model: if g_output.shape[0] > 1: am_output = acoustic_model(g_output) numpy_output = am_output.detach().cpu().numpy() imported_am_output = torch.from_numpy(numpy_output).cuda() am_loss = functional.nll_loss(imported_am_output, label_noisy_batch.long()) f = open(os.path.join(out_folder, "am_loss.txt"), 'a') f.writelines(str(am_loss)) f.close() tot_am_loss += am_loss.item() else: am_loss = 0 if criterion == "bce": gen_labels = get_labels(clean_batch.shape[0], real_label).cuda() bce_loss = functional.binary_cross_entropy(d_verdict, gen_labels) loss_generator = bce_loss + (acoustic_model_lambda * am_loss) loss_generator.backward() optimizer_g.step() if am_loss > 0: g_loss += loss_generator.item() - (acoustic_model_lambda * am_loss.item()) file_loss = open(os.path.join(out_folder, "losses"), "a") file_loss.write(str(bce_loss.item()) + "," + str(am_loss.item()) + "\n") file_loss.close() elif criterion == "wgan": loss_generator = -torch.mean(d_verdict) + (acoustic_model_lambda * am_loss) loss_generator.backward() optimizer_g.step() if am_loss > 0: g_loss += loss_generator.item() - (acoustic_model_lambda * am_loss.item()) file_loss = open(os.path.join(out_folder, "losses"), "a") temp_g_loss = -torch.mean(d_verdict) file_loss.write(str(temp_g_loss.item()) + "," + str(am_loss.item()) + "\n") file_loss.close() elif criterion == "cycle": criterion_GAN = torch.nn.MSELoss() criterion_cycle = torch.nn.L1Loss() criterion_identity = torch.nn.L1Loss() criterion_GAN = criterion_GAN.cuda() criterion_cycle = criterion_cycle.cuda() criterion_identity = criterion_identity.cuda() f_verdict = discriminator_h(generator_f(clean_batch)) # TRAIN CYCLE GENERATORS # GAN loss loss_GAN_g = criterion_GAN(d_verdict, real_labels) loss_GAN_f = criterion_GAN(f_verdict, real_labels) loss_GAN = (loss_GAN_g + loss_GAN_f) / 2 # Cycle loss cycle_input_g = torch.unsqueeze(generator_f(clean_batch), dim = 1).cuda() cycle_input_g = torch.cat((cycle_input_g, torch.randn(cycle_input_g.shape).cuda()), dim = 1) cycle_input_f = torch.unsqueeze(generator(noisy_batch), dim = 1).cuda() cycle_input_f = torch.cat((cycle_input_f, torch.randn(cycle_input_f.shape).cuda()), dim = 1) recov_A = generator(generator_f(clean_batch)) loss_cycle_A = criterion_cycle(recov_A, clean_batch) recov_B = generator_f(generator(noisy_batch)) loss_cycle_B = criterion_cycle(recov_B, noisy_batch) loss_cycle = (loss_cycle_A + loss_cycle_B) / 2 # Total loss loss_generator = loss_GAN + (cycle_consistency_lambda * loss_cycle) + (acoustic_model_lambda * am_loss) loss_generator.backward() optimizer_g.step() g_loss += loss_generator.item() elif criterion == "am-gan": gen_labels = get_labels(clean_batch.shape[0], real_label).cuda() bce_loss = functional.binary_cross_entropy(d_verdict, gen_labels) am_gan_loss = functional.nll_loss(am_gan_output, label_noisy_batch.long()) loss_generator = bce_loss + (acoustic_model_lambda * am_gan_loss) + (acoustic_model_lambda * am_loss) loss_generator.backward() optimizer_g.step() g_loss += loss_generator.item() # Print end of batch results print("Processing batch", current_batch, "/", number_of_batches, "\r", end = '') try: am_loss = am_loss.item() except: pass print("\nD-loss:\t %.4f | G-loss:\t %.4f | AM-loss:\t %.4f" % (round(d_loss / current_batch, 4), round(g_loss / current_batch, 4), round(tot_am_loss / current_batch, 4))) f = open(os.path.join(out_folder, "performance.txt"), 'a') f.writelines(["Epoch " + str(epoch) + " Chunk: " + str(chunk), "\nD-loss:\t %.4f | G-loss:\t %.4f | AM-loss:\t %.4f\n" % (round(d_loss / current_batch, 4), round(g_loss / current_batch, 4), round(tot_am_loss / current_batch, 4))]) f.close() if wandb_on: wandb.quick_log("d-loss", (d_loss / current_batch), commit = False) wandb.quick_log("g-loss", (g_loss / current_batch), commit = False) if train_with_am: wandb.quick_log("am-loss", (tot_am_loss / current_batch), commit = False) torch.save(generator.state_dict(), directory_g) torch.save(discriminator.state_dict(), directory_d) if criterion == "cycle": torch.save(generator_f.state_dict(), os.path.dirname(directory_g) + "/generator_f.pt") torch.save(discriminator_h.state_dict(), os.path.dirname(directory_d) + "/discriminator_h.pt") if config["gan"]["save_figures"] == "True": figure_name = out_folder + '/gan/images/e' + str(epoch) + 'c' + str(chunk) + '.png' with torch.no_grad(): numpyarr = [clean_batch[0].cpu(), noisy_batch[0].cpu(), g_output[0].cpu()] titles = ["Clean", "Encoded", "Generator"] save_tensor_list_to_png(numpyarr, titles, figure_name) update_log_file('epoch_' + str(epoch) + '_' + str(chunk)) print(" ".center(30, " "), end = '\r') if train_with_am: print("") print(" Validation ".center(64, "-")) valid_loss, valid_error = validate_generator_results() print("Validation-loss: %.4f | Validation-error: %.4f" % (valid_loss, valid_error)) f = open(os.path.join(out_folder, "performance.txt"), 'a') f.writelines(["\nValidation\n", "Validation-loss: %.4f | Validation-error: %.4f\n" % (valid_loss, valid_error)]) f.close() if early_stopping: if valid_error <= lowest_valid_error: torch.save(generator.state_dict(), os.path.dirname(directory_g) + "/generator_es.pt") torch.save(discriminator.state_dict(), os.path.dirname(directory_d) + "/discriminator_es.pt") lowest_valid_error = valid_error early_stopping_epoch = epoch if wandb_on: wandb.quick_log("early-stopping-epoch", early_stopping_epoch, commit=False) wandb.quick_log("early-stopping-valid-error", lowest_valid_error, commit=False) if wandb_on: wandb.quick_log("valid-loss", valid_loss, commit = False) wandb.quick_log("valid-error", valid_error, commit = False) # Print end of epoch summary epoch_end_time = time.time() ave_epoch_time = (epoch_end_time - train_start_time) / (epoch - epochs_skipped) epochs_remaining = max_epochs - (epoch - epochs_skipped) estimated_time_left = ave_epoch_time * epochs_remaining d_loss = d_loss / number_of_batches g_loss = g_loss / number_of_batches print(" Epoch {} completed in: {} | ETA: {} ".format(epoch, format_time(epoch_end_time - epoch_start_time), format_time(estimated_time_left)).center(64, "#")) f = open(os.path.join(out_folder, "performance.txt"), 'a') f.writelines("\nEpoch {} completed in: {} | ETA: {} \n".format(epoch, format_time(epoch_end_time - epoch_start_time), format_time(estimated_time_left))) f.close() if wandb_on: wandb.quick_log("ETA", format_time(estimated_time_left), commit = False) wandb.quick_log("epoch_time", format_time(epoch_end_time - epoch_start_time), commit = False) if early_stopping: print("Early-stopping | Epoch: %d | Validation-error: %.4f" % (early_stopping_epoch, lowest_valid_error)) f = open(os.path.join(out_folder, "performance.txt"), 'a') f.writelines("\nEarly-stopping | Epoch: %d | Validation-error: %.4f\n\n" % (early_stopping_epoch, lowest_valid_error)) f.close() print("\n@ Progress: Training complete\n") if wandb_on: wandb.quick_log("status", "complete", commit = True) print("Completed in:", format_time(time.time() - script_start_time))
44,242
36.621599
191
py
pytorch-kaldi-gan
pytorch-kaldi-gan-master/gan_networks.py
import torch import torch.nn as nn from distutils.util import strtobool from torch.nn.utils import spectral_norm import math class LayerNorm(nn.Module): def __init__(self, features, eps=1e-6): super(LayerNorm, self).__init__() self.gamma = nn.Parameter(torch.ones(features)) self.beta = nn.Parameter(torch.zeros(features)) self.eps = eps def forward(self, x): mean = x.mean(-1, keepdim=True) std = x.std(-1, keepdim=True) return self.gamma * (x - mean) / (std + self.eps) + self.beta def act_fun(act_type): if act_type == "relu": return nn.ReLU() if act_type == "tanh": return nn.Tanh() if act_type == "sigmoid": return nn.Sigmoid() if act_type == "leaky_relu": return nn.LeakyReLU(0.2) if act_type == "elu": return nn.ELU() if act_type == "softmax": return nn.LogSoftmax(dim=1) if act_type == "linear": return nn.LeakyReLU(1) # initializzed like this, but not used in forward! def create_module_list(input_dim, output_dim, cfg): dnn_lay = list(map(int, cfg["dnn_lay"].split(","))) dnn_drop = list(map(float, cfg["dnn_drop"].split(","))) dnn_batchnorm = list(map(strtobool, cfg["dnn_batchnorm"].split(","))) dnn_act = cfg["dnn_act"].split(",") dnn_lay.append(output_dim) layers = nn.ModuleList([]) N_dnn_lay = len(dnn_lay) current_input = input_dim add_bias = True for i in range(N_dnn_lay): # Linear operations layers.append(nn.Linear(current_input, dnn_lay[i], bias=add_bias)) add_bias = False # batch norm if dnn_batchnorm[i]: layers.append(nn.BatchNorm1d(dnn_lay[i], momentum=0.05)) # activation if dnn_act[i] != "linear": layers.append(act_fun(dnn_act[i])) # dropout if dnn_drop[i] > 0: layers.append(nn.Dropout(p=dnn_drop[i])) current_input = dnn_lay[i] return layers class Block_Encode(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, stride, dropout): super().__init__() self.block = nn.Sequential( nn.Conv1d(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, stride=stride, padding=int((kernel_size - 1) / 2)), nn.ReLU(), nn.Dropout(dropout), ) def forward(self, x): return self.block(x) class Block_Decode(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, stride, dropout): super().__init__() self.block = nn.Sequential( nn.ConvTranspose1d(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, stride=stride, padding=int(math.ceil((kernel_size - 2) / 2))), nn.ReLU(), nn.Dropout(dropout), ) def forward(self, x): return self.block(x) class Block_Encode_BN(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, stride, dropout): super().__init__() self.block = nn.Sequential( nn.Conv1d(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, stride=stride, padding=int((kernel_size - 1) / 2)), nn.BatchNorm1d(out_channels), nn.ReLU(), nn.Dropout(dropout), ) def forward(self, x): return self.block(x) class Block_Decode_BN(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, stride, dropout): super().__init__() self.block = nn.Sequential( nn.ConvTranspose1d(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, stride=stride, padding=int(math.ceil((kernel_size - 2) / 2))), nn.BatchNorm1d(out_channels), nn.ReLU(), nn.Dropout(dropout), ) def forward(self, x): return self.block(x) class Block_Encode_SN(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, stride, dropout): super().__init__() self.block = nn.Sequential( spectral_norm(nn.Conv1d(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, stride=stride, padding=int((kernel_size - 1) / 2))), nn.ReLU(), nn.Dropout(dropout), ) def forward(self, x): return self.block(x) class Block_Decode_SN(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, stride, dropout): super().__init__() self.block = nn.Sequential( spectral_norm(nn.ConvTranspose1d(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, stride=stride, padding=int(math.ceil((kernel_size - 2) / 2)))), nn.ReLU(), nn.Dropout(dropout), ) def forward(self, x): return self.block(x) class Discriminator_BCE(nn.Module): def __init__(self, inp_dim, cfg): super(Discriminator_BCE, self).__init__() self.input_dim = inp_dim self.output_dim = 1 leaky_alpha = 0.2 self.block = nn.Sequential( nn.Conv1d(in_channels=1, out_channels=16, kernel_size=41, padding=20, stride=1), # nn.BatchNorm1d(16), nn.MaxPool1d(kernel_size=2, stride=2), nn.LeakyReLU(leaky_alpha, inplace=True), nn.Dropout(0.3), nn.Conv1d(in_channels=16, out_channels=16, kernel_size=13, padding=6, stride=1), # nn.BatchNorm1d(16), nn.MaxPool1d(kernel_size=2, stride=2), nn.LeakyReLU(leaky_alpha, inplace=True), nn.Dropout(0.3), nn.Conv1d(in_channels=16, out_channels=32, kernel_size=13, padding=6, stride=1), nn.MaxPool1d(kernel_size=2, stride=2), nn.LeakyReLU(leaky_alpha, inplace=True), nn.Conv1d(in_channels=32, out_channels=32, kernel_size=13, padding=6, stride=1), nn.MaxPool1d(kernel_size=2, stride=2), nn.LeakyReLU(leaky_alpha, inplace=True), nn.Conv1d(in_channels=32, out_channels=64, kernel_size=13, padding=6, stride=1), nn.MaxPool1d(kernel_size=2, stride=2), nn.LeakyReLU(leaky_alpha, inplace=True), nn.Conv1d(in_channels=64, out_channels=64, kernel_size=13, padding=6, stride=1), nn.MaxPool1d(kernel_size=2, stride=2), nn.LeakyReLU(leaky_alpha, inplace=True), nn.Conv1d(in_channels=64, out_channels=128, kernel_size=13, padding=6, stride=1), nn.MaxPool1d(kernel_size=2, stride=2), nn.LeakyReLU(leaky_alpha, inplace=True), nn.Conv1d(in_channels=128, out_channels=128, kernel_size=13, padding=6, stride=1), # nn.BatchNorm1d(128), nn.MaxPool1d(kernel_size=2, stride=2), nn.LeakyReLU(leaky_alpha, inplace=True), ) self.out_block = nn.Sequential( nn.Linear(128, self.output_dim), nn.Sigmoid(), ) def forward(self, x): x = self.block(x.view(-1, 1, self.input_dim)) x = self.out_block(x.view(-1, 128)) return x def create_conv_module_list(input_dim, output_dim, type, cfg): conv_features = list(map(int, cfg["conv_features"].replace(" ", "").split(","))) conv_kernals = list(map(int, cfg["conv_kernals"].replace(" ", "").split(","))) conv_dropout = list(map(float, cfg["conv_dropout"].replace(" ", "").split(","))) conv_batchnorm = list(map(str, cfg["conv_batchnorm"].replace(" ", "").split(","))) conv_act = list(map(str, cfg["conv_act"].replace(" ", "").split(","))) layers = nn.ModuleList([]) N_features_lay = len(conv_features) if type == "Cycle_Generator" or type == "Cycle_Discriminator": for i in range(N_features_lay - 1): # Convolutional layers layers.append(nn.Conv1d(in_channels=conv_features[i], out_channels=conv_features[i + 1], kernel_size=conv_kernals[i], padding=int((conv_kernals[i] - 1) / 2), stride=1)) # Batch norm if conv_batchnorm[i] == "True": layers.append(nn.BatchNorm1d(conv_features[i + 1])) # Activation if conv_act[i] != "linear": layers.append(act_fun(conv_act[i])) # Dropout if conv_dropout[i] > 0: layers.append(nn.Dropout(p=conv_dropout[i])) if type.lower().__contains__("discriminator"): layers.append(nn.Linear(input_dim, output_dim)) layers.append(nn.Sigmoid()) return layers class Conv2dAuto(nn.Conv2d): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.padding = ( self.kernel_size[0] // 2, self.kernel_size[1] // 2) # dynamic add padding based on the kernel_size class Conv1dAuto(nn.Conv1d): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.padding = ((self.kernel_size[0] - 1) // 2) class Discriminator_wgan_spectral_norm(nn.Module): def __init__(self, inp_dim, cfg): super(Dis_WGAN_SN, self).__init__() self.input_dim = inp_dim self.output_dim = 1 leaky_alpha = 0.2 dropout = 0.3 self.block = nn.Sequential( nn.Conv1d(in_channels=1, out_channels=16, kernel_size=41, padding=20, stride=1), nn.MaxPool1d(kernel_size=2, stride=2), nn.LeakyReLU(leaky_alpha, inplace=True), nn.BatchNorm1d(16), nn.Dropout(dropout), nn.Conv1d(in_channels=16, out_channels=16, kernel_size=13, padding=6, stride=1), nn.MaxPool1d(kernel_size=2, stride=2), nn.LeakyReLU(leaky_alpha, inplace=True), nn.BatchNorm1d(16), nn.Dropout(dropout), nn.Conv1d(in_channels=16, out_channels=32, kernel_size=13, padding=6, stride=1), nn.MaxPool1d(kernel_size=2, stride=2), nn.LeakyReLU(leaky_alpha, inplace=True), nn.BatchNorm1d(32), nn.Dropout(dropout), nn.Conv1d(in_channels=32, out_channels=32, kernel_size=13, padding=6, stride=1), nn.MaxPool1d(kernel_size=2, stride=2), nn.LeakyReLU(leaky_alpha, inplace=True), nn.BatchNorm1d(32), nn.Dropout(dropout), nn.Conv1d(in_channels=32, out_channels=64, kernel_size=13, padding=6, stride=1), nn.MaxPool1d(kernel_size=2, stride=2), nn.LeakyReLU(leaky_alpha, inplace=True), nn.BatchNorm1d(64), nn.Dropout(dropout), nn.Conv1d(in_channels=64, out_channels=64, kernel_size=3, padding=1, stride=1), nn.MaxPool1d(kernel_size=2, stride=2), nn.LeakyReLU(leaky_alpha, inplace=True), nn.BatchNorm1d(64), nn.Dropout(dropout), nn.Conv1d(in_channels=64, out_channels=128, kernel_size=3, padding=1, stride=1), nn.MaxPool1d(kernel_size=2, stride=2), nn.LeakyReLU(leaky_alpha, inplace=True), nn.BatchNorm1d(128), nn.Dropout(dropout), nn.Conv1d(in_channels=128, out_channels=128, kernel_size=3, padding=1, stride=1), nn.MaxPool1d(kernel_size=2, stride=2), nn.LeakyReLU(leaky_alpha, inplace=True), nn.BatchNorm1d(128), nn.Dropout(dropout), ) self.out_block = nn.Sequential( spectral_norm(nn.Linear(128, self.output_dim)), ) def forward(self, x): x = self.block(x.view(-1, 1, self.input_dim)) x = self.out_block(x.view(-1, 128)) return x class Generator_small(nn.Module): def __init__(self, inp_dim, out_dim, cfg): super(Generator_small, self).__init__() dropout = 0 self.inp_dim = inp_dim leaky_alpha = 0.2 kernel_size = 5 self.block = nn.Sequential( nn.Conv1d(in_channels=1, out_channels=16, kernel_size=kernel_size, padding=int((kernel_size - 1) / 2), stride=1), nn.LeakyReLU(leaky_alpha, inplace=True), nn.Dropout(dropout), nn.Conv1d(in_channels=16, out_channels=16, kernel_size=kernel_size, padding=int((kernel_size - 1) / 2), stride=1), nn.LeakyReLU(leaky_alpha, inplace=True), nn.Dropout(dropout), nn.Conv1d(in_channels=16, out_channels=32, kernel_size=kernel_size, padding=int((kernel_size - 1) / 2), stride=1), nn.LeakyReLU(leaky_alpha, inplace=True), nn.Dropout(dropout), nn.Conv1d(in_channels=32, out_channels=16, kernel_size=kernel_size, padding=int((kernel_size - 1) / 2), stride=1), nn.LeakyReLU(leaky_alpha, inplace=True), nn.Dropout(dropout), nn.Conv1d(in_channels=16, out_channels=1, kernel_size=kernel_size, padding=int((kernel_size - 1) / 2), stride=1), ) # initialize weights self.init_weights() def init_weights(self): """ Initialize weights for convolution layers using Xavier initialization. """ for m in self.modules(): if isinstance(m, nn.Conv1d) or isinstance(m, nn.ConvTranspose1d) or isinstance(m, nn.Linear): nn.init.xavier_normal_(m.weight.data) def forward(self, x): x = x.view(-1, 1, self.inp_dim) return self.block(x).view(-1, self.inp_dim) class Generator_large(nn.Module): def __init__(self, inp_dim, out_dim, cfg): super(Generator_large, self).__init__() dropout = 0 self.encode1 = Block_Encode(in_channels=1, out_channels=16, kernel_size=7, stride=2, dropout=0) self.encode2 = Block_Encode(16, 16, 7, 2, dropout) self.encode3 = Block_Encode(16, 32, 5, 2, dropout) self.encode4 = Block_Encode(32, 32, 5, 2, dropout) self.encode5 = Block_Encode(32, 64, 3, 2, dropout) self.decode1 = Block_Decode(64, 32, 4, 2, dropout) self.decode2 = Block_Decode(64, 32, 5, 2, dropout) self.decode3 = Block_Decode(64, 16, 6, 2, dropout) self.decode4 = Block_Decode(32, 16, 6, 2, dropout) self.decode5 = Block_Decode(32, 1, 6, 2, dropout) # initialize weights self.init_weights() def init_weights(self): """ Initialize weights for convolution layers using Xavier initialization. """ for m in self.modules(): if isinstance(m, nn.Conv1d) or isinstance(m, nn.ConvTranspose1d) or isinstance(m, nn.Linear): nn.init.xavier_normal_(m.weight.data) def forward(self, x): x = torch.unsqueeze(x, dim=1) # [b x 1 x 440] e1 = self.encode1(x) # [b x 16 x 220] e2 = self.encode2(e1) # [b x 16 x 110] e3 = self.encode3(e2) # [b x 32 x 55] e4 = self.encode4(e3) # [b x 32 x 28] e5 = self.encode5(e4) # [b x 64 x 14] d1 = self.decode1(e5) d2 = self.decode2(torch.cat((d1, e4), dim=1)) d3 = self.decode3(torch.cat((d2, e3), dim=1)) d4 = self.decode4(torch.cat((d3, e2), dim=1)) d5 = self.decode5(torch.cat((d4, e1), dim=1)) return torch.squeeze(d5, dim=1) class Discriminator_spectral_norm(nn.Module): def __init__(self, inp_dim, cfg): super(Discriminator_spectral_norm, self).__init__() self.input_dim = inp_dim self.output_dim = 1 leaky_alpha = 0.2 dropout = 0.25 kernel_size = 5 self.block = nn.Sequential( nn.Conv1d(in_channels=1, out_channels=16, kernel_size=kernel_size, padding=int((kernel_size-1)/2), stride=1), nn.MaxPool1d(kernel_size=2, stride=2), nn.LeakyReLU(leaky_alpha, inplace=True), nn.Dropout(dropout), nn.Conv1d(in_channels=16, out_channels=16, kernel_size=kernel_size, padding=int((kernel_size-1)/2), stride=1), nn.MaxPool1d(kernel_size=2, stride=2), nn.LeakyReLU(leaky_alpha, inplace=True), nn.Dropout(dropout), nn.Conv1d(in_channels=16, out_channels=32, kernel_size=kernel_size, padding=int((kernel_size-1)/2), stride=1), nn.MaxPool1d(kernel_size=2, stride=2), nn.LeakyReLU(leaky_alpha, inplace=True), nn.Dropout(dropout), nn.Conv1d(in_channels=32, out_channels=32, kernel_size=kernel_size, padding=int((kernel_size-1)/2), stride=1), nn.MaxPool1d(kernel_size=2, stride=2), nn.LeakyReLU(leaky_alpha, inplace=True), nn.Conv1d(in_channels=32, out_channels=64, kernel_size=kernel_size, padding=int((kernel_size-1)/2), stride=1), nn.MaxPool1d(kernel_size=2, stride=2), nn.LeakyReLU(leaky_alpha, inplace=True), ) self.out_block = nn.Sequential( spectral_norm(nn.Linear(832, self.output_dim)), nn.Sigmoid(), ) def forward(self, x): x = self.block(x.view(-1, 1, self.input_dim)) x = self.out_block(x.view(-1, 832)) return x
20,229
32.001631
111
py
pytorch-kaldi-gan
pytorch-kaldi-gan-master/tune_hyperparameters.py
#!/usr/bin/env python ########################################################## # pytorch-kaldi v.0.1 # Mirco Ravanelli, Titouan Parcollet # Mila, University of Montreal # October 2018 # # Description: # This scripts generates config files with the random hyperparamters specified by the user. # python tune_hyperparameters.py cfg_file out_folder N_exp hyperparameters_spec # e.g., python tune_hyperparameters.py cfg/TIMIT_MLP_mfcc.cfg exp/TIMIT_MLP_mfcc_tuning 10 arch_lr=randfloat(0.001,0.01) batch_size_train=randint(32,256) dnn_act=choose_str{relu,relu,relu,relu,softmax|tanh,tanh,tanh,tanh,softmax} ########################################################## import random import re import os import sys from random import randint if __name__ == "__main__": cfg_file = sys.argv[1] output_folder = sys.argv[2] N_exp = int(sys.argv[3]) hyperparam_list = sys.argv[4:] seed = 1234 print("Generating config file for hyperparameter tuning...") if not os.path.exists(output_folder): os.makedirs(output_folder) random.seed(seed) for i in range(N_exp): cfg_file_out = output_folder + "/exp" + str(i) + ".cfg" with open(cfg_file_out, "wt") as cfg_out, open(cfg_file, "rt") as cfg_in: for line in cfg_in: key = line.split("=")[0] if key == "out_folder": line = "out_folder=" + output_folder + "/exp" + str(i) + "\n" hyper_found = False for hyperparam in hyperparam_list: key_hyper = hyperparam.split("=")[0] if key == key_hyper: if "randint" in hyperparam: lower, higher = re.search("randint\((.+?)\)", hyperparam).group(1).split(",") value_hyper = randint(int(lower), int(higher)) hyper_found = True if "randfloat" in hyperparam: lower, higher = re.search("randfloat\((.+?)\)", hyperparam).group(1).split(",") value_hyper = random.uniform(float(lower), float(higher)) hyper_found = True if "choose_str" in hyperparam: value_hyper = random.choice(re.search("\{(.+?)\}", hyperparam).group(1).split("|")) hyper_found = True if "choose_int" in hyperparam: value_hyper = int(random.choice(re.search("\{(.+?)\}", hyperparam).group(1).split("|"))) hyper_found = True if "choose_float" in hyperparam: value_hyper = float(random.choice(re.search("\{(.+?)\}", hyperparam).group(1).split("|"))) hyper_found = True line_out = key + "=" + str(value_hyper) + "\n" if not hyper_found: line_out = line cfg_out.write(line_out) print("Done %s" % cfg_file_out)
3,100
35.916667
229
py
pytorch-kaldi-gan
pytorch-kaldi-gan-master/weights_and_biases.py
########################################################## # pytorch-kaldi-gan v.1.0 # Walter Heymans # North West University # 2020 ########################################################## import wandb import yaml import os from sys import exit def initialize_wandb(project, config, directory, resume, identity = "", name = ""): if not (identity == "") and not (name == ""): wandb.init(project = project, config = config, dir = directory, id = identity, name = name, resume = resume, reinit = True) else: wandb.init(project = project, config = config, dir = directory, resume = resume, reinit = True) def quick_log(key, value, commit = True): wandb.log({key: value}, commit = commit) def load_cfg_dict_from_yaml(cfg_filename): f = open(cfg_filename, 'r') cfg_yaml = None try: cfg_yaml = yaml.full_load(f) except Exception as e: print("Error loading WANDB config file.", e) exit(101) finally: f.close() cfg = {} for key in cfg_yaml.keys(): cfg[key] = cfg_yaml[key]['value'] return cfg def get_api(): return wandb.Api() def get_run_name(): return wandb.run.name def get_run_id(): return wandb.run.id
1,414
22.983051
83
py
pytorch-kaldi-gan
pytorch-kaldi-gan-master/audio_processing.py
import torch import torchaudio import numpy as np import matplotlib.pyplot as plt import configparser import os import sys import random import shutil import torch.nn as nn import torch.nn.functional as F import torch.nn.utils.spectral_norm as spectral_norm # Reading global cfg file (first argument-mandatory file) cfg_file = sys.argv[1] if not (os.path.exists(cfg_file)): sys.stderr.write("ERROR: The config file %s does not exist!\n" % (cfg_file)) sys.exit(0) else: config = configparser.ConfigParser() config.read(cfg_file) # Output folder creation out_folder = config["exp"]["out_folder"] if not os.path.exists(out_folder): os.makedirs(out_folder) clean_dataset_dir = config["exp"]["clean_dataset"] noisy_dataset_dir = config["exp"]["noisy_dataset"] print("- Reading config file......OK!") def normalize_batch(tensor): ''' Normalize batch of tensors between -1 and 1 ''' max_val = torch.abs(torch.max(tensor)) min_val = torch.abs(torch.min(tensor)) return torch.mul(torch.sub(torch.div(torch.add(tensor, min_val), torch.add(max_val, min_val)), 0.5), 2) def validate_dir(dir_list): ''' Remove hidden files from directory list ''' for dir in dir_list: if dir.__contains__('.'): dir_list.remove(dir) return dir_list def get_utterances(dir_list): ''' Seperate utterances and transcription files ''' transcriptions = '' for dir in dir_list: if dir.__contains__('.txt'): transcriptions = dir dir_list.remove(dir) return transcriptions, dir_list def plot_spectrogram(specgram): with torch.no_grad(): plt.figure() plt.imshow(specgram.log2()[0, :, :].numpy(), cmap = 'gray') plt.show() def plot_spectrogram_list(specgram_list): with torch.no_grad(): plt.figure() for i in range(len(specgram_list)): plt.subplot(len(specgram_list), 1 , i+1) plt.imshow(specgram_list[i].log2()[0, :, :].numpy(), cmap = 'gray') plt.show() def plot_waveform(waveform_tensor): ''' Plot tensor in a figure ''' with torch.no_grad(): plt.figure() try: plt.plot(waveform_tensor.t().detach().to("cpu").numpy()) except AttributeError: plt.plot(waveform_tensor.detach().to("cpu").numpy()) plt.show() def plot_waveform_list(waveform_tensor_list): ''' Plot tensor in a figure ''' with torch.no_grad(): plt.figure() for i in range(len(waveform_tensor_list)): plt.subplot(len(waveform_tensor_list), 1 , i+1) plt.plot(waveform_tensor_list[i].detach().to("cpu").numpy()) plt.show() def normalize_tensor(tensor): ''' Normalize tensor between -1 and 1 ''' max_val = torch.abs(torch.max(tensor)) min_val = torch.abs(torch.min(tensor)) return torch.mul(torch.sub(torch.div(torch.add(tensor, min_val), torch.add(max_val, min_val)), 0.5), 2) def get_context(mfcc_tensor, context_width_left, context_width_right): for i in range(context_width_left, mfcc_tensor.shape[2] - context_width_right): mfcc_frame = mfcc_tensor[:,1:,(i-context_width_left):(i+context_width_right+1)] def get_batch(mfcc_tensor, batch_nr, batchsize): batch_nr = batch_nr * batchsize batch_tensor = mfcc_tensor[batch_nr:batch_nr+batchsize,:] return batch_tensor def reshape_utterance(mfcc_tensor): ''' Transpose and remove MFCC 0 ''' mfcc_tensor = torch.squeeze(mfcc_tensor, dim = 0) return torch.transpose(mfcc_tensor, dim0 = 1, dim1 = 0) def get_pearson_correlation(tensor1, tensor2): from scipy.stats import pearsonr output1 = tensor1.detach().cpu().numpy() output2 = tensor2.detach().cpu().numpy() if output1.shape == output2.shape: # calculate Pearson's correlation if len(output1.shape) > 1: correlation = 0 for i in range(output1.shape[0]): try: temp_corr, _ = pearsonr(output1[i], output2[i]) except: temp_corr = 0 correlation += temp_corr if output1.shape[0] > 0: correlation = correlation / output1.shape[0] else: correlation, _ = pearsonr(output1, output2) return correlation else: return 0 def get_mean_squared_error(tensor1, tensor2): output1 = tensor1.detach().cpu() output2 = tensor2.detach().cpu() if output1.shape == output2.shape: if len(output1.shape) > 1: error = 0 for i in range(output1.shape[0]): error += torch.mean(torch.abs(torch.abs(output1) - torch.abs(output2))) if output1.shape[0] > 0: error = error / output1.shape[0] else: error = torch.mean(torch.abs(torch.abs(output1) - torch.abs(output2))) return error.numpy() else: return 0 def get_g_performance(clean, noisy, generated): ''' Performance metric using Pearson correlation, mean squared error and L1 loss. Metric is comparing generator relative to noisy signal. Higher is better. ''' l1_loss_noisy = torch.nn.functional.l1_loss(clean, noisy).item() l1_loss_gen = torch.nn.functional.l1_loss(clean, generated).item() r_clean_noisy = get_pearson_correlation(clean, noisy) r_clean_gen = get_pearson_correlation(clean, generated) mse_clean_noisy = get_mean_squared_error(clean, noisy) mse_clean_gen = get_mean_squared_error(clean, generated) l1_performance = l1_loss_noisy - l1_loss_gen r_performance = r_clean_gen - r_clean_noisy mse_performance = mse_clean_noisy - mse_clean_gen performance_metric = r_performance + mse_performance + l1_performance return performance_metric def get_labels(batch_size, label): return torch.ones((batch_size, 1)) * label class Conv2dAuto(nn.Conv2d): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.padding = ( self.kernel_size[0] // 2, self.kernel_size[1] // 2) # dynamic add padding based on the kernel_size class Conv1dAuto(nn.Conv1d): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.padding = ((self.kernel_size[0] - 1) // 2) class Generator(nn.Module): def __init__(self, input_dim): super(Generator, self).__init__() self.input_block = nn.Sequential( Conv1dAuto(in_channels = 2, out_channels = 32, kernel_size = 3, bias = True), nn.BatchNorm1d(32), nn.ReLU(), Conv1dAuto(in_channels = 32, out_channels = 32, kernel_size = 3, bias = False), nn.BatchNorm1d(32), nn.ReLU(), ) self.block1 = nn.Sequential( Conv1dAuto(in_channels = 32, out_channels = 32, kernel_size = 3, bias = False), nn.BatchNorm1d(32), nn.ReLU(), Conv1dAuto(in_channels = 32, out_channels = 32, kernel_size = 3, bias = False), nn.BatchNorm1d(32), nn.ReLU(), Conv1dAuto(in_channels = 32, out_channels = 32, kernel_size = 3, bias = False), nn.BatchNorm1d(32), nn.ReLU(), ) self.block2 = nn.Sequential( Conv1dAuto(in_channels = 64, out_channels = 32, kernel_size = 3, bias = False), nn.BatchNorm1d(32), nn.ReLU(), Conv1dAuto(in_channels = 32, out_channels = 32, kernel_size = 3, bias = False), nn.BatchNorm1d(32), nn.ReLU(), Conv1dAuto(in_channels = 32, out_channels = 32, kernel_size = 3, bias = False), nn.BatchNorm1d(32), nn.ReLU(), ) self.block3 = nn.Sequential( Conv1dAuto(in_channels = 64, out_channels = 32, kernel_size = 3, bias = False), nn.BatchNorm1d(32), nn.ReLU(), Conv1dAuto(in_channels = 32, out_channels = 32, kernel_size = 3, bias = False), nn.BatchNorm1d(32), nn.ReLU(), Conv1dAuto(in_channels = 32, out_channels = 1, kernel_size = 3, bias = False), ) def forward(self, x): x1 = self.input_block(x) x2 = self.block1(x1) x3 = self.block2(torch.cat((x1, x2), dim = 1)) x4 = self.block3(torch.cat((x2, x3), dim = 1)) return torch.squeeze(x4, dim = 1) class Discriminator(nn.Module): def __init__(self, input_dim): super(Discriminator, self).__init__() self.input_dim = input_dim self.block = nn.Sequential( Conv1dAuto(in_channels = 1, out_channels = 32, kernel_size = 3, bias = True), nn.BatchNorm1d(32), nn.MaxPool1d(kernel_size = 2, stride = 2), nn.ReLU(), nn.Dropout(0.15), spectral_norm(Conv1dAuto(in_channels = 32, out_channels = 32, kernel_size = 3, bias = False)), nn.BatchNorm1d(32), nn.MaxPool1d(kernel_size = 2, stride = 2), nn.ReLU(), nn.Dropout(0.15), spectral_norm(Conv1dAuto(in_channels = 32, out_channels = 64, kernel_size = 3, bias = False)), nn.BatchNorm1d(64), nn.MaxPool1d(kernel_size = 2, stride = 2), nn.ReLU(), nn.Dropout(0.15), spectral_norm(Conv1dAuto(in_channels = 64, out_channels = 64, kernel_size = 3, bias = False)), nn.BatchNorm1d(64), nn.MaxPool1d(kernel_size = 2, stride = 2), nn.ReLU(), nn.Dropout(0.15), ) self.out_block = nn.Sequential( spectral_norm(nn.Linear(128, 1)), nn.Sigmoid(), ) def forward(self, x): x = self.block(x.view(-1, 1, self.input_dim)) x = self.out_block(x.view(-1, 128)) return x if config["exp"]["dataset_name"] == "LibriSpeech": speaker_lst = os.listdir(clean_dataset_dir) speaker_lst = validate_dir(speaker_lst) N_epochs_tr = int(config['gan']['N_epochs_tr']) batch_size = int(config['gan']['batch_size']) # Create networks and optimizers input_dim = 40 generator = Generator(input_dim).cuda() discriminator = Discriminator(input_dim).cuda() if os.path.exists('gan/generator_audio.pt'): try: generator.load_state_dict(torch.load('gan/generator_audio.pt')) except RuntimeError: print("Load error loading G, network will be recreated.") if os.path.exists('gan/discriminator_audio.pt'): try: discriminator.load_state_dict(torch.load('gan/discriminator_audio.pt')) except RuntimeError: print("Load error loading D, network will be recreated.") if config["gan"]["optimizer"] == "adam": optimizer_g = torch.optim.Adam(generator.parameters(), lr = float(config["gan"]["learning_rate_g"])) optimizer_d = torch.optim.Adam(discriminator.parameters(), lr = float(config["gan"]["learning_rate_d"])) elif config["gan"]["optimizer"] == "rmsprop": optimizer_g = torch.optim.RMSprop(generator.parameters(), lr = float(config["gan"]["learning_rate_g"])) optimizer_d = torch.optim.RMSprop(discriminator.parameters(), lr = float(config["gan"]["learning_rate_d"])) # Training print("\nTraining started.\n") for epoch in range(1, N_epochs_tr + 1): print("------------------ Epoch", epoch, "/", N_epochs_tr, "------------------") generator.train() discriminator.train() d_loss = 0 g_loss = 0 correlation_noisy = 0 correlation_g = 0 mse_noisy = 0 mse_g = 0 performance_metric = 0 total_batches = 0 for speaker in speaker_lst: speaker_dir_clean = os.path.join(clean_dataset_dir, speaker) speaker_dir_noisy = os.path.join(noisy_dataset_dir, speaker) # Get chapters by speaker chapter_lst = os.listdir(speaker_dir_clean) chapter_lst = validate_dir(chapter_lst) for chap in chapter_lst: chapter_dir_clean = os.path.join(speaker_dir_clean, chap) chapter_dir_noisy = os.path.join(speaker_dir_noisy, chap) # Get utterances by speaker per chapter utterance_lst = os.listdir(chapter_dir_clean) utt_transcripitons, utterance_lst = get_utterances(utterance_lst) j = 0 for utt in utterance_lst: utterance_dir_clean = os.path.join(chapter_dir_clean, utt) utterance_dir_noisy = os.path.join(chapter_dir_noisy, utt) audio_clean, sample_rate = torchaudio.load(utterance_dir_clean) audio_noisy, _ = torchaudio.load(utterance_dir_noisy) #CMN_extraction = torchaudio.transforms.SlidingWindowCmn(cmn_window = 600, min_cmn_window = 100) MFCC_extraction = torchaudio.transforms.MFCC(sample_rate = sample_rate, n_mfcc = 40).cuda() #Spectrogram_extraction = torchaudio.transforms.Spectrogram() mfcc_clean = MFCC_extraction(audio_clean.cuda()) mfcc_noisy = MFCC_extraction(audio_noisy.cuda()) utterance_features_clean = reshape_utterance(mfcc_clean) utterance_features_noisy = reshape_utterance(mfcc_noisy) number_of_batches = int(utterance_features_clean.shape[0] / batch_size) last_batch_size = utterance_features_clean.shape[0] % batch_size if last_batch_size > 0: number_of_batches += 1 for batch in range(number_of_batches): total_batches += 1 print("Batch: {} \r".format(total_batches), end = '') data_clean = get_batch(utterance_features_clean, batch, batch_size) data_noisy = get_batch(utterance_features_noisy, batch, batch_size) #=== TRAINING ================================================================================== real_labels = get_labels(data_clean.shape[0], float(config['gan']['real_label'])).cuda() fake_labels = get_labels(data_clean.shape[0], 0).cuda() # Train Discriminator optimizer_d.zero_grad() d_output_real = discriminator(data_clean) z_noise = torch.randn(torch.unsqueeze(data_noisy, dim = 1).shape).cuda() g_output = generator(torch.cat((z_noise, torch.unsqueeze(data_noisy, dim = 1)), dim = 1)) d_output_fake = discriminator(g_output) loss_real = F.binary_cross_entropy(d_output_real, real_labels) loss_fake = F.binary_cross_entropy(d_output_fake, fake_labels) loss_d = loss_real + loss_fake loss_d.backward() optimizer_d.step() # Train Generator optimizer_g.zero_grad() d_verdict = discriminator(generator(torch.cat((z_noise, torch.unsqueeze(data_noisy, dim = 1)), dim = 1))) bce_loss = F.binary_cross_entropy(d_verdict, real_labels) cycle_loss = F.l1_loss(data_clean, generator(torch.cat((z_noise, torch.unsqueeze(data_noisy, dim = 1)), dim = 1))) loss_g = bce_loss + cycle_loss loss_g.backward() optimizer_g.step() #==== Statistics ==== d_loss += loss_d.item() g_loss += loss_g.item() correlation_noisy += get_pearson_correlation(data_clean, data_noisy) correlation_g += get_pearson_correlation(data_clean, g_output) mse_noisy += get_mean_squared_error(data_clean, data_noisy) mse_g += get_mean_squared_error(data_clean, g_output) performance_metric += get_g_performance(data_clean, data_noisy, g_output) print("Discriminator loss:\t %.4f | Generator loss:\t %.4f" % (round(d_loss/total_batches, 4), round(g_loss/total_batches, 4))) print("Correlation G:\t\t %.4f | Correlation noisy:\t %.4f" % ( round(correlation_g/total_batches, 4), round(correlation_noisy/total_batches, 4))) print("MSE G:\t\t\t %.4f | MSE noisy:\t\t %.4f" % (round(mse_g/total_batches, 4), round(mse_noisy/total_batches, 4))) print("Performance:", round(performance_metric/total_batches, 4)) # Save after each speaker torch.save(generator.state_dict(), 'gan/generator_audio.pt') torch.save(discriminator.state_dict(), 'gan/discriminator_audio.pt') print("") d_loss = d_loss / total_batches g_loss = g_loss / total_batches correlation_noisy = correlation_noisy / total_batches correlation_g = correlation_g / total_batches mse_noisy = mse_noisy / total_batches mse_g = mse_g / total_batches performance_metric = performance_metric / total_batches print("\nEpoch complete") print("Discriminator loss:\t %.4f | Generator loss:\t %.4f" % (round(d_loss, 4), round(g_loss, 4))) print("Correlation G:\t\t %.4f | Correlation noisy:\t %.4f" % ( round(correlation_g, 4), round(correlation_noisy, 4))) print("MSE G:\t\t\t %.4f | MSE noisy:\t\t %.4f" % (round(mse_g, 4), round(mse_noisy, 4))) print("Performance:", round(performance_metric, 4)) print("Total batches", total_batches) #=============================================================================================================== print("\n\nTraining complete\n")
18,066
35.061876
144
py
pytorch-kaldi-gan
pytorch-kaldi-gan-master/data_io.py
########################################################## # pytorch-kaldi-gan # Walter Heymans # North West University # 2020 # Adapted from: # pytorch-kaldi v.0.1 # Mirco Ravanelli, Titouan Parcollet # Mila, University of Montreal # October 2018 ########################################################## import numpy as np import sys from utils import compute_cw_max, dict_fea_lab_arch, is_sequential_dict import os import configparser import re, gzip, struct def load_dataset( fea_scp, fea_opts, lab_folder, lab_opts, left, right, max_sequence_length, output_folder, fea_only=False ): def _input_is_wav_file(fea_scp): with open(fea_scp, "r") as f: first_line = f.readline() ark_file = first_line.split(" ")[1].split(":")[0] with open(ark_file, "rb") as f: first_ark_line = f.readline() return b"RIFF" in first_ark_line def _input_is_feature_file(fea_scp): return not _input_is_wav_file(fea_scp) def _read_features_and_labels_with_kaldi(fea_scp, fea_opts, fea_only, lab_folder, lab_opts, output_folder): fea = dict() lab = dict() if _input_is_feature_file(fea_scp): kaldi_bin = "copy-feats" read_function = read_mat_ark elif _input_is_wav_file(fea_scp): kaldi_bin = "wav-copy" read_function = read_vec_flt_ark fea = { k: m for k, m in read_function("ark:" + kaldi_bin + " scp:" + fea_scp + " ark:- |" + fea_opts, output_folder) } if not fea_only: lab = { k: v for k, v in read_vec_int_ark( "gunzip -c " + lab_folder + "/ali*.gz | " + lab_opts + " " + lab_folder + "/final.mdl ark:- ark:-|", output_folder, ) if k in fea } # Note that I'm copying only the aligments of the loaded fea fea = { k: v for k, v in fea.items() if k in lab } # This way I remove all the features without an aligment (see log file in alidir "Did not Succeded") if "_ivector.lst" in fea_scp: for utterance in fea.keys(): temp_features = fea[utterance] new_features = np.zeros((lab[utterance].shape[0], temp_features.shape[1])) for ivector in range(lab[utterance].shape[0]): i_temp = int(ivector / 10) new_features[ivector] = temp_features[i_temp] fea[utterance] = new_features return fea, lab def _chunk_features_and_labels(max_sequence_length, fea, lab, fea_only, input_is_wav): def _append_to_concat_list(fea_chunked, lab_chunked, fea_conc, lab_conc, name): for j in range(0, len(fea_chunked)): fea_conc.append(fea_chunked[j]) lab_conc.append(lab_chunked[j]) if len(fea_chunked) > 1: snt_name.append(name + "_split" + str(j)) else: snt_name.append(k) return fea_conc, lab_conc def _chunk(max_sequence_length, fea, lab, fea_only): def _chunk_by_input_and_output_chunk_config(chunk_config, fea, lab, fea_only): """ If the sequence length is above the threshold, we split it with a minimal length max/4 If max length = 500, then the split will start at 500 + (500/4) = 625. A seq of length 625 will be splitted in one of 500 and one of 125 """ chunk_size_fea, chunk_step_fea, chunk_size_lab, chunk_step_lab = ( chunk_config["chunk_size_fea"], chunk_config["chunk_step_fea"], chunk_config["chunk_size_lab"], chunk_config["chunk_step_lab"], ) fea_chunked = list() lab_chunked = list() split_threshold_fea = chunk_size_fea + (chunk_size_fea / 4) if (len(fea) > chunk_size_fea) and chunk_size_fea > 0: nr_of_chunks = (len(fea) + chunk_size_fea - 1) // chunk_size_fea for i in range(nr_of_chunks): chunk_start_fea = i * chunk_step_fea if len(fea[chunk_start_fea:]) > split_threshold_fea: chunk_end_fea = chunk_start_fea + chunk_size_fea fea_chunk = fea[chunk_start_fea:chunk_end_fea] if not fea_only: chunk_start_lab = i * chunk_step_lab chunk_end_lab = chunk_start_lab + chunk_size_lab lab_chunk = lab[chunk_start_lab:chunk_end_lab] else: lab_chunk = np.zeros((fea_chunk.shape[0],)) fea_chunked.append(fea_chunk) lab_chunked.append(lab_chunk) else: fea_chunk = fea[chunk_start_fea:] if not fea_only: chunk_start_lab = i * chunk_step_lab lab_chunk = lab[chunk_start_lab:] else: lab_chunk = np.zeros((fea_chunk.shape[0],)) lab_chunked.append(lab_chunk) fea_chunked.append(fea_chunk) break else: fea_chunked.append(fea) if not fea_only: lab_chunked.append(lab) else: lab_chunked.append(np.zeros((fea.shape[0],))) return fea_chunked, lab_chunked chunk_config = dict() if type(max_sequence_length) == dict: chunk_config["chunk_size_fea"] = max_sequence_length["chunk_size_fea"] chunk_config["chunk_step_fea"] = max_sequence_length["chunk_step_fea"] chunk_config["chunk_size_lab"] = max_sequence_length["chunk_size_lab"] chunk_config["chunk_step_lab"] = max_sequence_length["chunk_step_lab"] elif type(max_sequence_length) == int: chunk_config["chunk_size_fea"] = max_sequence_length chunk_config["chunk_step_fea"] = max_sequence_length chunk_config["chunk_size_lab"] = max_sequence_length chunk_config["chunk_step_lab"] = max_sequence_length else: raise ValueError("Unknown type of max_sequence_length") return _chunk_by_input_and_output_chunk_config(chunk_config, fea, lab, fea_only) snt_name = list() fea_conc = list() lab_conc = list() feature_keys_soted_by_sequence_length = sorted(sorted(fea.keys()), key=lambda k: len(fea[k])) for k in feature_keys_soted_by_sequence_length: fea_el = fea[k] lab_el = None if not fea_only: lab_el = lab[k] fea_chunked, lab_chunked = _chunk(max_sequence_length, fea_el, lab_el, fea_only) fea_conc, lab_conc = _append_to_concat_list(fea_chunked, lab_chunked, fea_conc, lab_conc, k) return fea_conc, lab_conc, snt_name def _concatenate_features_and_labels(fea_conc, lab_conc): def _sort_chunks_by_length(fea_conc, lab_conc): fea_zipped = zip(fea_conc, lab_conc) fea_sorted = sorted(fea_zipped, key=lambda x: x[0].shape[0]) fea_conc, lab_conc = zip(*fea_sorted) return fea_conc, lab_conc def _get_end_index_from_list(conc): end_snt = 0 end_index = list() for entry in conc: end_snt = end_snt + entry.shape[0] end_index.append(end_snt) return end_index fea_conc, lab_conc = _sort_chunks_by_length(fea_conc, lab_conc) end_index_fea = _get_end_index_from_list(fea_conc) end_index_lab = _get_end_index_from_list(lab_conc) fea_conc = np.concatenate(fea_conc) lab_conc = np.concatenate(lab_conc) return fea_conc, lab_conc, end_index_fea, end_index_lab def _match_feature_and_label_sequence_lengths(fea, lab, max_sequence_length): ALLOW_FRAME_DIFF_LARGER_ONE = False def _adjust_feature_sequence_length(fea, nr_of_fea_for_lab): nr_of_fea = fea.shape[0] if nr_of_fea > nr_of_fea_for_lab: fea_adj = np.take(fea, range(nr_of_fea_for_lab), axis=0) elif nr_of_fea < nr_of_fea_for_lab: padding = np.zeros(shape=(nr_of_fea_for_lab - nr_of_fea,) + fea.shape[1:]) fea_adj = np.concatenate([fea, padding], axis=0) else: fea_adj = fea return fea_adj chunk_size_fea = max_sequence_length["chunk_size_fea"] chunk_step_fea = max_sequence_length["chunk_step_fea"] chunk_size_lab = max_sequence_length["chunk_size_lab"] chunk_step_lab = max_sequence_length["chunk_step_lab"] window_shift = max_sequence_length["window_shift"] window_size = max_sequence_length["window_size"] for k in fea.keys(): nr_of_fea = fea[k].shape[0] nr_of_lab = lab[k].shape[0] nr_of_fea_for_lab = (nr_of_lab - 1) * window_shift + window_size if abs(nr_of_fea - nr_of_fea_for_lab) > window_shift and not ALLOW_FRAME_DIFF_LARGER_ONE: raise ValueError( "Nr. of features: " + str(nr_of_fea) + " does not match nr. of labels: " + str(nr_of_lab) + " with expected nr. of features: " + str(nr_of_fea_for_lab) ) fea[k] = _adjust_feature_sequence_length(fea[k], nr_of_fea_for_lab) return fea, lab fea, lab = _read_features_and_labels_with_kaldi(fea_scp, fea_opts, fea_only, lab_folder, lab_opts, output_folder) if _input_is_wav_file(fea_scp) and (not fea_only): fea, lab = _match_feature_and_label_sequence_lengths(fea, lab, max_sequence_length) fea_chunks, lab_chunks, chunk_names = _chunk_features_and_labels( max_sequence_length, fea, lab, fea_only, _input_is_wav_file(fea_scp) ) fea_conc, lab_conc, end_index_fea, end_index_lab = _concatenate_features_and_labels(fea_chunks, lab_chunks) return [chunk_names, fea_conc, lab_conc, np.asarray(end_index_fea), np.asarray(end_index_lab)] def context_window_old(fea, left, right): N_row = fea.shape[0] N_fea = fea.shape[1] frames = np.empty((N_row - left - right, N_fea * (left + right + 1))) for frame_index in range(left, N_row - right): right_context = fea[frame_index + 1 : frame_index + right + 1].flatten() # right context left_context = fea[frame_index - left : frame_index].flatten() # left context current_frame = np.concatenate([left_context, fea[frame_index], right_context]) frames[frame_index - left] = current_frame return frames def context_window(fea, left, right): N_elem = fea.shape[0] N_fea = fea.shape[1] fea_conc = np.empty([N_elem, N_fea * (left + right + 1)]) index_fea = 0 for lag in range(-left, right + 1): fea_conc[:, index_fea : index_fea + fea.shape[1]] = np.roll(fea, -lag, axis=0) index_fea = index_fea + fea.shape[1] fea_conc = fea_conc[left : fea_conc.shape[0] - right] return fea_conc def load_chunk( fea_scp, fea_opts, lab_folder, lab_opts, left, right, max_sequence_length, output_folder, fea_only=False ): ''' CUSTOM CODE Loading chunks from Kaldi files ''' # open the file [data_name, data_set, data_lab, end_index_fea, end_index_lab] = load_dataset( fea_scp, fea_opts, lab_folder, lab_opts, left, right, max_sequence_length, output_folder, fea_only ) # TODO: currently end_index_lab is ignored # Context window if left != 0 or right != 0: data_set = context_window(data_set, left, right) end_index_fea = end_index_fea - left end_index_fea[-1] = end_index_fea[-1] - right # mean and variance normalization data_set = (data_set - np.mean(data_set, axis=0)) / np.std(data_set, axis=0) # Label processing data_lab = data_lab - data_lab.min() if right > 0: data_lab = data_lab[left:-right] else: data_lab = data_lab[left:] data_set = np.column_stack((data_set, data_lab)) return [data_name, data_set, end_index_fea] def load_counts(class_counts_file): with open(class_counts_file) as f: row = next(f).strip().strip("[]").strip() counts = np.array([np.float32(v) for v in row.split()]) return counts def read_lab_fea_refac01(cfg_file, fea_only, shared_list, output_folder): def _read_chunk_specific_config(cfg_file): if not (os.path.exists(cfg_file)): sys.stderr.write("ERROR: The config file %s does not exist!\n" % (cfg_file)) sys.exit(0) else: config = configparser.ConfigParser() config.read(cfg_file) return config def _read_from_config(config, fea_only): def _get_max_seq_length_from_config_str(config_str): max_seq_length = [int(e) for e in config_str.split(",")] if len(max_seq_length) == 1: max_seq_length = max_seq_length[0] else: assert len(max_seq_length) == 6 max_seq_length_list = max_seq_length max_seq_length = dict() max_seq_length["chunk_size_fea"] = max_seq_length_list[0] max_seq_length["chunk_step_fea"] = max_seq_length_list[1] max_seq_length["chunk_size_lab"] = max_seq_length_list[2] max_seq_length["chunk_step_lab"] = max_seq_length_list[3] max_seq_length["window_shift"] = max_seq_length_list[4] max_seq_length["window_size"] = max_seq_length_list[5] return max_seq_length to_do = config["exp"]["to_do"] if to_do == "train": max_seq_length = _get_max_seq_length_from_config_str(config["batches"]["max_seq_length_train"]) if to_do == "valid": max_seq_length = _get_max_seq_length_from_config_str(config["batches"]["max_seq_length_valid"]) if to_do == "forward": max_seq_length = -1 # do to break forward sentences fea_only = True fea_dict, lab_dict, arch_dict = dict_fea_lab_arch(config, fea_only) seq_model = is_sequential_dict(config, arch_dict) return to_do, max_seq_length, fea_dict, lab_dict, arch_dict, seq_model def _read_features_and_labels(fea_dict, lab_dict, max_seq_length, fea_only, output_folder): def _get_fea_config_from_dict(fea_dict_entr): fea_scp = fea_dict_entr[1] fea_opts = fea_dict_entr[2] cw_left = int(fea_dict_entr[3]) cw_right = int(fea_dict_entr[4]) return fea_scp, fea_opts, cw_left, cw_right def _get_lab_config_from_dict(lab_dict_entr, fea_only): if fea_only: lab_folder = None lab_opts = None else: lab_folder = lab_dict_entr[1] lab_opts = lab_dict_entr[2] return lab_folder, lab_opts def _compensate_for_different_context_windows( data_set_fea, data_set_lab, cw_left_max, cw_left, cw_right_max, cw_right, data_end_index_fea, data_end_index_lab, ): data_set_lab = np.take( data_set_lab, range(cw_left_max - cw_left, data_set_lab.shape[0] - (cw_right_max - cw_right)), axis=0, mode="clip", ) data_set_fea = np.take( data_set_fea, range(cw_left_max - cw_left, data_set_fea.shape[0] - (cw_right_max - cw_right)), axis=0, mode="clip", ) data_end_index_fea = data_end_index_fea - (cw_left_max - cw_left) data_end_index_lab = data_end_index_lab - (cw_left_max - cw_left) data_end_index_fea[-1] = data_end_index_fea[-1] - (cw_right_max - cw_right) data_end_index_lab[-1] = data_end_index_lab[-1] - (cw_right_max - cw_right) return data_set_lab, data_set_fea, data_end_index_fea, data_end_index_lab def _update_data(data_set, labs, fea_dict, fea, fea_index, data_set_fea, labs_fea, cnt_fea, cnt_lab): if cnt_fea == 0 and cnt_lab == 0: data_set = data_set_fea labs = labs_fea fea_dict[fea].append(fea_index) fea_index = fea_index + data_set_fea.shape[1] fea_dict[fea].append(fea_index) fea_dict[fea].append(fea_dict[fea][6] - fea_dict[fea][5]) elif cnt_fea == 0 and (not cnt_lab == 0): labs = np.column_stack((labs, labs_fea)) elif (not cnt_fea == 0) and cnt_lab == 0: data_set = np.column_stack((data_set, data_set_fea)) fea_dict[fea].append(fea_index) fea_index = fea_index + data_set_fea.shape[1] fea_dict[fea].append(fea_index) fea_dict[fea].append(fea_dict[fea][6] - fea_dict[fea][5]) return data_set, labs, fea_dict, fea_index def _check_consistency( data_name, data_name_fea, data_end_index_fea_ini, data_end_index_fea, data_end_index_lab_ini, data_end_index_lab, ): if not (data_name == data_name_fea): sys.stderr.write( 'ERROR: different sentence ids are detected for the different features. Plase check again input feature lists"\n' ) sys.exit(0) if not (data_end_index_fea_ini == data_end_index_fea).all(): sys.stderr.write('ERROR end_index must be the same for all the sentences"\n') sys.exit(0) if not (data_end_index_lab_ini == data_end_index_lab).all(): sys.stderr.write('ERROR end_index must be the same for all the sentences"\n') sys.exit(0) def _update_lab_dict(lab_dict, data_set): cnt_lab = 0 for lab in lab_dict.keys(): lab_dict[lab].append(data_set.shape[1] + cnt_lab) cnt_lab = cnt_lab + 1 return lab_dict def _load_chunk_refac01( fea_scp, fea_opts, lab_folder, lab_opts, left, right, max_sequence_length, output_folder, fea_only=False ): [data_name, data_set, data_lab, end_index_fea, end_index_lab] = load_dataset( fea_scp, fea_opts, lab_folder, lab_opts, left, right, max_sequence_length, output_folder, fea_only ) # TODO: this function will currently only work well if no context window is given or fea and lab have the same time dimensionality # Context window if left != 0 or right != 0: data_set = context_window(data_set, left, right) end_index_fea = end_index_fea - left end_index_lab = end_index_lab - left end_index_fea[-1] = end_index_fea[-1] - right end_index_lab[-1] = end_index_lab[-1] - right # mean and variance normalization data_set = (data_set - np.mean(data_set, axis=0)) / np.std(data_set, axis=0) # Label processing data_lab = data_lab - data_lab.min() if right > 0: data_lab = data_lab[left:-right] else: data_lab = data_lab[left:] if len(data_set.shape) == 1: data_set = np.expand_dims(data_set, -1) return [data_name, data_set, data_lab, end_index_fea, end_index_lab] cw_left_max, cw_right_max = compute_cw_max(fea_dict) fea_index = 0 cnt_fea = 0 data_name = None data_end_index_fea_ini = None data_end_index_lab_ini = None data_set = None labs = None for fea in fea_dict.keys(): fea_scp, fea_opts, cw_left, cw_right = _get_fea_config_from_dict(fea_dict[fea]) cnt_lab = 0 if fea_only: lab_dict.update({"lab_name": "none"}) for lab in lab_dict.keys(): lab_folder, lab_opts = _get_lab_config_from_dict(lab_dict[lab], fea_only) data_name_fea, data_set_fea, data_set_lab, data_end_index_fea, data_end_index_lab = _load_chunk_refac01( fea_scp, fea_opts, lab_folder, lab_opts, cw_left, cw_right, max_seq_length, output_folder, fea_only ) if sum([abs(e) for e in [cw_left_max, cw_right_max, cw_left, cw_right]]) != 0: data_set_lab, data_set_fea, data_end_index_fea, data_end_index_lab = _compensate_for_different_context_windows( data_set_fea, data_set_lab, cw_left_max, cw_left, cw_right_max, cw_right, data_end_index_fea, data_end_index_lab, ) if cnt_fea == 0 and cnt_lab == 0: data_end_index_fea_ini = data_end_index_fea data_end_index_lab_ini = data_end_index_lab data_name = data_name_fea data_set, labs, fea_dict, fea_index = _update_data( data_set, labs, fea_dict, fea, fea_index, data_set_fea, data_set_lab, cnt_fea, cnt_lab ) _check_consistency( data_name, data_name_fea, data_end_index_fea_ini, data_end_index_fea, data_end_index_lab_ini, data_end_index_lab, ) cnt_lab = cnt_lab + 1 cnt_fea = cnt_fea + 1 if not fea_only: lab_dict = _update_lab_dict(lab_dict, data_set) return data_name, data_end_index_fea_ini, data_end_index_lab_ini, fea_dict, lab_dict, data_set, labs def _reorder_data_set(data_set, labs, seq_model, to_do): if not (seq_model) and to_do != "forward" and (data_set.shape[0] == labs.shape[0]): data_set_shape = data_set.shape[1] data_set_joint = np.column_stack((data_set, labs)) ganset = True try: if str(config["ganset"]["create_set"]) == "True": ganset = False except KeyError: pass if ganset: np.random.shuffle(data_set) data_set = data_set_joint[:, :data_set_shape] labs = np.squeeze(data_set_joint[:, data_set_shape:], axis=-1) return data_set, labs def _append_to_shared_list( shared_list, data_name, data_end_index_fea, data_end_index_lab, fea_dict, lab_dict, arch_dict, data_set ): shared_list.append(data_name) shared_list.append(data_end_index_fea) shared_list.append(data_end_index_lab) shared_list.append(fea_dict) shared_list.append(lab_dict) shared_list.append(arch_dict) shared_list.append(data_set) return shared_list config = _read_chunk_specific_config(cfg_file) to_do, max_seq_length, fea_dict, lab_dict, arch_dict, seq_model = _read_from_config(config, fea_only) data_name, data_end_index_fea, data_end_index_lab, fea_dict, lab_dict, data_set, labs = _read_features_and_labels( fea_dict, lab_dict, max_seq_length, fea_only, output_folder ) data_set, labs = _reorder_data_set(data_set, labs, seq_model, to_do) data_set = {"input": data_set, "ref": labs} shared_list = _append_to_shared_list( shared_list, data_name, data_end_index_fea, data_end_index_lab, fea_dict, lab_dict, arch_dict, data_set ) def read_lab_fea(cfg_file, fea_only, shared_list, output_folder): # Reading chunk-specific cfg file (first argument-mandatory file) if not (os.path.exists(cfg_file)): sys.stderr.write("ERROR: The config file %s does not exist!\n" % (cfg_file)) sys.exit(0) else: config = configparser.ConfigParser() config.read(cfg_file) # Reading some cfg parameters to_do = config["exp"]["to_do"] if to_do == "train": max_seq_length = int( config["batches"]["max_seq_length_train"] ) # *(int(info_file[-13:-10])+1) # increasing over the epochs if to_do == "valid": max_seq_length = int(config["batches"]["max_seq_length_valid"]) if to_do == "forward": max_seq_length = -1 # do to break forward sentences [fea_dict, lab_dict, arch_dict] = dict_fea_lab_arch(config, fea_only) [cw_left_max, cw_right_max] = compute_cw_max(fea_dict) fea_index = 0 cnt_fea = 0 for fea in fea_dict.keys(): # reading the features fea_scp = fea_dict[fea][1] fea_opts = fea_dict[fea][2] cw_left = int(fea_dict[fea][3]) cw_right = int(fea_dict[fea][4]) cnt_lab = 0 # Production case, we don't have labels (lab_name = none) if fea_only: lab_dict.update({"lab_name": "none"}) for lab in lab_dict.keys(): # Production case, we don't have labels (lab_name = none) if fea_only: lab_folder = None lab_opts = None else: lab_folder = lab_dict[lab][1] lab_opts = lab_dict[lab][2] [data_name_fea, data_set_fea, data_end_index_fea] = load_chunk( fea_scp, fea_opts, lab_folder, lab_opts, cw_left, cw_right, max_seq_length, output_folder, fea_only ) # making the same dimenion for all the features (compensating for different context windows) labs_fea = data_set_fea[cw_left_max - cw_left : data_set_fea.shape[0] - (cw_right_max - cw_right), -1] data_set_fea = data_set_fea[cw_left_max - cw_left : data_set_fea.shape[0] - (cw_right_max - cw_right), 0:-1] data_end_index_fea = data_end_index_fea - (cw_left_max - cw_left) data_end_index_fea[-1] = data_end_index_fea[-1] - (cw_right_max - cw_right) if cnt_fea == 0 and cnt_lab == 0: data_set = data_set_fea labs = labs_fea data_end_index = data_end_index_fea data_name = data_name_fea fea_dict[fea].append(fea_index) fea_index = fea_index + data_set_fea.shape[1] fea_dict[fea].append(fea_index) fea_dict[fea].append(fea_dict[fea][6] - fea_dict[fea][5]) else: if cnt_fea == 0: labs = np.column_stack((labs, labs_fea)) if cnt_lab == 0: data_set = np.column_stack((data_set, data_set_fea)) fea_dict[fea].append(fea_index) fea_index = fea_index + data_set_fea.shape[1] fea_dict[fea].append(fea_index) fea_dict[fea].append(fea_dict[fea][6] - fea_dict[fea][5]) # Checks if lab_names are the same for all the features if not (data_name == data_name_fea): sys.stderr.write( 'ERROR: different sentence ids are detected for the different features. Plase check again input feature lists"\n' ) sys.exit(0) # Checks if end indexes are the same for all the features if not (data_end_index == data_end_index_fea).all(): sys.stderr.write('ERROR end_index must be the same for all the sentences"\n') sys.exit(0) cnt_lab = cnt_lab + 1 cnt_fea = cnt_fea + 1 cnt_lab = 0 if not fea_only: for lab in lab_dict.keys(): lab_dict[lab].append(data_set.shape[1] + cnt_lab) cnt_lab = cnt_lab + 1 data_set = np.column_stack((data_set, labs)) # appends labels next to features # check automatically if the model is sequential seq_model = is_sequential_dict(config, arch_dict) ganset = True try: if str(config["ganset"]["create_set"]) == "True": ganset = False except KeyError: pass # Randomize if the model is not sequential if not (seq_model) and to_do != "forward" and ganset: np.random.shuffle(data_set) # Split dataset in many part. If the dataset is too big, we can have issues to copy it into the shared memory (due to pickle limits) # N_split=10 # data_set=np.array_split(data_set, N_split) # Adding all the elements in the shared list shared_list.append(data_name) shared_list.append(data_end_index) shared_list.append(fea_dict) shared_list.append(lab_dict) shared_list.append(arch_dict) shared_list.append(data_set) # The following libraries are copied from kaldi-io-for-python project (https://github.com/vesis84/kaldi-io-for-python) # Copyright 2014-2016 Brno University of Technology (author: Karel Vesely) # Licensed under the Apache License, Version 2.0 (the "License") ################################################# # Define all custom exceptions, class UnsupportedDataType(Exception): pass class UnknownVectorHeader(Exception): pass class UnknownMatrixHeader(Exception): pass class BadSampleSize(Exception): pass class BadInputFormat(Exception): pass class SubprocessFailed(Exception): pass ################################################# # Data-type independent helper functions, def open_or_fd(file, output_folder, mode="rb"): """ fd = open_or_fd(file) Open file, gzipped file, pipe, or forward the file-descriptor. Eventually seeks in the 'file' argument contains ':offset' suffix. """ offset = None try: # strip 'ark:' prefix from r{x,w}filename (optional), if re.search("^(ark|scp)(,scp|,b|,t|,n?f|,n?p|,b?o|,n?s|,n?cs)*:", file): (prefix, file) = file.split(":", 1) # separate offset from filename (optional), if re.search(":[0-9]+$", file): (file, offset) = file.rsplit(":", 1) # input pipe? if file[-1] == "|": fd = popen(file[:-1], output_folder, "rb") # custom, # output pipe? elif file[0] == "|": fd = popen(file[1:], output_folder, "wb") # custom, # is it gzipped? elif file.split(".")[-1] == "gz": fd = gzip.open(file, mode) # a normal file... else: fd = open(file, mode) except TypeError: # 'file' is opened file descriptor, fd = file # Eventually seek to offset, if offset != None: fd.seek(int(offset)) return fd # based on '/usr/local/lib/python3.4/os.py' def popen(cmd, output_folder, mode="rb"): if not isinstance(cmd, str): raise TypeError("invalid cmd type (%s, expected string)" % type(cmd)) import subprocess, io, threading # cleanup function for subprocesses, def cleanup(proc, cmd): ret = proc.wait() if ret > 0: raise SubprocessFailed("cmd %s returned %d !" % (cmd, ret)) return # text-mode, if mode == "r": err = open(output_folder + "/log.log", "a") proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=err) threading.Thread(target=cleanup, args=(proc, cmd)).start() # clean-up thread, return io.TextIOWrapper(proc.stdout) elif mode == "w": err = open(output_folder + "/log.log", "a") proc = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stderr=err) threading.Thread(target=cleanup, args=(proc, cmd)).start() # clean-up thread, return io.TextIOWrapper(proc.stdin) # binary, elif mode == "rb": err = open(output_folder + "/log.log", "a") proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=err) threading.Thread(target=cleanup, args=(proc, cmd)).start() # clean-up thread, return proc.stdout elif mode == "wb": err = open(output_folder + "/log.log", "a") proc = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stderr=err) threading.Thread(target=cleanup, args=(proc, cmd)).start() # clean-up thread, return proc.stdin # sanity, else: raise ValueError("invalid mode %s" % mode) def read_key(fd): """ [key] = read_key(fd) Read the utterance-key from the opened ark/stream descriptor 'fd'. """ key = "" while 1: char = fd.read(1).decode("latin1") if char == "": break if char == " ": break key += char key = key.strip() if key == "": return None # end of file, assert re.match("^\S+$", key) != None # check format (no whitespace!) return key ################################################# # Integer vectors (alignments, ...), def read_ali_ark(file_or_fd, output_folder): """ Alias to 'read_vec_int_ark()' """ return read_vec_int_ark(file_or_fd, output_folder) def read_vec_int_ark(file_or_fd, output_folder): """ generator(key,vec) = read_vec_int_ark(file_or_fd) Create generator of (key,vector<int>) tuples, which reads from the ark file/stream. file_or_fd : ark, gzipped ark, pipe or opened file descriptor. Read ark to a 'dictionary': d = { u:d for u,d in kaldi_io.read_vec_int_ark(file) } """ fd = open_or_fd(file_or_fd, output_folder) try: key = read_key(fd) while key: ali = read_vec_int(fd, output_folder) yield key, ali key = read_key(fd) finally: if fd is not file_or_fd: fd.close() def read_vec_int(file_or_fd, output_folder): """ [int-vec] = read_vec_int(file_or_fd) Read kaldi integer vector, ascii or binary input, """ fd = open_or_fd(file_or_fd, output_folder) binary = fd.read(2).decode() if binary == "\0B": # binary flag assert fd.read(1).decode() == "\4" # int-size vec_size = np.frombuffer(fd.read(4), dtype="int32", count=1)[0] # vector dim if vec_size == 0: return np.array([], dtype="int32") # Elements from int32 vector are sored in tuples: (sizeof(int32), value), vec = np.frombuffer(fd.read(vec_size * 5), dtype=[("size", "int8"), ("value", "int32")], count=vec_size) assert vec[0]["size"] == 4 # int32 size, ans = vec[:]["value"] # values are in 2nd column, else: # ascii, arr = (binary + fd.readline().decode()).strip().split() try: arr.remove("[") arr.remove("]") # optionally except ValueError: pass ans = np.array(arr, dtype=int) if fd is not file_or_fd: fd.close() # cleanup return ans # Writing, def write_vec_int(file_or_fd, output_folder, v, key=""): """ write_vec_int(f, v, key='') Write a binary kaldi integer vector to filename or stream. Arguments: file_or_fd : filename or opened file descriptor for writing, v : the vector to be stored, key (optional) : used for writing ark-file, the utterance-id gets written before the vector. Example of writing single vector: kaldi_io.write_vec_int(filename, vec) Example of writing arkfile: with open(ark_file,'w') as f: for key,vec in dict.iteritems(): kaldi_io.write_vec_flt(f, vec, key=key) """ fd = open_or_fd(file_or_fd, output_folder, mode="wb") if sys.version_info[0] == 3: assert fd.mode == "wb" try: if key != "": fd.write((key + " ").encode("latin1")) # ark-files have keys (utterance-id), fd.write("\0B".encode()) # we write binary! # dim, fd.write("\4".encode()) # int32 type, fd.write(struct.pack(np.dtype("int32").char, v.shape[0])) # data, for i in range(len(v)): fd.write("\4".encode()) # int32 type, fd.write(struct.pack(np.dtype("int32").char, v[i])) # binary, finally: if fd is not file_or_fd: fd.close() ################################################# # Float vectors (confidences, ivectors, ...), # Reading, def read_vec_flt_scp(file_or_fd, output_folder): """ generator(key,mat) = read_vec_flt_scp(file_or_fd) Returns generator of (key,vector) tuples, read according to kaldi scp. file_or_fd : scp, gzipped scp, pipe or opened file descriptor. Iterate the scp: for key,vec in kaldi_io.read_vec_flt_scp(file): ... Read scp to a 'dictionary': d = { key:mat for key,mat in kaldi_io.read_mat_scp(file) } """ fd = open_or_fd(file_or_fd, output_folder) try: for line in fd: (key, rxfile) = line.decode().split(" ") vec = read_vec_flt(rxfile, output_folder) yield key, vec finally: if fd is not file_or_fd: fd.close() def read_vec_flt_ark(file_or_fd, output_folder): """ generator(key,vec) = read_vec_flt_ark(file_or_fd) Create generator of (key,vector<float>) tuples, reading from an ark file/stream. file_or_fd : ark, gzipped ark, pipe or opened file descriptor. Read ark to a 'dictionary': d = { u:d for u,d in kaldi_io.read_vec_flt_ark(file) } """ fd = open_or_fd(file_or_fd, output_folder) try: key = read_key(fd) while key: ali = read_vec_flt(fd, output_folder) yield key, ali key = read_key(fd) finally: if fd is not file_or_fd: fd.close() def read_vec_flt(file_or_fd, output_folder): """ [flt-vec] = read_vec_flt(file_or_fd) Read kaldi float vector, ascii or binary input, """ fd = open_or_fd(file_or_fd, output_folder) binary = fd.read(2).decode() if binary == "\0B": # binary flag return _read_vec_flt_binary(fd) elif binary == "RI": return _read_vec_flt_riff(fd) else: # ascii, arr = (binary + fd.readline().decode()).strip().split() try: arr.remove("[") arr.remove("]") # optionally except ValueError: pass ans = np.array(arr, dtype=float) if fd is not file_or_fd: fd.close() # cleanup return ans def _read_vec_flt_riff(fd): RIFF_CHUNK_DESCR_HEADER_SIZE = 12 ALREADY_READ_HEADER_BYTES = 2 SUB_CHUNK_HEADER_SIZE = 8 DATA_CHUNK_HEADER_SIZE = 8 def pcm2float(signal, dtype="float32"): signal = np.asarray(signal) dtype = np.dtype(dtype) return signal.astype(dtype) / dtype.type(-np.iinfo(signal.dtype).min) import struct header = fd.read(RIFF_CHUNK_DESCR_HEADER_SIZE - ALREADY_READ_HEADER_BYTES) assert header[:2] == b"FF" chunk_header = fd.read(SUB_CHUNK_HEADER_SIZE) subchunk_id, subchunk_size = struct.unpack("<4sI", chunk_header) aformat, channels, samplerate, byterate, block_align, bps = struct.unpack("HHIIHH", fd.read(subchunk_size)) subchunk2_id, subchunk2_size = struct.unpack("<4sI", fd.read(DATA_CHUNK_HEADER_SIZE)) pcm_data = np.frombuffer(fd.read(subchunk2_size), dtype="int" + str(bps)) return pcm2float(pcm_data) def _read_vec_flt_binary(fd): header = fd.read(3).decode() if header == "FV ": sample_size = 4 # floats elif header == "DV ": sample_size = 8 # doubles else: raise UnknownVectorHeader("The header contained '%s'" % header) assert sample_size > 0 # Dimension, assert fd.read(1).decode() == "\4" # int-size vec_size = np.frombuffer(fd.read(4), dtype="int32", count=1)[0] # vector dim if vec_size == 0: return np.array([], dtype="float32") # Read whole vector, buf = fd.read(vec_size * sample_size) if sample_size == 4: ans = np.frombuffer(buf, dtype="float32") elif sample_size == 8: ans = np.frombuffer(buf, dtype="float64") else: raise BadSampleSize return ans # Writing, def write_vec_flt(file_or_fd, output_folder, v, key=""): """ write_vec_flt(f, v, key='') Write a binary kaldi vector to filename or stream. Supports 32bit and 64bit floats. Arguments: file_or_fd : filename or opened file descriptor for writing, v : the vector to be stored, key (optional) : used for writing ark-file, the utterance-id gets written before the vector. Example of writing single vector: kaldi_io.write_vec_flt(filename, vec) Example of writing arkfile: with open(ark_file,'w') as f: for key,vec in dict.iteritems(): kaldi_io.write_vec_flt(f, vec, key=key) """ fd = open_or_fd(file_or_fd, output_folder, mode="wb") if sys.version_info[0] == 3: assert fd.mode == "wb" try: if key != "": fd.write((key + " ").encode("latin1")) # ark-files have keys (utterance-id), fd.write("\0B".encode()) # we write binary! # Data-type, if v.dtype == "float32": fd.write("FV ".encode()) elif v.dtype == "float64": fd.write("DV ".encode()) else: raise UnsupportedDataType("'%s', please use 'float32' or 'float64'" % v.dtype) # Dim, fd.write("\04".encode()) fd.write(struct.pack(np.dtype("uint32").char, v.shape[0])) # dim # Data, fd.write(v.tobytes()) finally: if fd is not file_or_fd: fd.close() ################################################# # Float matrices (features, transformations, ...), # Reading, def read_mat_scp(file_or_fd, output_folder): """ generator(key,mat) = read_mat_scp(file_or_fd) Returns generator of (key,matrix) tuples, read according to kaldi scp. file_or_fd : scp, gzipped scp, pipe or opened file descriptor. Iterate the scp: for key,mat in kaldi_io.read_mat_scp(file): ... Read scp to a 'dictionary': d = { key:mat for key,mat in kaldi_io.read_mat_scp(file) } """ fd = open_or_fd(file_or_fd, output_folder) try: for line in fd: (key, rxfile) = line.decode().split(" ") mat = read_mat(rxfile, output_folder) yield key, mat finally: if fd is not file_or_fd: fd.close() def read_mat_ark(file_or_fd, output_folder): """ generator(key,mat) = read_mat_ark(file_or_fd) Returns generator of (key,matrix) tuples, read from ark file/stream. file_or_fd : scp, gzipped scp, pipe or opened file descriptor. Iterate the ark: for key,mat in kaldi_io.read_mat_ark(file): ... Read ark to a 'dictionary': d = { key:mat for key,mat in kaldi_io.read_mat_ark(file) } """ fd = open_or_fd(file_or_fd, output_folder) try: key = read_key(fd) while key: mat = read_mat(fd, output_folder) yield key, mat key = read_key(fd) finally: if fd is not file_or_fd: fd.close() def read_mat(file_or_fd, output_folder): """ [mat] = read_mat(file_or_fd) Reads single kaldi matrix, supports ascii and binary. file_or_fd : file, gzipped file, pipe or opened file descriptor. """ fd = open_or_fd(file_or_fd, output_folder) try: binary = fd.read(2).decode() if binary == "\0B": mat = _read_mat_binary(fd) else: assert binary == " [" mat = _read_mat_ascii(fd) finally: if fd is not file_or_fd: fd.close() return mat def _read_mat_binary(fd): # Data type header = fd.read(3).decode() # 'CM', 'CM2', 'CM3' are possible values, if header.startswith("CM"): return _read_compressed_mat(fd, header) elif header == "FM ": sample_size = 4 # floats elif header == "DM ": sample_size = 8 # doubles else: raise UnknownMatrixHeader("The header contained '%s'" % header) assert sample_size > 0 # Dimensions s1, rows, s2, cols = np.frombuffer(fd.read(10), dtype="int8,int32,int8,int32", count=1)[0] # Read whole matrix buf = fd.read(rows * cols * sample_size) if sample_size == 4: vec = np.frombuffer(buf, dtype="float32") elif sample_size == 8: vec = np.frombuffer(buf, dtype="float64") else: raise BadSampleSize mat = np.reshape(vec, (rows, cols)) return mat def _read_mat_ascii(fd): rows = [] while 1: line = fd.readline().decode() if len(line) == 0: raise BadInputFormat # eof, should not happen! if len(line.strip()) == 0: continue # skip empty line arr = line.strip().split() if arr[-1] != "]": rows.append(np.array(arr, dtype="float32")) # not last line else: rows.append(np.array(arr[:-1], dtype="float32")) # last line mat = np.vstack(rows) return mat def _read_compressed_mat(fd, format): """ Read a compressed matrix, see: https://github.com/kaldi-asr/kaldi/blob/master/src/matrix/compressed-matrix.h methods: CompressedMatrix::Read(...), CompressedMatrix::CopyToMat(...), """ assert format == "CM " # The formats CM2, CM3 are not supported... # Format of header 'struct', global_header = np.dtype( [("minvalue", "float32"), ("range", "float32"), ("num_rows", "int32"), ("num_cols", "int32")] ) # member '.format' is not written, per_col_header = np.dtype( [ ("percentile_0", "uint16"), ("percentile_25", "uint16"), ("percentile_75", "uint16"), ("percentile_100", "uint16"), ] ) # Read global header, globmin, globrange, rows, cols = np.frombuffer(fd.read(16), dtype=global_header, count=1)[0] # The data is structed as [Colheader, ... , Colheader, Data, Data , .... ] # { cols }{ size } col_headers = np.frombuffer(fd.read(cols * 8), dtype=per_col_header, count=cols) col_headers = np.array( [np.array([x for x in y]) * globrange * 1.52590218966964e-05 + globmin for y in col_headers], dtype=np.float32 ) data = np.reshape( np.frombuffer(fd.read(cols * rows), dtype="uint8", count=cols * rows), newshape=(cols, rows) ) # stored as col-major, mat = np.zeros((cols, rows), dtype="float32") p0 = col_headers[:, 0].reshape(-1, 1) p25 = col_headers[:, 1].reshape(-1, 1) p75 = col_headers[:, 2].reshape(-1, 1) p100 = col_headers[:, 3].reshape(-1, 1) mask_0_64 = data <= 64 mask_193_255 = data > 192 mask_65_192 = ~(mask_0_64 | mask_193_255) mat += (p0 + (p25 - p0) / 64.0 * data) * mask_0_64.astype(np.float32) mat += (p25 + (p75 - p25) / 128.0 * (data - 64)) * mask_65_192.astype(np.float32) mat += (p75 + (p100 - p75) / 63.0 * (data - 192)) * mask_193_255.astype(np.float32) return mat.T # transpose! col-major -> row-major, # Writing, def write_mat(output_folder, file_or_fd, m, key=""): """ write_mat(f, m, key='') Write a binary kaldi matrix to filename or stream. Supports 32bit and 64bit floats. Arguments: file_or_fd : filename of opened file descriptor for writing, m : the matrix to be stored, key (optional) : used for writing ark-file, the utterance-id gets written before the matrix. Example of writing single matrix: kaldi_io.write_mat(filename, mat) Example of writing arkfile: with open(ark_file,'w') as f: for key,mat in dict.iteritems(): kaldi_io.write_mat(f, mat, key=key) """ fd = open_or_fd(file_or_fd, output_folder, mode="wb") if sys.version_info[0] == 3: assert fd.mode == "wb" try: if key != "": fd.write((key + " ").encode("latin1")) # ark-files have keys (utterance-id), fd.write("\0B".encode()) # we write binary! # Data-type, if m.dtype == "float32": fd.write("FM ".encode()) elif m.dtype == "float64": fd.write("DM ".encode()) else: raise UnsupportedDataType("'%s', please use 'float32' or 'float64'" % m.dtype) # Dims, fd.write("\04".encode()) fd.write(struct.pack(np.dtype("uint32").char, m.shape[0])) # rows fd.write("\04".encode()) fd.write(struct.pack(np.dtype("uint32").char, m.shape[1])) # cols # Data, fd.write(m.tobytes()) finally: if fd is not file_or_fd: fd.close() ################################################# # 'Posterior' kaldi type (posteriors, confusion network, nnet1 training targets, ...) # Corresponds to: vector<vector<tuple<int,float> > > # - outer vector: time axis # - inner vector: records at the time # - tuple: int = index, float = value # def read_cnet_ark(file_or_fd, output_folder): """ Alias of function 'read_post_ark()', 'cnet' = confusion network """ return read_post_ark(file_or_fd, output_folder) def read_post_rxspec(file_): """ adaptor to read both 'ark:...' and 'scp:...' inputs of posteriors, """ if file_.startswith("ark:"): return read_post_ark(file_) elif file_.startswith("scp:"): return read_post_scp(file_) else: print("unsupported intput type: %s" % file_) print("it should begint with 'ark:' or 'scp:'") sys.exit(1) def read_post_scp(file_or_fd, output_folder): """ generator(key,post) = read_post_scp(file_or_fd) Returns generator of (key,post) tuples, read according to kaldi scp. file_or_fd : scp, gzipped scp, pipe or opened file descriptor. Iterate the scp: for key,post in kaldi_io.read_post_scp(file): ... Read scp to a 'dictionary': d = { key:post for key,post in kaldi_io.read_post_scp(file) } """ fd = open_or_fd(file_or_fd, output_folder) try: for line in fd: (key, rxfile) = line.decode().split(" ") post = read_post(rxfile) yield key, post finally: if fd is not file_or_fd: fd.close() def read_post_ark(file_or_fd, output_folder): """ generator(key,vec<vec<int,float>>) = read_post_ark(file) Returns generator of (key,posterior) tuples, read from ark file. file_or_fd : ark, gzipped ark, pipe or opened file descriptor. Iterate the ark: for key,post in kaldi_io.read_post_ark(file): ... Read ark to a 'dictionary': d = { key:post for key,post in kaldi_io.read_post_ark(file) } """ fd = open_or_fd(file_or_fd, output_folder) try: key = read_key(fd) while key: post = read_post(fd) yield key, post key = read_key(fd) finally: if fd is not file_or_fd: fd.close() def read_post(file_or_fd, output_folder): """ [post] = read_post(file_or_fd) Reads single kaldi 'Posterior' in binary format. The 'Posterior' is C++ type 'vector<vector<tuple<int,float> > >', the outer-vector is usually time axis, inner-vector are the records at given time, and the tuple is composed of an 'index' (integer) and a 'float-value'. The 'float-value' can represent a probability or any other numeric value. Returns vector of vectors of tuples. """ fd = open_or_fd(file_or_fd, output_folder) ans = [] binary = fd.read(2).decode() assert binary == "\0B" # binary flag assert fd.read(1).decode() == "\4" # int-size outer_vec_size = np.frombuffer(fd.read(4), dtype="int32", count=1)[0] # number of frames (or bins) # Loop over 'outer-vector', for i in range(outer_vec_size): assert fd.read(1).decode() == "\4" # int-size inner_vec_size = np.frombuffer(fd.read(4), dtype="int32", count=1)[0] # number of records for frame (or bin) data = np.frombuffer( fd.read(inner_vec_size * 10), dtype=[("size_idx", "int8"), ("idx", "int32"), ("size_post", "int8"), ("post", "float32")], count=inner_vec_size, ) assert data[0]["size_idx"] == 4 assert data[0]["size_post"] == 4 ans.append(data[["idx", "post"]].tolist()) if fd is not file_or_fd: fd.close() return ans ################################################# # Kaldi Confusion Network bin begin/end times, # (kaldi stores CNs time info separately from the Posterior). # def read_cntime_ark(file_or_fd, output_folder): """ generator(key,vec<tuple<float,float>>) = read_cntime_ark(file_or_fd) Returns generator of (key,cntime) tuples, read from ark file. file_or_fd : file, gzipped file, pipe or opened file descriptor. Iterate the ark: for key,time in kaldi_io.read_cntime_ark(file): ... Read ark to a 'dictionary': d = { key:time for key,time in kaldi_io.read_post_ark(file) } """ fd = open_or_fd(file_or_fd, output_folder) try: key = read_key(fd) while key: cntime = read_cntime(fd) yield key, cntime key = read_key(fd) finally: if fd is not file_or_fd: fd.close() def read_cntime(file_or_fd, output_folder): """ [cntime] = read_cntime(file_or_fd) Reads single kaldi 'Confusion Network time info', in binary format: C++ type: vector<tuple<float,float> >. (begin/end times of bins at the confusion network). Binary layout is '<num-bins> <beg1> <end1> <beg2> <end2> ...' file_or_fd : file, gzipped file, pipe or opened file descriptor. Returns vector of tuples. """ fd = open_or_fd(file_or_fd, output_folder) binary = fd.read(2).decode() assert binary == "\0B" # assuming it's binary assert fd.read(1).decode() == "\4" # int-size vec_size = np.frombuffer(fd.read(4), dtype="int32", count=1)[0] # number of frames (or bins) data = np.frombuffer( fd.read(vec_size * 10), dtype=[("size_beg", "int8"), ("t_beg", "float32"), ("size_end", "int8"), ("t_end", "float32")], count=vec_size, ) assert data[0]["size_beg"] == 4 assert data[0]["size_end"] == 4 ans = data[["t_beg", "t_end"]].tolist() # Return vector of tuples (t_beg,t_end), if fd is not file_or_fd: fd.close() return ans ################################################# # Segments related, # # Segments as 'Bool vectors' can be handy, # - for 'superposing' the segmentations, # - for frame-selection in Speaker-ID experiments, def read_segments_as_bool_vec(segments_file): """ [ bool_vec ] = read_segments_as_bool_vec(segments_file) using kaldi 'segments' file for 1 wav, format : '<utt> <rec> <t-beg> <t-end>' - t-beg, t-end is in seconds, - assumed 100 frames/second, """ segs = np.loadtxt(segments_file, dtype="object,object,f,f", ndmin=1) # Sanity checks, assert len(segs) > 0 # empty segmentation is an error, assert len(np.unique([rec[1] for rec in segs])) == 1 # segments with only 1 wav-file, # Convert time to frame-indexes, start = np.rint([100 * rec[2] for rec in segs]).astype(int) end = np.rint([100 * rec[3] for rec in segs]).astype(int) # Taken from 'read_lab_to_bool_vec', htk.py, frms = np.repeat( np.r_[np.tile([False, True], len(end)), False], np.r_[np.c_[start - np.r_[0, end[:-1]], end - start].flat, 0] ) assert np.sum(end - start) == np.sum(frms) return frms
55,933
36.767725
142
py
pytorch-kaldi-gan
pytorch-kaldi-gan-master/parallel_dataset.py
import configparser import sox import logging import torch import torchaudio import numpy as np import matplotlib.pyplot as plt import os import random import shutil import subprocess import shlex import sys import math def validate_dir(dir_list): ''' Remove hidden files from directory list ''' for dir in dir_list: if dir.__contains__('.'): dir_list.remove(dir) return dir_list def get_utterances(dir_list): ''' Seperate utterances and transcription files ''' transcriptions = '' for dir in dir_list: if dir.__contains__('.txt'): transcriptions = dir dir_list.remove(dir) return transcriptions, dir_list def plot_waveform(waveform_tensor): ''' Plot tensor in a figure ''' with torch.no_grad(): plt.figure() plt.plot(waveform_tensor.t().detach().to("cpu").numpy()) plt.show() def normalize_tensor(tensor): ''' Normalize tensor between -1 and 1 ''' max_val = torch.abs(torch.max(tensor)) min_val = torch.abs(torch.min(tensor)) if max_val < min_val: max_val = min_val return torch.div(tensor, max_val) def get_average_power(clip): return torch.sqrt(torch.mean(clip ** 2)) def add_noise(clean_wav, noise_wav, signal_to_noise, rate_of_repeat = 0, sample_rate = 16000): output_len = len(clean_wav) noise_len = len(noise_wav) if rate_of_repeat > 0: # Add silence gaps between noise files temp_noise = torch.zeros(noise_len + sample_rate * rate_of_repeat) temp_noise[0:noise_len] = noise_wav noise_wav = temp_noise noise_len = len(noise_wav) if output_len < noise_len: # Choose a random part from the noise file if (noise_len - output_len - 1) > 10: rnd = random.randrange(0, (noise_len - output_len - 1)) else: rnd = 1 new_noise = noise_wav[rnd:(rnd + output_len)] clean_power = get_average_power(clean_wav) noisy_power = get_average_power(new_noise) factor = (clean_power / noisy_power) / (10 ** (signal_to_noise / 20.0)) # noise Coefficient for target SNR combined_signal = torch.add(clean_wav, torch.mul(new_noise, torch.sqrt(factor))) elif output_len > noise_len: # Repeat noise file to get same length as output file n_repeat = int(output_len / noise_len) n_remain = output_len - (n_repeat * noise_len) new_noise = torch.zeros(output_len) for i in range(n_repeat): new_noise[i*noise_len:(i+1)*noise_len] = noise_wav new_noise[n_repeat*noise_len:] = noise_wav[:n_remain] clean_power = get_average_power(clean_wav) noisy_power = get_average_power(new_noise) factor = (clean_power / noisy_power) / (10 ** (signal_to_noise / 20.0)) # noise Coefficient for target SNR combined_signal = torch.add(clean_wav, torch.mul(new_noise, torch.sqrt(factor))) else: # Both lengths are the same clean_power = get_average_power(clean_wav) noisy_power = get_average_power(noise_wav) factor = (clean_power / noisy_power) / (10 ** (signal_to_noise / 20.0)) # noise Coefficient for target SNR combined_signal = torch.add(clean_wav, torch.mul(noise_wav, torch.sqrt(factor))) combined_signal = normalize_tensor(combined_signal) return combined_signal.view(1, -1) def convolve_impulse(clean_wav, noise_wav, signal_to_noise): output_len = len(clean_wav) noise_len = len(noise_wav) clean_power = get_average_power(clean_wav) noisy_power = get_average_power(noise_wav) factor = math.sqrt((clean_power / noisy_power) / (10 ** (signal_to_noise / 20.0))) # noise Coefficient for target SNR if output_len < noise_len: # Choose a random part from the noise file rnd = random.randrange(0, (noise_len - output_len - 1)) new_noise = noise_wav[rnd:(rnd + int(output_len / 10))] else: # Noise is equal or shorther than clean sample new_noise = noise_wav new_noise = torch.mul(new_noise, factor) clean_np = clean_wav.numpy() noisy_np = new_noise.numpy() convolution = np.convolve(clean_np, noisy_np, 'same') combined_signal = torch.from_numpy(convolution) return combined_signal.view(1, -1) def get_random_noise_file(data_dir): ''' Return random noise file from the given directory ''' audio_list = os.listdir(data_dir) rnd = random.randrange(0, len(audio_list)) data_dir = os.path.join(data_dir, audio_list[rnd]) noise_tensor, n_sample_rate = torchaudio.load(data_dir) return noise_tensor def backup_and_replace(chapter_file, clean_word, noisy_word): if os.path.exists(chapter_file): chapter_txt = open(chapter_file, "r") temp_lines = [] entries = chapter_txt.readlines() for line in entries: temp_lines.append(line.replace(clean_word, noisy_word)) from_dir = chapter_file to_dir = chapter_file.replace(".TXT", "_BACKUP.TXT") shutil.copyfile(from_dir, to_dir) new_file = open(from_dir, "w") new_file.writelines(temp_lines) new_file.close() chapter_txt.close() def update_metadata_files(root_folder): chapter_file = os.path.join(root_folder, "CHAPTERS.TXT") speaker_file = os.path.join(root_folder, "SPEAKERS.TXT") clean_word = config["data"]["clean_word"] noisy_word = config["data"]["noisy_word"] backup_and_replace(chapter_file, clean_word, noisy_word) backup_and_replace(speaker_file, clean_word, noisy_word) def run_shell(cmd): import subprocess p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) (output, err) = p.communicate() p.wait() return output.decode('utf-8') def invoke_process_popen_poll_live(command, shellType=False, stdoutType=subprocess.PIPE): """runs subprocess with Popen/poll so that live stdout is shown""" try: process = subprocess.Popen( shlex.split(command), shell=shellType, stdout=stdoutType) except: print("ERROR {} while running {}".format(sys.exc_info()[1], command)) return None while True: output = process.stdout.readline() # used to check for empty output in Python2, but seems # to work with just poll in 2.7.12 and 3.5.2 # if output == '' and process.poll() is not None: if process.poll() is not None: break if output: print(output.strip().decode()) rc = process.poll() return rc def invoke_process_silent(command, shellType=False, stdoutType=subprocess.PIPE): try: process = subprocess.Popen( shlex.split(command), shell=shellType, stdout=stdoutType) except: print("ERROR {} while running {}".format(sys.exc_info()[1], command)) return None while True: output = process.stdout.readline() if process.poll() is not None: break if output: print() rc = process.poll() return rc logging.getLogger('sox').setLevel(logging.ERROR) # Reading global cfg file (first argument-mandatory file) cfg_file = sys.argv[1] if not (os.path.exists(cfg_file)): sys.stderr.write("ERROR: The config file %s does not exist!\n" % (cfg_file)) sys.exit(0) else: config = configparser.ConfigParser() config.read(cfg_file) # Set seed for noise adding random.seed(int(config["noise"]["seed"])) torch.manual_seed(int(config["noise"]["seed"])) # Output folder creation out_folder = config["data"]["out_folder"] if not os.path.exists(out_folder): os.makedirs(out_folder) data_folder = config["data"]["data_folder"] # Read cfg file options snr_db = int(config["noise"]["snr_db"]) snr = math.pow(10, snr_db / 10) snr_array = np.array(list(map(int, config["impulse"]["snrs"].split(",")))) snr_list = 10 ** (snr_array / 10) print("- Reading config file......OK!") if config["data"]["dataset"] == "librispeech": update_metadata_files(config["data"]["root_folder"]) speaker_lst = os.listdir(data_folder) speaker_lst = validate_dir(speaker_lst) # Create parallel dataset print("\n- Starting dataset parallelization.\n") speaker_count = 1 for speaker in speaker_lst: print(" Speaker {} / {} ".format(speaker_count, len(speaker_lst)).center(40, "=")) speaker_count += 1 speaker_dir = os.path.join(data_folder, speaker) # Get chapters by speaker chapter_lst = os.listdir(speaker_dir) chapter_lst = validate_dir(chapter_lst) chapter_count = 1 for chap in chapter_lst: print("Chapter {} / {} \r".format(chapter_count, len(chapter_lst)), end = '') chapter_count += 1 chapter_dir = os.path.join(speaker_dir, chap) # Get utterances by speaker per chapter utterance_lst = os.listdir(chapter_dir) utt_transcripitons, utterance_lst = get_utterances(utterance_lst) output_dir = os.path.join(out_folder, speaker, chap) if not os.path.exists(output_dir): os.makedirs(output_dir) transcription_from_dir = os.path.join(chapter_dir, utt_transcripitons) transcription_to_dir = os.path.join(output_dir, utt_transcripitons) shutil.copyfile(transcription_from_dir, transcription_to_dir) for utt in utterance_lst: utterance_dir = os.path.join(chapter_dir, utt) utt_save_dir = os.path.join(output_dir, utt) if config["styles"]["change_speed"] == "True": random_number = random.randint(0, 1) if random_number == 1: vol_fraction = 1 + float(config["impulse"]["volume_change"]) else: vol_fraction = 1 - float(config["impulse"]["volume_change"]) else: vol_fraction = 1 if config["styles"]["change_volume"] == "True": random_number = random.randint(0, 1) if random_number == 1: speed_fraction = 1 + float(config["impulse"]["speed_change"]) else: speed_fraction = 1 - float(config["impulse"]["speed_change"]) else: speed_fraction = 1 if config["styles"]["change_speed"] == "True" or config["styles"]["change_volume"] == "True": # create a transformer tfm = sox.Transformer() tfm.tempo(speed_fraction, 's') tfm.vol(vol_fraction) tfm.build_file( input_filepath = utterance_dir, sample_rate_in = int(config["impulse"]["sample_rate"]), output_filepath = utt_save_dir ) utterance_dir = utt_save_dir if config["styles"]["additive_noise"] == "True": recording, sample_rate = torchaudio.load(utterance_dir) noise = get_random_noise_file(config["noise"]["noise_dir"]) recording = normalize_tensor(recording) recording = add_noise(recording[0], noise[0], snr) torchaudio.save(utt_save_dir, recording, sample_rate = sample_rate) utterance_dir = utt_save_dir if config["styles"]["add_impulse"] == "True": recording, sample_rate = torchaudio.load(utterance_dir) noise = get_random_noise_file(config["impulse"]["impulse_dir"]) recording = normalize_tensor(recording) random_snr_value = random.randrange(len(snr_list)) recording = convolve_impulse(recording[0], noise[0], snr_list[random_snr_value]) recording = normalize_tensor(recording) torchaudio.save(utt_save_dir, recording, sample_rate = sample_rate) utterance_dir = utt_save_dir downsample_clean = False if config["styles"]["wav49_encode"] == "True": output_sampling_rate = "16000" if utterance_dir == utt_save_dir: encode = "sox -G " + utterance_dir + " -r 8000 -c 1 -e gsm " + utterance_dir.replace(".flac", ".wav") invoke_process_silent(encode) removed = "rm " + utterance_dir invoke_process_silent(removed) flac_convert = "sox -G " + utterance_dir.replace(".flac", ".wav") + " -r " + output_sampling_rate + " " + utterance_dir invoke_process_silent(flac_convert) removed_wav = "rm " + utterance_dir.replace(".flac", ".wav") invoke_process_silent(removed_wav) else: encode = "sox -G " + utterance_dir + " -r 8000 -c 1 -e gsm " + utt_save_dir.replace(".flac", ".wav") invoke_process_silent(encode) flac_convert = "sox -G " + utt_save_dir.replace(".flac", ".wav") + " -r " + output_sampling_rate + " " + utt_save_dir invoke_process_silent(flac_convert) removed_wav = "rm " + utt_save_dir.replace(".flac", ".wav") invoke_process_silent(removed_wav) elif downsample_clean: encode = "sox -G " + utterance_dir + " -r 8000 -c 1 " + utt_save_dir invoke_process_silent(encode) cmd = "kaldi_decoding_scripts/create_parallel_dataset.sh " \ + os.path.basename(config["data"]["out_folder"]) + " " \ + os.path.dirname(config["data"]["root_folder"]) invoke_process_popen_poll_live(cmd) print("\n\nDataset created successfully\n") elif config["data"]["dataset"] == "swahili": speaker_lst = os.listdir(data_folder) speaker_lst = validate_dir(speaker_lst) # Create parallel dataset print("\n- Starting dataset parallelization.\n") speaker_count = 1 for speaker in speaker_lst: print(" Speaker {} / {} ".format(speaker_count, len(speaker_lst)).center(40, "=")) speaker_count += 1 speaker_dir = os.path.join(data_folder, speaker) # Get utterances by speaker per chapter utterance_lst = os.listdir(speaker_dir) output_dir = os.path.join(out_folder, speaker) if not os.path.exists(output_dir): os.makedirs(output_dir) for utt in utterance_lst: utterance_dir = os.path.join(speaker_dir, utt) utt_save_dir = os.path.join(output_dir, utt) if config["styles"]["change_speed"] == "True": random_number = random.randint(0, 1) if random_number == 1: vol_fraction = 1 + float(config["impulse"]["volume_change"]) else: vol_fraction = 1 - float(config["impulse"]["volume_change"]) else: vol_fraction = 1 if config["styles"]["change_volume"] == "True": random_number = random.randint(0, 1) if random_number == 1: speed_fraction = 1 + float(config["impulse"]["speed_change"]) else: speed_fraction = 1 - float(config["impulse"]["speed_change"]) else: speed_fraction = 1 if config["styles"]["change_speed"] == "True" or config["styles"]["change_volume"] == "True": # create a transformer tfm = sox.Transformer() tfm.tempo(speed_fraction, 's') tfm.vol(vol_fraction) tfm.build_file( input_filepath = utterance_dir, sample_rate_in = int(config["impulse"]["sample_rate"]), output_filepath = utt_save_dir ) utterance_dir = utt_save_dir if config["styles"]["additive_noise"] == "True": recording, sample_rate = torchaudio.load(utterance_dir) noise = get_random_noise_file(config["noise"]["noise_dir"]) recording = normalize_tensor(recording) recording = add_noise(recording[0], noise[0], snr) torchaudio.save(utt_save_dir, recording, sample_rate = sample_rate) utterance_dir = utt_save_dir if config["styles"]["add_impulse"] == "True": recording, sample_rate = torchaudio.load(utterance_dir) noise = get_random_noise_file(config["impulse"]["impulse_dir"]) recording = normalize_tensor(recording) random_snr_value = random.randrange(len(snr_list)) recording = convolve_impulse(recording[0], noise[0], snr_list[random_snr_value]) recording = normalize_tensor(recording) torchaudio.save(utt_save_dir, recording, sample_rate = sample_rate) utterance_dir = utt_save_dir '''cmd = "kaldi_decoding_scripts/create_parallel_dataset.sh " \ + os.path.basename(config["data"]["out_folder"]) + " " \ + os.path.dirname(config["data"]["root_folder"]) invoke_process_popen_poll_live(cmd)''' print("\n\nDataset created successfully\n")
17,550
34.031936
143
py
pytorch-kaldi-gan
pytorch-kaldi-gan-master/plot_acc_and_loss.py
########################################################## # pytorch-kaldi v.0.1 # Mirco Ravanelli, Titouan Parcollet # Mila, University of Montreal # October 2018 ########################################################## import sys import configparser import os from utils import create_curves # Checking arguments if len(sys.argv) != 2: print("ERROR: Please provide only the path of the cfg_file as : python plot_acc_and_loss.py cfg/TIMIT_MLP_mfcc.cfg") # Checking if the cfg_file exists and loading it cfg_file = sys.argv[1] if not (os.path.exists(cfg_file)): sys.stderr.write("ERROR: The config file %s does not exist !\n" % (cfg_file)) sys.exit(0) else: config = configparser.ConfigParser() config.read(cfg_file) # Getting the parameters valid_data_lst = config["data_use"]["valid_with"].split(",") out_folder = config["exp"]["out_folder"] N_ep = int(config["exp"]["N_epochs_tr"]) # Handling call without running run_exp.py before if not (os.path.exists(out_folder + "res.res")): sys.stderr.write("ERROR: Please run the experiment in order to get results to plot first !\n") sys.exit(0) # Creating files and curves create_curves(out_folder, N_ep, valid_data_lst)
1,203
30.684211
120
py
pytorch-kaldi-gan
pytorch-kaldi-gan-master/save_raw_fea.py
########################################################## # pytorch-kaldi v.0.1 # Mirco Ravanelli, Titouan Parcollet # Mila, University of Montreal # October 2018 # # Description: This script generates kaldi ark files containing raw features. # The file list must be a file containing "snt_id file.wav". # Note that only wav files are supported here (sphere or other format are not supported) ########################################################## import scipy.io.wavfile import math import numpy as np import os from data_io import read_vec_int_ark, write_mat # Run it for all the data chunks (e.g., train, dev, test) => uncomment lab_folder = "/users/parcollet/KALDI/kaldi-trunk/egs/timit/s5/exp/dnn4_pretrain-dbn_dnn_ali_test" lab_opts = "ali-to-pdf" out_folder = "/users/parcollet/KALDI/kaldi-trunk/egs/timit/s5/data/raw_TIMIT_200ms/test" wav_lst = "/users/parcollet/KALDI/kaldi-trunk/egs/timit/s5/data/test/wav.lst" scp_file_out = "/users/parcollet/KALDI/kaldi-trunk/egs/timit/s5/data/raw_TIMIT_200ms/test/feats_raw.scp" # lab_folder='quick_test/dnn4_pretrain-dbn_dnn_ali_dev' # lab_opts='ali-to-pdf' # out_folder='raw_TIMIT_200ms/dev' # wav_lst='/home/mirco/pytorch-kaldi-new/quick_test/data/dev/wav_lst.scp' # scp_file_out='quick_test/data/dev/feats_raw.scp' # lab_folder='quick_test/dnn4_pretrain-dbn_dnn_ali_test' # lab_opts='ali-to-pdf' # out_folder='raw_TIMIT_200ms/test' # wav_lst='/home/mirco/pytorch-kaldi-new/quick_test/data/test/wav_lst.scp' # scp_file_out='quick_test/data/test/feats_raw.scp' sig_fs = 16000 # Hz sig_wlen = 200 # ms lab_fs = 16000 # Hz lab_wlen = 25 # ms lab_wshift = 10 # ms sig_wlen_samp = int((sig_fs * sig_wlen) / 1000) lab_wlen_samp = int((lab_fs * lab_wlen) / 1000) lab_wshift_samp = int((lab_fs * lab_wshift) / 1000) # Create the output folder try: os.stat(out_folder) except: os.makedirs(out_folder) # Creare the scp file scp_file = open(scp_file_out, "w") # reading the labels lab = { k: v for k, v in read_vec_int_ark( "gunzip -c " + lab_folder + "/ali*.gz | " + lab_opts + " " + lab_folder + "/final.mdl ark:- ark:-|", out_folder ) } # reading the list file with open(wav_lst) as f: sig_lst = f.readlines() sig_lst = [x.strip() for x in sig_lst] for sig_file in sig_lst: sig_id = sig_file.split(" ")[0] sig_path = sig_file.split(" ")[1] [fs, signal] = scipy.io.wavfile.read(sig_path) signal = signal.astype(float) / 32768 signal = signal / np.max(np.abs(signal)) cnt_fr = 0 beg_samp = 0 frame_all = [] while beg_samp + lab_wlen_samp < signal.shape[0]: sample_fr = np.zeros(sig_wlen_samp) central_sample_lab = int(((beg_samp + lab_wlen_samp / 2) - 1)) central_fr_index = int(((sig_wlen_samp / 2) - 1)) beg_signal_fr = int(central_sample_lab - (sig_wlen_samp / 2)) end_signal_fr = int(central_sample_lab + (sig_wlen_samp / 2)) if beg_signal_fr >= 0 and end_signal_fr <= signal.shape[0]: sample_fr = signal[beg_signal_fr:end_signal_fr] else: if beg_signal_fr < 0: n_left_samples = central_sample_lab sample_fr[central_fr_index - n_left_samples + 1 :] = signal[0:end_signal_fr] if end_signal_fr > signal.shape[0]: n_right_samples = signal.shape[0] - central_sample_lab sample_fr[0 : central_fr_index + n_right_samples + 1] = signal[beg_signal_fr:] frame_all.append(sample_fr) cnt_fr = cnt_fr + 1 beg_samp = beg_samp + lab_wshift_samp frame_all = np.asarray(frame_all) # Save the matrix into a kaldi ark out_file = out_folder + "/" + sig_id + ".ark" write_mat(out_folder, out_file, frame_all, key=sig_id) print(sig_id) scp_file.write(sig_id + " " + out_folder + "/" + sig_id + ".ark:" + str(len(sig_id) + 1) + "\n") N_fr_comp = 1 + math.floor((signal.shape[0] - 400) / 160) # print("%s %i %i "%(lab[sig_id].shape[0],N_fr_comp,cnt_fr)) scp_file.close()
4,010
31.877049
119
py
pytorch-kaldi-gan
pytorch-kaldi-gan-master/kaldi_decoding_scripts/utils/reverse_arpa.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright 2012 Mirko Hannemann BUT, mirko.hannemann@gmail.com import sys import codecs # for UTF-8/unicode if len(sys.argv) != 2: print 'usage: reverse_arpa arpa.in' sys.exit() arpaname = sys.argv[1] #\data\ #ngram 1=4 #ngram 2=2 #ngram 3=2 # #\1-grams: #-5.234679 a -3.3 #-3.456783 b #0.0000000 <s> -2.5 #-4.333333 </s> # #\2-grams: #-1.45678 a b -3.23 #-1.30490 <s> a -4.2 # #\3-grams: #-0.34958 <s> a b #-0.23940 a b </s> #\end\ # read language model in ARPA format try: file = codecs.open(arpaname, "r", "utf-8") except IOError: print 'file not found: ' + arpaname sys.exit() text=file.readline() while (text and text[:6] != "\\data\\"): text=file.readline() if not text: print "invalid ARPA file" sys.exit() #print text, while (text and text[:5] != "ngram"): text=file.readline() # get ngram counts cngrams=[] n=0 while (text and text[:5] == "ngram"): ind = text.split("=") counts = int(ind[1].strip()) r = ind[0].split() read_n = int(r[1].strip()) if read_n != n+1: print "invalid ARPA file:", text sys.exit() n = read_n cngrams.append(counts) #print text, text=file.readline() # read all n-grams order by order sentprob = 0.0 # sentence begin unigram ngrams=[] inf=float("inf") for n in range(1,len(cngrams)+1): # unigrams, bigrams, trigrams while (text and "-grams:" not in text): text=file.readline() if n != int(text[1]): print "invalid ARPA file:", text sys.exit() #print text,cngrams[n-1] this_ngrams={} # stores all read ngrams for ng in range(cngrams[n-1]): while (text and len(text.split())<2): text=file.readline() if (not text) or ((len(text.split())==1) and (("-grams:" in text) or (text[:5] == "\\end\\"))): break if (not text) or ((len(text.split())==1) and (("-grams:" in text) or (text[:5] == "\\end\\"))): break # to deal with incorrect ARPA files entry = text.split() prob = float(entry[0]) if len(entry)>n+1: back = float(entry[-1]) words = entry[1:n+1] else: back = 0.0 words = entry[1:] ngram = " ".join(words) if (n==1) and words[0]=="<s>": sentprob = prob prob = 0.0 this_ngrams[ngram] = (prob,back) #print prob,ngram.encode("utf-8"),back for x in range(n-1,0,-1): # add all missing backoff ngrams for reversed lm l_ngram = " ".join(words[:x]) # shortened ngram r_ngram = " ".join(words[1:1+x]) # shortened ngram with offset one if l_ngram not in ngrams[x-1]: # create missing ngram ngrams[x-1][l_ngram] = (0.0,inf) #print ngram, "create 0.0", l_ngram, "inf" if r_ngram not in ngrams[x-1]: # create missing ngram ngrams[x-1][r_ngram] = (0.0,inf) #print ngram, "create 0.0", r_ngram, "inf",x,n,h_ngram # add all missing backoff ngrams for forward lm h_ngram = " ".join(words[n-x:]) # shortened history if h_ngram not in ngrams[x-1]: # create missing ngram ngrams[x-1][h_ngram] = (0.0,inf) #print "create inf", h_ngram, "0.0" text=file.readline() if (not text) or ((len(text.split())==1) and (("-grams:" in text) or (text[:5] == "\\end\\"))): break ngrams.append(this_ngrams) while (text and text[:5] != "\\end\\"): text=file.readline() if not text: print "invalid ARPA file" sys.exit() file.close() #print text, #fourgram "maxent" model (b(ABCD)=0): #p(A)+b(A) A 0 #p(AB)+b(AB)-b(A)-p(B) AB 0 #p(ABC)+b(ABC)-b(AB)-p(BC) ABC 0 #p(ABCD)+b(ABCD)-b(ABC)-p(BCD) ABCD 0 #fourgram reverse ARPA model (b(ABCD)=0): #p(A)+b(A) A 0 #p(AB)+b(AB)-p(B)+p(A) BA 0 #p(ABC)+b(ABC)-p(BC)+p(AB)-p(B)+p(A) CBA 0 #p(ABCD)+b(ABCD)-p(BCD)+p(ABC)-p(BC)+p(AB)-p(B)+p(A) DCBA 0 # compute new reversed ARPA model print "\\data\\" for n in range(1,len(cngrams)+1): # unigrams, bigrams, trigrams print "ngram "+str(n)+"="+str(len(ngrams[n-1].keys())) offset = 0.0 for n in range(1,len(cngrams)+1): # unigrams, bigrams, trigrams print "\\"+str(n)+"-grams:" keys = ngrams[n-1].keys() keys.sort() for ngram in keys: prob = ngrams[n-1][ngram] # reverse word order words = ngram.split() rstr = " ".join(reversed(words)) # swap <s> and </s> rev_ngram = rstr.replace("<s>","<temp>").replace("</s>","<s>").replace("<temp>","</s>") revprob = prob[0] if (prob[1] != inf): # only backoff weights from not newly created ngrams revprob = revprob + prob[1] #print prob[0],prob[1] # sum all missing terms in decreasing ngram order for x in range(n-1,0,-1): l_ngram = " ".join(words[:x]) # shortened ngram if l_ngram not in ngrams[x-1]: sys.stderr.write(rev_ngram+": not found "+l_ngram+"\n") p_l = ngrams[x-1][l_ngram][0] #print p_l,l_ngram revprob = revprob + p_l r_ngram = " ".join(words[1:1+x]) # shortened ngram with offset one if r_ngram not in ngrams[x-1]: sys.stderr.write(rev_ngram+": not found "+r_ngram+"\n") p_r = ngrams[x-1][r_ngram][0] #print -p_r,r_ngram revprob = revprob - p_r if n != len(cngrams): #not highest order back = 0.0 if rev_ngram[:3] == "<s>": # special handling since arpa2fst ignores <s> weight if n == 1: offset = revprob # remember <s> weight revprob = sentprob # apply <s> weight from forward model back = offset elif n == 2: revprob = revprob + offset # add <s> weight to bigrams starting with <s> if (prob[1] != inf): # only backoff weights from not newly created ngrams print revprob,rev_ngram.encode("utf-8"),back else: print revprob,rev_ngram.encode("utf-8"),"-100000.0" else: # highest order - no backoff weights if (n==2) and (rev_ngram[:3] == "<s>"): revprob = revprob + offset print revprob,rev_ngram.encode("utf-8") print "\\end\\"
5,846
29.936508
107
py
pytorch-kaldi-gan
pytorch-kaldi-gan-master/kaldi_decoding_scripts/utils/filt.py
#!/usr/bin/env python # Apache 2.0 from __future__ import print_function import sys vocab = set() with open(sys.argv[1]) as vocabfile: for line in vocabfile: vocab.add(line.strip()) with open(sys.argv[2]) as textfile: for line in textfile: print(" ".join(map(lambda word: word if word in vocab else "<UNK>", line.strip().split())))
360
21.5625
99
py
pytorch-kaldi-gan
pytorch-kaldi-gan-master/kaldi_decoding_scripts/utils/nnet/make_nnet_proto.py
#!/usr/bin/env python # Copyright 2014 Brno University of Technology (author: Karel Vesely) # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED # WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, # MERCHANTABLITY OR NON-INFRINGEMENT. # See the Apache 2 License for the specific language governing permissions and # limitations under the License. # Generated Nnet prototype, to be initialized by 'nnet-initialize'. from __future__ import print_function import math, random, sys, re ### ### Parse options ### from optparse import OptionParser usage = "%prog [options] <feat-dim> <num-leaves> <num-hid-layers> <num-hid-neurons> >nnet-proto-file" parser = OptionParser(usage) parser.add_option( "--no-proto-head", dest="with_proto_head", help="Do not put <NnetProto> head-tag in the prototype [default: %default]", default=True, action="store_false", ) parser.add_option( "--no-softmax", dest="with_softmax", help="Do not put <SoftMax> in the prototype [default: %default]", default=True, action="store_false", ) parser.add_option( "--block-softmax-dims", dest="block_softmax_dims", help="Generate <BlockSoftmax> with dims D1:D2:D3 [default: %default]", default="", type="string", ) parser.add_option( "--activation-type", dest="activation_type", help="Select type of activation function : (<Sigmoid>|<Tanh>) [default: %default]", default="<Sigmoid>", type="string", ) parser.add_option( "--hid-bias-mean", dest="hid_bias_mean", help="Set bias for hidden activations [default: %default]", default=-2.0, type="float", ) parser.add_option( "--hid-bias-range", dest="hid_bias_range", help="Set bias range for hidden activations (+/- 1/2 range around mean) [default: %default]", default=4.0, type="float", ) parser.add_option( "--param-stddev-factor", dest="param_stddev_factor", help="Factor to rescale Normal distriburtion for initalizing weight matrices [default: %default]", default=0.1, type="float", ) parser.add_option( "--bottleneck-dim", dest="bottleneck_dim", help="Make bottleneck network with desired bn-dim (0 = no bottleneck) [default: %default]", default=0, type="int", ) parser.add_option( "--no-glorot-scaled-stddev", dest="with_glorot", help="Generate normalized weights according to X.Glorot paper, but mapping U->N with same variance (factor sqrt(x/(dim_in+dim_out)))", action="store_false", default=True, ) parser.add_option( "--no-smaller-input-weights", dest="smaller_input_weights", help="Disable 1/12 reduction of stddef in input layer [default: %default]", action="store_false", default=True, ) parser.add_option( "--no-bottleneck-trick", dest="bottleneck_trick", help="Disable smaller initial weights and learning rate around bottleneck", action="store_false", default=True, ) parser.add_option( "--max-norm", dest="max_norm", help="Max radius of neuron-weights in L2 space (if longer weights get shrinked, not applied to last layer, 0.0 = disable) [default: %default]", default=0.0, type="float", ) (o, args) = parser.parse_args() if len(args) != 4: parser.print_help() sys.exit(1) (feat_dim, num_leaves, num_hid_layers, num_hid_neurons) = list(map(int, args)) ### End parse options # Check assert feat_dim > 0 assert num_leaves > 0 assert num_hid_layers >= 0 assert num_hid_neurons > 0 if o.block_softmax_dims: assert sum(map(int, re.split("[,:]", o.block_softmax_dims))) == num_leaves # posible separators : ',' ':' # Optionaly scale def Glorot(dim1, dim2): if o.with_glorot: # 35.0 = magic number, gives ~1.0 in inner layers for hid-dim 1024dim, return 35.0 * math.sqrt(2.0 / (dim1 + dim2)) else: return 1.0 ### ### Print prototype of the network ### # NO HIDDEN LAYER, ADDING BOTTLENECK! # No hidden layer while adding bottleneck means: # - add bottleneck layer + hidden layer + output layer if num_hid_layers == 0 and o.bottleneck_dim != 0: assert o.bottleneck_dim > 0 assert num_hid_layers == 0 if o.with_proto_head: print("<NnetProto>") if o.bottleneck_trick: # 25% smaller stddev -> small bottleneck range, 10x smaller learning rate print( "<LinearTransform> <InputDim> %d <OutputDim> %d <ParamStddev> %f <LearnRateCoef> %f" % (feat_dim, o.bottleneck_dim, (o.param_stddev_factor * Glorot(feat_dim, o.bottleneck_dim) * 0.75), 0.1) ) # 25% smaller stddev -> smaller gradient in prev. layer, 10x smaller learning rate for weigts & biases print( "<AffineTransform> <InputDim> %d <OutputDim> %d <BiasMean> %f <BiasRange> %f <ParamStddev> %f <LearnRateCoef> %f <BiasLearnRateCoef> %f <MaxNorm> %f" % ( o.bottleneck_dim, num_hid_neurons, o.hid_bias_mean, o.hid_bias_range, (o.param_stddev_factor * Glorot(o.bottleneck_dim, num_hid_neurons) * 0.75), 0.1, 0.1, o.max_norm, ) ) else: print( "<LinearTransform> <InputDim> %d <OutputDim> %d <ParamStddev> %f" % (feat_dim, o.bottleneck_dim, (o.param_stddev_factor * Glorot(feat_dim, o.bottleneck_dim))) ) print( "<AffineTransform> <InputDim> %d <OutputDim> %d <BiasMean> %f <BiasRange> %f <ParamStddev> %f <MaxNorm> %f" % ( o.bottleneck_dim, num_hid_neurons, o.hid_bias_mean, o.hid_bias_range, (o.param_stddev_factor * Glorot(o.bottleneck_dim, num_hid_neurons)), o.max_norm, ) ) print("%s <InputDim> %d <OutputDim> %d" % (o.activation_type, num_hid_neurons, num_hid_neurons)) # Non-linearity # Last AffineTransform (10x smaller learning rate on bias) print( "<AffineTransform> <InputDim> %d <OutputDim> %d <BiasMean> %f <BiasRange> %f <ParamStddev> %f <LearnRateCoef> %f <BiasLearnRateCoef> %f" % ( num_hid_neurons, num_leaves, 0.0, 0.0, (o.param_stddev_factor * Glorot(num_hid_neurons, num_leaves)), 1.0, 0.1, ) ) # Optionaly append softmax if o.with_softmax: if o.block_softmax_dims == "": print("<Softmax> <InputDim> %d <OutputDim> %d" % (num_leaves, num_leaves)) else: print( "<BlockSoftmax> <InputDim> %d <OutputDim> %d <BlockDims> %s" % (num_leaves, num_leaves, o.block_softmax_dims) ) print("</NnetProto>") # We are done! sys.exit(0) # NO HIDDEN LAYERS! # Add only last layer (logistic regression) if num_hid_layers == 0: if o.with_proto_head: print("<NnetProto>") print( "<AffineTransform> <InputDim> %d <OutputDim> %d <BiasMean> %f <BiasRange> %f <ParamStddev> %f" % (feat_dim, num_leaves, 0.0, 0.0, (o.param_stddev_factor * Glorot(feat_dim, num_leaves))) ) if o.with_softmax: if o.block_softmax_dims == "": print("<Softmax> <InputDim> %d <OutputDim> %d" % (num_leaves, num_leaves)) else: print( "<BlockSoftmax> <InputDim> %d <OutputDim> %d <BlockDims> %s" % (num_leaves, num_leaves, o.block_softmax_dims) ) print("</NnetProto>") # We are done! sys.exit(0) # THE USUAL DNN PROTOTYPE STARTS HERE! # Assuming we have >0 hidden layers, assert num_hid_layers > 0 # Begin the prototype, if o.with_proto_head: print("<NnetProto>") # First AffineTranform, print( "<AffineTransform> <InputDim> %d <OutputDim> %d <BiasMean> %f <BiasRange> %f <ParamStddev> %f <MaxNorm> %f" % ( feat_dim, num_hid_neurons, o.hid_bias_mean, o.hid_bias_range, ( o.param_stddev_factor * Glorot(feat_dim, num_hid_neurons) * (math.sqrt(1.0 / 12.0) if o.smaller_input_weights else 1.0) ), o.max_norm, ) ) # Note.: compensating dynamic range mismatch between input features and Sigmoid-hidden layers, # i.e. mapping the std-dev of N(0,1) (input features) to std-dev of U[0,1] (sigmoid-outputs). # This is done by multiplying with stddev(U[0,1]) = sqrt(1/12). # The stddev of weights is consequently reduced by 0.29x. print("%s <InputDim> %d <OutputDim> %d" % (o.activation_type, num_hid_neurons, num_hid_neurons)) # Internal AffineTransforms, for i in range(num_hid_layers - 1): print( "<AffineTransform> <InputDim> %d <OutputDim> %d <BiasMean> %f <BiasRange> %f <ParamStddev> %f <MaxNorm> %f" % ( num_hid_neurons, num_hid_neurons, o.hid_bias_mean, o.hid_bias_range, (o.param_stddev_factor * Glorot(num_hid_neurons, num_hid_neurons)), o.max_norm, ) ) print("%s <InputDim> %d <OutputDim> %d" % (o.activation_type, num_hid_neurons, num_hid_neurons)) # Optionaly add bottleneck, if o.bottleneck_dim != 0: assert o.bottleneck_dim > 0 if o.bottleneck_trick: # 25% smaller stddev -> small bottleneck range, 10x smaller learning rate print( "<LinearTransform> <InputDim> %d <OutputDim> %d <ParamStddev> %f <LearnRateCoef> %f" % ( num_hid_neurons, o.bottleneck_dim, (o.param_stddev_factor * Glorot(num_hid_neurons, o.bottleneck_dim) * 0.75), 0.1, ) ) # 25% smaller stddev -> smaller gradient in prev. layer, 10x smaller learning rate for weigts & biases print( "<AffineTransform> <InputDim> %d <OutputDim> %d <BiasMean> %f <BiasRange> %f <ParamStddev> %f <LearnRateCoef> %f <BiasLearnRateCoef> %f <MaxNorm> %f" % ( o.bottleneck_dim, num_hid_neurons, o.hid_bias_mean, o.hid_bias_range, (o.param_stddev_factor * Glorot(o.bottleneck_dim, num_hid_neurons) * 0.75), 0.1, 0.1, o.max_norm, ) ) else: # Same learninig-rate and stddev-formula everywhere, print( "<LinearTransform> <InputDim> %d <OutputDim> %d <ParamStddev> %f" % (num_hid_neurons, o.bottleneck_dim, (o.param_stddev_factor * Glorot(num_hid_neurons, o.bottleneck_dim))) ) print( "<AffineTransform> <InputDim> %d <OutputDim> %d <BiasMean> %f <BiasRange> %f <ParamStddev> %f <MaxNorm> %f" % ( o.bottleneck_dim, num_hid_neurons, o.hid_bias_mean, o.hid_bias_range, (o.param_stddev_factor * Glorot(o.bottleneck_dim, num_hid_neurons)), o.max_norm, ) ) print("%s <InputDim> %d <OutputDim> %d" % (o.activation_type, num_hid_neurons, num_hid_neurons)) # Last AffineTransform (10x smaller learning rate on bias) print( "<AffineTransform> <InputDim> %d <OutputDim> %d <BiasMean> %f <BiasRange> %f <ParamStddev> %f <LearnRateCoef> %f <BiasLearnRateCoef> %f" % (num_hid_neurons, num_leaves, 0.0, 0.0, (o.param_stddev_factor * Glorot(num_hid_neurons, num_leaves)), 1.0, 0.1) ) # Optionaly append softmax if o.with_softmax: if o.block_softmax_dims == "": print("<Softmax> <InputDim> %d <OutputDim> %d" % (num_leaves, num_leaves)) else: print( "<BlockSoftmax> <InputDim> %d <OutputDim> %d <BlockDims> %s" % (num_leaves, num_leaves, o.block_softmax_dims) ) # End the prototype print("</NnetProto>") # We are done! sys.exit(0)
12,177
33.498584
161
py
pytorch-kaldi-gan
pytorch-kaldi-gan-master/kaldi_decoding_scripts/utils/nnet/gen_dct_mat.py
#!/usr/bin/env python # Copyright 2012 Brno University of Technology (author: Karel Vesely) # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED # WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, # MERCHANTABLITY OR NON-INFRINGEMENT. # See the Apache 2 License for the specific language governing permissions and # limitations under the License. # ./gen_dct_mat.py # script generates matrix with DCT transform, which is sparse # and takes into account that data-layout is along frequency axis, # while DCT is done along temporal axis. from __future__ import print_function from math import * import sys from optparse import OptionParser parser = OptionParser() parser.add_option("--fea-dim", dest="dim", help="feature dimension") parser.add_option("--splice", dest="splice", help="applied splice value") parser.add_option("--dct-basis", dest="dct_basis", help="number of DCT basis") (options, args) = parser.parse_args() if options.dim == None: parser.print_help() sys.exit(1) dim = int(options.dim) splice = int(options.splice) dct_basis = int(options.dct_basis) timeContext = 2 * splice + 1 # generate the DCT matrix M_PI = 3.1415926535897932384626433832795 M_SQRT2 = 1.4142135623730950488016887 # generate sparse DCT matrix print("[") for k in range(dct_basis): for m in range(dim): for n in range(timeContext): if n == 0: print(m * "0 ", end=" ") else: print((dim - 1) * "0 ", end=" ") print(str(sqrt(2.0 / timeContext) * cos(M_PI / timeContext * k * (n + 0.5))), end=" ") if n == timeContext - 1: print((dim - m - 1) * "0 ", end=" ") print() print() print("]")
2,057
29.264706
98
py
pytorch-kaldi-gan
pytorch-kaldi-gan-master/kaldi_decoding_scripts/utils/nnet/make_cnn2d_proto.py
#!/usr/bin/python # Copyright 2014 Brno University of Technology (author: Karel Vesely) # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED # WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, # MERCHANTABLITY OR NON-INFRINGEMENT. # See the Apache 2 License for the specific language governing permissions and # limitations under the License. # Generated Nnet prototype, to be initialized by 'nnet-initialize'. from __future__ import print_function import math, random, sys, warnings from optparse import OptionParser ### ### Parse options ### usage = "%prog [options] <feat-dim> <num-leaves> <num-hidden-layers> <num-hidden-neurons> >nnet-proto-file" parser = OptionParser(usage) parser.add_option( "--activation-type", dest="activation_type", help="Select type of activation function : (<Sigmoid>|<Tanh>) [default: %default]", default="<Sigmoid>", type="string", ) parser.add_option( "--cnn1-num-filters", dest="cnn1_num_filters", help="Number of filters in first convolutional layer [default: %default]", default=128, type="int", ) # this is given by splice # parser.add_option('--cnn1-fmap-x-len', dest='cnn1_fmap_x_len', # help='Size of cnn1-fmap-x-len [default: %default]', # default=11, type='int') # this should be equal to feat_raw_dim # parser.add_option('--cnn1-fmap-y-len', dest='cnn1_fmap_y_len', # help='Size of cnn1-fmap-y-len [default: %default]', # default=32, type='int') parser.add_option( "--cnn1-filt-x-len", dest="cnn1_filt_x_len", help="Size of cnn1-filt-x-len [default: %default]", default=9, type="int", ) parser.add_option( "--cnn1-filt-y-len", dest="cnn1_filt_y_len", help="Size of cnn1-filt-y-len [default: %default]", default=9, type="int", ) parser.add_option( "--cnn1-filt-x-step", dest="cnn1_filt_x_step", help="Size of cnn1-filt-x-step [default: %default]", default=1, type="int", ) parser.add_option( "--cnn1-filt-y-step", dest="cnn1_filt_y_step", help="Size of cnn1-filt-y-step [default: %default]", default=1, type="int", ) parser.add_option( "--cnn1-connect-fmap", dest="cnn1_connect_fmap", help="Size of cnn1-connect-fmap [default: %default]", default=0, type="int", ) parser.add_option( "--pool1-x-len", dest="pool1_x_len", help="Size of pool1-filt-x-len [default: %default]", default=1, type="int" ) parser.add_option( "--pool1-x-step", dest="pool1_x_step", help="Size of pool1-x-step [default: %default]", default=1, type="int" ) # parser.add_option( "--pool1-y-len", dest="pool1_y_len", help="Size of pool1-y-len [default: %default]", default=3, type="int" ) parser.add_option( "--pool1-y-step", dest="pool1_y_step", help="Size of pool1-y-step [default: %default]", default=3, type="int" ) parser.add_option( "--pool1-type", dest="pool1_type", help="Type of pooling (Max || Average) [default: %default]", default="Max", type="string", ) parser.add_option( "--cnn2-num-filters", dest="cnn2_num_filters", help="Number of filters in first convolutional layer [default: %default]", default=256, type="int", ) parser.add_option( "--cnn2-filt-x-len", dest="cnn2_filt_x_len", help="Size of cnn2-filt-x-len [default: %default]", default=3, type="int", ) parser.add_option( "--cnn2-filt-y-len", dest="cnn2_filt_y_len", help="Size of cnn2-filt-y-len [default: %default]", default=4, type="int", ) parser.add_option( "--cnn2-filt-x-step", dest="cnn2_filt_x_step", help="Size of cnn2-filt-x-step [default: %default]", default=1, type="int", ) parser.add_option( "--cnn2-filt-y-step", dest="cnn2_filt_y_step", help="Size of cnn2-filt-y-step [default: %default]", default=1, type="int", ) parser.add_option( "--cnn2-connect-fmap", dest="cnn2_connect_fmap", help="Size of cnn2-connect-fmap [default: %default]", default=1, type="int", ) parser.add_option( "--pitch-dim", dest="pitch_dim", help="Number of features representing pitch [default: %default]", default=0, type="int", ) parser.add_option( "--delta-order", dest="delta_order", help="Order of delta features [default: %default]", default=2, type="int" ) parser.add_option("--splice", dest="splice", help="Length of splice [default: %default]", default=5, type="int") parser.add_option( "--dir", dest="dirct", help="Directory, where network prototypes will be saved [default: %default]", default=".", type="string", ) parser.add_option( "--num-pitch-neurons", dest="num_pitch_neurons", help="Number of neurons in layers processing pitch features [default: %default]", default="200", type="int", ) (o, args) = parser.parse_args() if len(args) != 1: parser.print_help() sys.exit(1) feat_dim = int(args[0]) ### End parse options feat_raw_dim = ( feat_dim / (o.delta_order + 1) / (o.splice * 2 + 1) - o.pitch_dim ) # we need number of feats without deltas and splice and pitch o.cnn1_fmap_y_len = feat_raw_dim o.cnn1_fmap_x_len = o.splice * 2 + 1 # Check assert feat_dim > 0 assert o.pool1_type == "Max" or o.pool1_type == "Average" ## Extra checks if dimensions are matching, if not match them by ## producing a warning # cnn1 assert (o.cnn1_fmap_y_len - o.cnn1_filt_y_len) % o.cnn1_filt_y_step == 0 assert (o.cnn1_fmap_x_len - o.cnn1_filt_x_len) % o.cnn1_filt_x_step == 0 # subsample1 cnn1_out_fmap_y_len = 1 + (o.cnn1_fmap_y_len - o.cnn1_filt_y_len) / o.cnn1_filt_y_step cnn1_out_fmap_x_len = 1 + (o.cnn1_fmap_x_len - o.cnn1_filt_x_len) / o.cnn1_filt_x_step # fix filt_len and filt_step def fix_filt_step(inp_len, filt_len, filt_step): if (inp_len - filt_len) % filt_step == 0: return filt_step else: # filt_step <= filt_len for filt_step in range(filt_len, 0, -1): if (inp_len - filt_len) % filt_step == 0: return filt_step o.pool1_y_step = fix_filt_step(cnn1_out_fmap_y_len, o.pool1_y_len, o.pool1_y_step) if o.pool1_y_step == 1 and o.pool1_y_len != 1: warnings.warn("WARNING: Choose different pool1_y_len as subsampling is not happening") o.pool1_x_step = fix_filt_step(cnn1_out_fmap_x_len, o.pool1_x_len, o.pool1_x_step) if o.pool1_x_step == 1 and o.pool1_x_len != 1: warnings.warn("WARNING: Choose different pool1_x_len as subsampling is not happening") ### ### Print prototype of the network ### # Begin the prototype print("<NnetProto>") # Convolutional part of network """1st CNN layer""" cnn1_input_dim = feat_raw_dim * (o.delta_order + 1) * (o.splice * 2 + 1) cnn1_out_fmap_x_len = 1 + (o.cnn1_fmap_x_len - o.cnn1_filt_x_len) / o.cnn1_filt_x_step cnn1_out_fmap_y_len = 1 + (o.cnn1_fmap_y_len - o.cnn1_filt_y_len) / o.cnn1_filt_y_step cnn1_output_dim = o.cnn1_num_filters * cnn1_out_fmap_x_len * cnn1_out_fmap_y_len """1st Pooling layer""" pool1_input_dim = cnn1_output_dim pool1_fmap_x_len = cnn1_out_fmap_x_len pool1_out_fmap_x_len = 1 + (pool1_fmap_x_len - o.pool1_x_len) / o.pool1_x_step pool1_fmap_y_len = cnn1_out_fmap_y_len pool1_out_fmap_y_len = 1 + (pool1_fmap_y_len - o.pool1_y_len) / o.pool1_y_step pool1_output_dim = o.cnn1_num_filters * pool1_out_fmap_x_len * pool1_out_fmap_y_len """2nd CNN layer""" cnn2_input_dim = pool1_output_dim cnn2_fmap_x_len = pool1_out_fmap_x_len cnn2_out_fmap_x_len = 1 + (cnn2_fmap_x_len - o.cnn2_filt_x_len) / o.cnn2_filt_x_step cnn2_fmap_y_len = pool1_out_fmap_y_len cnn2_out_fmap_y_len = 1 + (cnn2_fmap_y_len - o.cnn2_filt_y_len) / o.cnn2_filt_y_step cnn2_output_dim = o.cnn2_num_filters * cnn2_out_fmap_x_len * cnn2_out_fmap_y_len convolution_proto = "" convolution_proto += ( "<Convolutional2DComponent> <InputDim> %d <OutputDim> %d <FmapXLen> %d <FmapYLen> %d <FiltXLen> %d <FiltYLen> %d <FiltXStep> %d <FiltYStep> %d <ConnectFmap> %d <BiasMean> %f <BiasRange> %f <ParamStddev> %f\n" % ( cnn1_input_dim, cnn1_output_dim, o.cnn1_fmap_x_len, o.cnn1_fmap_y_len, o.cnn1_filt_x_len, o.cnn1_filt_y_len, o.cnn1_filt_x_step, o.cnn1_filt_y_step, o.cnn1_connect_fmap, 0.0, 0.0, 0.01, ) ) convolution_proto += ( "<%sPooling2DComponent> <InputDim> %d <OutputDim> %d <FmapXLen> %d <FmapYLen> %d <PoolXLen> %d <PoolYLen> %d <PoolXStep> %d <PoolYStep> %d\n" % ( o.pool1_type, pool1_input_dim, pool1_output_dim, pool1_fmap_x_len, pool1_fmap_y_len, o.pool1_x_len, o.pool1_y_len, o.pool1_x_step, o.pool1_y_step, ) ) convolution_proto += "<Rescale> <InputDim> %d <OutputDim> %d <InitParam> %f\n" % ( pool1_output_dim, pool1_output_dim, 1.0, ) convolution_proto += "<AddShift> <InputDim> %d <OutputDim> %d <InitParam> %f\n" % ( pool1_output_dim, pool1_output_dim, 0.0, ) convolution_proto += "%s <InputDim> %d <OutputDim> %d\n" % (o.activation_type, pool1_output_dim, pool1_output_dim) convolution_proto += ( "<Convolutional2DComponent> <InputDim> %d <OutputDim> %d <FmapXLen> %d <FmapYLen> %d <FiltXLen> %d <FiltYLen> %d <FiltXStep> %d <FiltYStep> %d <ConnectFmap> %d <BiasMean> %f <BiasRange> %f <ParamStddev> %f\n" % ( cnn2_input_dim, cnn2_output_dim, cnn2_fmap_x_len, cnn2_fmap_y_len, o.cnn2_filt_x_len, o.cnn2_filt_y_len, o.cnn2_filt_x_step, o.cnn2_filt_y_step, o.cnn2_connect_fmap, -2.0, 4.0, 0.1, ) ) convolution_proto += "<Rescale> <InputDim> %d <OutputDim> %d <InitParam> %f\n" % (cnn2_output_dim, cnn2_output_dim, 1.0) convolution_proto += "<AddShift> <InputDim> %d <OutputDim> %d <InitParam> %f\n" % ( cnn2_output_dim, cnn2_output_dim, 0.0, ) convolution_proto += "%s <InputDim> %d <OutputDim> %d\n" % (o.activation_type, cnn2_output_dim, cnn2_output_dim) if o.pitch_dim > 0: # convolutional part f_conv = open("%s/nnet.proto.convolution" % o.dirct, "w") f_conv.write("<NnetProto>\n") f_conv.write(convolution_proto) f_conv.write("</NnetProto>\n") f_conv.close() # pitch part f_pitch = open("%s/nnet.proto.pitch" % o.dirct, "w") f_pitch.write("<NnetProto>\n") f_pitch.write( "<AffineTransform> <InputDim> %d <OutputDim> %d <BiasMean> %f <BiasRange> %f <ParamStddev> %f\n" % ((o.pitch_dim * (o.delta_order + 1) * (o.splice * 2 + 1)), o.num_pitch_neurons, -2.0, 4.0, 0.109375) ) f_pitch.write("%s <InputDim> %d <OutputDim> %d\n" % (o.activation_type, o.num_pitch_neurons, o.num_pitch_neurons)) f_pitch.write( "<AffineTransform> <InputDim> %d <OutputDim> %d <BiasMean> %f <BiasRange> %f <ParamStddev> %f\n" % (o.num_pitch_neurons, o.num_pitch_neurons, -2.0, 4.0, 0.109375) ) f_pitch.write("%s <InputDim> %d <OutputDim> %d\n" % (o.activation_type, o.num_pitch_neurons, o.num_pitch_neurons)) f_pitch.write("</NnetProto>\n") f_pitch.close() # paralell part vector = "" for i in range( 1, (feat_raw_dim + o.pitch_dim) * (o.delta_order + 1) * (o.splice * 2 + 1), feat_raw_dim + o.pitch_dim ): vector += "%d:1:%d " % (i, i + feat_raw_dim - 1) for i in range( feat_raw_dim + 1, (feat_raw_dim + o.pitch_dim) * (o.delta_order + 1) * (o.splice * 2 + 1), feat_raw_dim + o.pitch_dim, ): vector += "%d:1:%d " % (i, i + o.pitch_dim - 1) print( "<Copy> <InputDim> %d <OutputDim> %d <BuildVector> %s </BuildVector> " % ( (feat_raw_dim + o.pitch_dim) * (o.delta_order + 1) * (o.splice * 2 + 1), (feat_raw_dim + o.pitch_dim) * (o.delta_order + 1) * (o.splice * 2 + 1), vector, ) ) print( "<ParallelComponent> <InputDim> %d <OutputDim> %d <NestedNnetProto> %s %s </NestedNnetProto>" % ( (feat_raw_dim + o.pitch_dim) * (o.delta_order + 1) * (o.splice * 2 + 1), o.num_pitch_neurons + cnn2_output_dim, "%s/nnet.proto.convolution" % o.dirct, "%s/nnet.proto.pitch" % o.dirct, ) ) num_convolution_output = o.num_pitch_neurons + cnn2_output_dim else: # no pitch print(convolution_proto) # We are done! sys.exit(0)
12,637
30.994937
212
py
pytorch-kaldi-gan
pytorch-kaldi-gan-master/kaldi_decoding_scripts/utils/nnet/gen_hamm_mat.py
#!/usr/bin/env python # Copyright 2012 Brno University of Technology (author: Karel Vesely) # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED # WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, # MERCHANTABLITY OR NON-INFRINGEMENT. # See the Apache 2 License for the specific language governing permissions and # limitations under the License. # ./gen_hamm_mat.py # script generates diagonal matrix with hamming window values from __future__ import print_function from math import * import sys from optparse import OptionParser parser = OptionParser() parser.add_option("--fea-dim", dest="dim", help="feature dimension") parser.add_option("--splice", dest="splice", help="applied splice value") (options, args) = parser.parse_args() if options.dim == None: parser.print_help() sys.exit(1) dim = int(options.dim) splice = int(options.splice) # generate the diagonal matrix with hammings M_2PI = 6.283185307179586476925286766559005 dim_mat = (2 * splice + 1) * dim timeContext = 2 * splice + 1 print("[") for row in range(dim_mat): for col in range(dim_mat): if col != row: print("0", end=" ") else: i = int(row / dim) print(str(0.54 - 0.46 * cos((M_2PI * i) / (timeContext - 1))), end=" ") print() print("]")
1,639
27.77193
83
py
pytorch-kaldi-gan
pytorch-kaldi-gan-master/kaldi_decoding_scripts/utils/nnet/make_blstm_proto.py
#!/usr/bin/env python # Copyright 2015 Brno University of Technology (author: Karel Vesely) # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED # WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, # MERCHANTABLITY OR NON-INFRINGEMENT. # See the Apache 2 License for the specific language governing permissions and # limitations under the License. # Generated Nnet prototype, to be initialized by 'nnet-initialize'. from __future__ import print_function import sys ### ### Parse options ### from optparse import OptionParser usage = "%prog [options] <feat-dim> <num-leaves> >nnet-proto-file" parser = OptionParser(usage) # parser.add_option( "--num-cells", dest="num_cells", type="int", default=800, help="Number of LSTM cells [default: %default]" ) parser.add_option( "--num-recurrent", dest="num_recurrent", type="int", default=512, help="Number of LSTM recurrent units [default: %default]", ) parser.add_option( "--num-layers", dest="num_layers", type="int", default=2, help="Number of LSTM layers [default: %default]" ) parser.add_option( "--lstm-stddev-factor", dest="lstm_stddev_factor", type="float", default=0.01, help="Standard deviation of initialization [default: %default]", ) parser.add_option( "--param-stddev-factor", dest="param_stddev_factor", type="float", default=0.04, help="Standard deviation in output layer [default: %default]", ) parser.add_option( "--clip-gradient", dest="clip_gradient", type="float", default=5.0, help="Clipping constant applied to gradients [default: %default]", ) # (o, args) = parser.parse_args() if len(args) != 2: parser.print_help() sys.exit(1) (feat_dim, num_leaves) = list(map(int, args)) # Original prototype from Jiayu, # <NnetProto> # <Transmit> <InputDim> 40 <OutputDim> 40 # <LstmProjectedStreams> <InputDim> 40 <OutputDim> 512 <CellDim> 800 <ParamScale> 0.01 <NumStream> 4 # <AffineTransform> <InputDim> 512 <OutputDim> 8000 <BiasMean> 0.000000 <BiasRange> 0.000000 <ParamStddev> 0.04 # <Softmax> <InputDim> 8000 <OutputDim> 8000 # </NnetProto> print("<NnetProto>") # normally we won't use more than 2 layers of LSTM if o.num_layers == 1: print( "<BLstmProjectedStreams> <InputDim> %d <OutputDim> %d <CellDim> %s <ParamScale> %f <ClipGradient> %f" % (feat_dim, 2 * o.num_recurrent, o.num_cells, o.lstm_stddev_factor, o.clip_gradient) ) elif o.num_layers == 2: print( "<BLstmProjectedStreams> <InputDim> %d <OutputDim> %d <CellDim> %s <ParamScale> %f <ClipGradient> %f" % (feat_dim, 2 * o.num_recurrent, o.num_cells, o.lstm_stddev_factor, o.clip_gradient) ) print( "<BLstmProjectedStreams> <InputDim> %d <OutputDim> %d <CellDim> %s <ParamScale> %f <ClipGradient> %f" % (2 * o.num_recurrent, 2 * o.num_recurrent, o.num_cells, o.lstm_stddev_factor, o.clip_gradient) ) else: sys.stderr.write("make_lstm_proto.py ERROR: more than 2 layers of LSTM, not supported yet.\n") sys.exit(1) print( "<AffineTransform> <InputDim> %d <OutputDim> %d <BiasMean> 0.0 <BiasRange> 0.0 <ParamStddev> %f" % (2 * o.num_recurrent, num_leaves, o.param_stddev_factor) ) print("<Softmax> <InputDim> %d <OutputDim> %d" % (num_leaves, num_leaves)) print("</NnetProto>")
3,637
33.320755
111
py
pytorch-kaldi-gan
pytorch-kaldi-gan-master/kaldi_decoding_scripts/utils/nnet/make_lstm_proto.py
#!/usr/bin/env python # Copyright 2015 Brno University of Technology (author: Karel Vesely) # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED # WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, # MERCHANTABLITY OR NON-INFRINGEMENT. # See the Apache 2 License for the specific language governing permissions and # limitations under the License. # Generated Nnet prototype, to be initialized by 'nnet-initialize'. from __future__ import print_function import sys ### ### Parse options ### from optparse import OptionParser usage = "%prog [options] <feat-dim> <num-leaves> >nnet-proto-file" parser = OptionParser(usage) # parser.add_option( "--num-cells", dest="num_cells", type="int", default=800, help="Number of LSTM cells [default: %default]" ) parser.add_option( "--num-recurrent", dest="num_recurrent", type="int", default=512, help="Number of LSTM recurrent units [default: %default]", ) parser.add_option( "--num-layers", dest="num_layers", type="int", default=2, help="Number of LSTM layers [default: %default]" ) parser.add_option( "--lstm-stddev-factor", dest="lstm_stddev_factor", type="float", default=0.01, help="Standard deviation of initialization [default: %default]", ) parser.add_option( "--param-stddev-factor", dest="param_stddev_factor", type="float", default=0.04, help="Standard deviation in output layer [default: %default]", ) parser.add_option( "--clip-gradient", dest="clip_gradient", type="float", default=5.0, help="Clipping constant applied to gradients [default: %default]", ) # (o, args) = parser.parse_args() if len(args) != 2: parser.print_help() sys.exit(1) (feat_dim, num_leaves) = list(map(int, args)) # Original prototype from Jiayu, # <NnetProto> # <Transmit> <InputDim> 40 <OutputDim> 40 # <LstmProjectedStreams> <InputDim> 40 <OutputDim> 512 <CellDim> 800 <ParamScale> 0.01 <NumStream> 4 # <AffineTransform> <InputDim> 512 <OutputDim> 8000 <BiasMean> 0.000000 <BiasRange> 0.000000 <ParamStddev> 0.04 # <Softmax> <InputDim> 8000 <OutputDim> 8000 # </NnetProto> print("<NnetProto>") # normally we won't use more than 2 layers of LSTM if o.num_layers == 1: print( "<LstmProjectedStreams> <InputDim> %d <OutputDim> %d <CellDim> %s <ParamScale> %f <ClipGradient> %f" % (feat_dim, o.num_recurrent, o.num_cells, o.lstm_stddev_factor, o.clip_gradient) ) elif o.num_layers == 2: print( "<LstmProjectedStreams> <InputDim> %d <OutputDim> %d <CellDim> %s <ParamScale> %f <ClipGradient> %f" % (feat_dim, o.num_recurrent, o.num_cells, o.lstm_stddev_factor, o.clip_gradient) ) print( "<LstmProjectedStreams> <InputDim> %d <OutputDim> %d <CellDim> %s <ParamScale> %f <ClipGradient> %f" % (o.num_recurrent, o.num_recurrent, o.num_cells, o.lstm_stddev_factor, o.clip_gradient) ) else: sys.stderr.write("make_lstm_proto.py ERROR: more than 2 layers of LSTM, not supported yet.\n") sys.exit(1) print( "<AffineTransform> <InputDim> %d <OutputDim> %d <BiasMean> 0.0 <BiasRange> 0.0 <ParamStddev> %f" % (o.num_recurrent, num_leaves, o.param_stddev_factor) ) print("<Softmax> <InputDim> %d <OutputDim> %d" % (num_leaves, num_leaves)) print("</NnetProto>")
3,614
33.103774
111
py
pytorch-kaldi-gan
pytorch-kaldi-gan-master/kaldi_decoding_scripts/utils/nnet/gen_splice.py
#!/usr/bin/env python # Copyright 2012 Brno University of Technology (author: Karel Vesely) # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED # WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, # MERCHANTABLITY OR NON-INFRINGEMENT. # See the Apache 2 License for the specific language governing permissions and # limitations under the License. # ./gen_splice.py # generates <splice> Component from __future__ import print_function from math import * import sys from optparse import OptionParser parser = OptionParser() parser.add_option("--fea-dim", dest="dim_in", help="feature dimension") parser.add_option("--splice", dest="splice", help="number of frames to concatenate with the central frame") parser.add_option( "--splice-step", dest="splice_step", help="splicing step (frames dont need to be consecutive, --splice 3 --splice-step 2 will select offsets: -6 -4 -2 0 2 4 6)", default="1", ) (options, args) = parser.parse_args() if options.dim_in == None: parser.print_help() sys.exit(1) dim_in = int(options.dim_in) splice = int(options.splice) splice_step = int(options.splice_step) dim_out = (2 * splice + 1) * dim_in print("<splice>", dim_out, dim_in) print("[", end=" ") splice_vec = range(-splice * splice_step, splice * splice_step + 1, splice_step) for idx in range(len(splice_vec)): print(splice_vec[idx], end=" ") print("]")
1,730
29.368421
128
py
pytorch-kaldi-gan
pytorch-kaldi-gan-master/kaldi_decoding_scripts/utils/nnet/make_cnn_proto.py
#!/usr/bin/env python # Copyright 2014 Brno University of Technology (author: Katerina Zmolikova, Karel Vesely) # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED # WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, # MERCHANTABLITY OR NON-INFRINGEMENT. # See the Apache 2 License for the specific language governing permissions and # limitations under the License. # Generated Nnet prototype, to be initialized by 'nnet-initialize'. from __future__ import print_function import math, random, sys from optparse import OptionParser ### ### Parse options ### usage = "%prog [options] <feat-dim> <num-leaves> <num-hidden-layers> <num-hidden-neurons> >nnet-proto-file" parser = OptionParser(usage) parser.add_option( "--activation-type", dest="activation_type", help="Select type of activation function : (<Sigmoid>|<Tanh>) [default: %default]", default="<Sigmoid>", type="string", ) parser.add_option( "--num-filters1", dest="num_filters1", help="Number of filters in first convolutional layer [default: %default]", default=128, type="int", ) parser.add_option( "--num-filters2", dest="num_filters2", help="Number of filters in second convolutional layer [default: %default]", default=256, type="int", ) parser.add_option("--pool-size", dest="pool_size", help="Size of pooling [default: %default]", default=3, type="int") parser.add_option("--pool-step", dest="pool_step", help="Step of pooling [default: %default]", default=3, type="int") parser.add_option( "--pool-type", dest="pool_type", help="Type of pooling (Max || Average) [default: %default]", default="Max", type="string", ) parser.add_option( "--pitch-dim", dest="pitch_dim", help="Number of features representing pitch [default: %default]", default=0, type="int", ) parser.add_option( "--delta-order", dest="delta_order", help="Order of delta features [default: %default]", default=2, type="int" ) parser.add_option("--splice", dest="splice", help="Length of splice [default: %default]", default=5, type="int") parser.add_option( "--patch-step1", dest="patch_step1", help="Patch step of first convolutional layer [default: %default]", default=1, type="int", ) parser.add_option( "--patch-dim1", dest="patch_dim1", help="Dim of convolutional kernel in 1st layer (freq. axis) [default: %default]", default=8, type="int", ) parser.add_option( "--patch-dim2", dest="patch_dim2", help="Dim of convolutional kernel in 2nd layer (freq. axis) [default: %default]", default=4, type="int", ) parser.add_option( "--dir", dest="protodir", help="Directory, where network prototypes will be saved [default: %default]", default=".", type="string", ) parser.add_option( "--num-pitch-neurons", dest="num_pitch_neurons", help="Number of neurons in layers processing pitch features [default: %default]", default="200", type="int", ) (o, args) = parser.parse_args() if len(args) != 1: parser.print_help() sys.exit(1) feat_dim = int(args[0]) ### End parse options feat_raw_dim = ( feat_dim / (o.delta_order + 1) / (o.splice * 2 + 1) - o.pitch_dim ) # we need number of feats without deltas and splice and pitch # Check assert feat_dim > 0 assert o.pool_type == "Max" or o.pool_type == "Average" ### ### Print prototype of the network ### # Begin the prototype print("<NnetProto>") # Convolutional part of network num_patch1 = 1 + (feat_raw_dim - o.patch_dim1) / o.patch_step1 num_pool = 1 + (num_patch1 - o.pool_size) / o.pool_step patch_dim2 = o.patch_dim2 * o.num_filters1 patch_step2 = o.num_filters1 patch_stride2 = num_pool * o.num_filters1 # same as layer1 outputs num_patch2 = 1 + (num_pool * o.num_filters1 - patch_dim2) / patch_step2 convolution_proto = "" convolution_proto += ( "<ConvolutionalComponent> <InputDim> %d <OutputDim> %d <PatchDim> %d <PatchStep> %d <PatchStride> %d <BiasMean> %f <BiasRange> %f <ParamStddev> %f <MaxNorm> %f\n" % ( feat_raw_dim * (o.delta_order + 1) * (o.splice * 2 + 1), o.num_filters1 * num_patch1, o.patch_dim1, o.patch_step1, feat_raw_dim, -1.0, 2.0, 0.02, 30, ) ) # ~8x11x3 = 264 inputs convolution_proto += ( "<%sPoolingComponent> <InputDim> %d <OutputDim> %d <PoolSize> %d <PoolStep> %d <PoolStride> %d\n" % (o.pool_type, o.num_filters1 * num_patch1, o.num_filters1 * num_pool, o.pool_size, o.pool_step, o.num_filters1) ) convolution_proto += "<Rescale> <InputDim> %d <OutputDim> %d <InitParam> %f\n" % ( o.num_filters1 * num_pool, o.num_filters1 * num_pool, 1, ) convolution_proto += "<AddShift> <InputDim> %d <OutputDim> %d <InitParam> %f\n" % ( o.num_filters1 * num_pool, o.num_filters1 * num_pool, 0, ) convolution_proto += "%s <InputDim> %d <OutputDim> %d\n" % ( o.activation_type, o.num_filters1 * num_pool, o.num_filters1 * num_pool, ) convolution_proto += ( "<ConvolutionalComponent> <InputDim> %d <OutputDim> %d <PatchDim> %d <PatchStep> %d <PatchStride> %d <BiasMean> %f <BiasRange> %f <ParamStddev> %f <MaxNorm> %f\n" % ( o.num_filters1 * num_pool, o.num_filters2 * num_patch2, patch_dim2, patch_step2, patch_stride2, -2.0, 4.0, 0.1, 50, ) ) # ~4x128 = 512 inputs convolution_proto += "<Rescale> <InputDim> %d <OutputDim> %d <InitParam> %f\n" % ( o.num_filters2 * num_patch2, o.num_filters2 * num_patch2, 1, ) convolution_proto += "<AddShift> <InputDim> %d <OutputDim> %d <InitParam> %f\n" % ( o.num_filters2 * num_patch2, o.num_filters2 * num_patch2, 0, ) convolution_proto += "%s <InputDim> %d <OutputDim> %d\n" % ( o.activation_type, o.num_filters2 * num_patch2, o.num_filters2 * num_patch2, ) if o.pitch_dim > 0: # convolutional part f_conv = open("%s/nnet.proto.convolution" % o.protodir, "w") f_conv.write("<NnetProto>\n") f_conv.write(convolution_proto) f_conv.write("</NnetProto>\n") f_conv.close() # pitch part f_pitch = open("%s/nnet.proto.pitch" % o.protodir, "w") f_pitch.write("<NnetProto>\n") f_pitch.write( "<AffineTransform> <InputDim> %d <OutputDim> %d <BiasMean> %f <BiasRange> %f <ParamStddev> %f\n" % ((o.pitch_dim * (o.delta_order + 1) * (o.splice * 2 + 1)), o.num_pitch_neurons, -2, 4, 0.02) ) f_pitch.write("%s <InputDim> %d <OutputDim> %d\n" % (o.activation_type, o.num_pitch_neurons, o.num_pitch_neurons)) f_pitch.write( "<AffineTransform> <InputDim> %d <OutputDim> %d <BiasMean> %f <BiasRange> %f <ParamStddev> %f\n" % (o.num_pitch_neurons, o.num_pitch_neurons, -2, 4, 0.1) ) f_pitch.write("%s <InputDim> %d <OutputDim> %d\n" % (o.activation_type, o.num_pitch_neurons, o.num_pitch_neurons)) f_pitch.write("</NnetProto>\n") f_pitch.close() # parallel part vector = "" for i in range( 1, (feat_raw_dim + o.pitch_dim) * (o.delta_order + 1) * (o.splice * 2 + 1), feat_raw_dim + o.pitch_dim ): vector += "%d:1:%d " % (i, i + feat_raw_dim - 1) for i in range( feat_raw_dim + 1, (feat_raw_dim + o.pitch_dim) * (o.delta_order + 1) * (o.splice * 2 + 1), feat_raw_dim + o.pitch_dim, ): vector += "%d:1:%d " % (i, i + o.pitch_dim - 1) print( "<Copy> <InputDim> %d <OutputDim> %d <BuildVector> %s </BuildVector>" % ( (feat_raw_dim + o.pitch_dim) * (o.delta_order + 1) * (o.splice * 2 + 1), (feat_raw_dim + o.pitch_dim) * (o.delta_order + 1) * (o.splice * 2 + 1), vector, ) ) print( "<ParallelComponent> <InputDim> %d <OutputDim> %d <NestedNnetProto> %s %s </NestedNnetProto>" % ( (feat_raw_dim + o.pitch_dim) * (o.delta_order + 1) * (o.splice * 2 + 1), o.num_pitch_neurons + o.num_filters2 * num_patch2, "%s/nnet.proto.convolution" % o.protodir, "%s/nnet.proto.pitch" % o.protodir, ) ) else: # no pitch print(convolution_proto) # We are done! sys.exit(0)
8,528
31.553435
166
py
LIGGGHTS-WITH-BONDS
LIGGGHTS-WITH-BONDS-master/src/Make.py
#!/usr/bin/env python # if necessary, edit preceding line to point to your Python # or launch as "python Make.py ..." # Purpose: manage LAMMPS packages, external libraries, and builds # create a version of LAMMPS specific to an input script(s) # Syntax: Make.py switch args ... # Help: type Make.py or Make.py -h # ----------------------------------------------------------------------- # LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator # http://lammps.sandia.gov, Sandia National Laboratories # Steve Plimpton, sjplimp@sandia.gov # # Copyright (2003) Sandia Corporation. Under the terms of Contract # DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains # certain rights in this software. This software is distributed under # the GNU General Public License. # # See the README file in the top-level LAMMPS directory. # ----------------------------------------------------------------------- # hi-level tasks that can be performed: # install/uninstall packages and build the associated external libs # use -p and -u and -e # install packages needed for input script(s) # use -i and -p # create new dir with only the source code needed for input script(s) # use -i and -n # build LAMMPS, either in src or new dir # use -b # data structures: # packstd list = ["ASPHERE", "PASCAL", ...] # packuser list = ["USER-SPH", "USER-EWALDN", ...], currently not existing # cfiles,hfiles dicts of LAMMPS *.cpp,*.h files = # {"fix_nve.cpp": "", "angle_diplole.cpp": "USER-MISC", ...} # cdep,hdep dicts of files with list of LAMMPS *.h files they include = # {"fix_nve.cpp": ['fix_nve.h', 'atom.h', 'force.h', ...'], ...} # creq,hreq lists of src files needed to build LAMMPS for input scripts = # ["main.cpp", "atom.cpp", ...] # ISSUES: # see KLUDGE comments # add more general input script parsing, see NOTE comments # including another file # variable substitution could be used to create new command (hard) # single/double quotes could affect args and hide nested commands # hybrid styles can have required sub-styles # if-then-else and run every could nest other commands as args # special case: linalg sometimes needed with ATC external lib # could scan atc/Makefile.lammps for it # can long makes print incrementally to screen as they progress? # add a verbose output option? # ----------------------------------------------------------------------- # ----------------------------------------------------------------------- import sys,glob,re,os,commands # ----------------------------------------------------------------------- # variables # support files in lammps/src neeeded for a build support = ["Makefile","Make.sh","Makefile.package.empty", "Makefile.package.settings.empty"] # packages that have external libs with their external lib dir extlibs = {"USER-ATC": "atc", "USER-AWPMD": "awpmd", "USER-COLVARS": "colvars", "USER-CUDA": "cuda","GPU": "gpu","MEAM": "meam", "POEMS": "poems", "REAX": "reax"} # help messages syntax_message = """ Make.py switch args ... Switches: -i file1 file2 ... -p package1 package2 ... -u package1 package2 ... -e package1 arg1 arg2 package2 ... -o dir -b machine -s suffix1 suffix2 ... -l dir -j N -h switch1 switch2 ... Help: Make.py or Make.py -h """ ihelp = """ -i file1 file2 ... scan input scripts, make list of needed files and packages """ phelp = """ -p package1 package2 ... specify zero or more packages can use "all" or "standard" or "user" install packages required by -i input scripts also install listed packages """ uhelp = """ -u package1 package2 ... specify zero or more packages can specify "all" or "standard" or "user", or package w/out user prefix uninstall packages not required by -i input scripts also uninstall listed packages """ ehelp = """ -e package1 arg1 arg2 package2 ... build external libs for zero or more packages can specify package w/out user prefix each package can have 1 or 2 optional args arg1 = suffix for lib Makefile arg2 = suffix for lib Makefile.lammps example packages with external libs: "gpu", "meam", "user-cuda" build external libs for packages required by -i input scripts also build external libs for installed packages if none listed also build external libs for listed packages if arg1 specified, use Makefile.arg1 to build lib, else use Makefile if arg2 specified, copy Makefile.lammps.arg2 to Makefile.lammps, else copy Makefile.lammps.arg1 to Makefile.lammps, else do nothing """ ohelp = """ -o newdir create newdir with exactly the needed src files for -i input scripts newdir will be at same level as src so LAMMPS build will work requires use of -i, cannot use with -p or -u newdir will include STUBS and MAKE, but no package dirs """ bhelp = """ -b machine build LAMMPS in src or newdir using Makefile.machine assumes external package libs are already built if no -o, build in src if -o, build in newdir, including STUBS build if needed """ shelp = """ -s suffix1 suffix2 ... specify optimization suffixes to add to style names in -i input scripts requires use of -i same suffixes as LAMMPS -s command-line switch allows example suffixes = "opt", "gpu", "cuda", "omp" """ lhelp = """ -l dir specify LAMMPS home dir required if not running Make.py from within lammps/src """ jhelp = """ -j N perform LAMMPS and external lib builds in parallel adds "-j N" switch to "make" commands N = 0 performs serial make default N = 16 """ hhelp = """ Make.py lists all switches Make.py -h -i -b ... gives help on each switch Make.py -h gives this message """ # ----------------------------------------------------------------------- # functions # print syntax message def syntax(): print syntax_message sys.exit() # help messages def helptxt(switches): if not switches: switches = ["-h"] for sw in switches: if sw == "-i": print ihelp elif sw == "-p": print phelp elif sw == "-u": print uhelp elif sw == "-e": print ehelp elif sw == "-o": print ohelp elif sw == "-b": print bhelp elif sw == "-s": print shelp elif sw == "-l": print lhelp elif sw == "-j": print jhelp elif sw == "-h": print hhelp else: error("Invalid help switch") # print error message def error(str): print "ERROR:",str sys.exit() # convert *.cpp file to *.h file def c2h(file): return file[:-4] + ".h" # convert *.h file to *.cpp file def h2c(file): return file[:-2] + ".cpp" # append file to list # but only if file is not already in list # but only if file is in cfiles or hfiles def addfile(file,list): if file in list: return if file not in cfiles and file not in hfiles: return list.append(file) # grab list of LAMMPS package dirs from src/Makefile def lammps_packages(): txt = open(srcdir + "/Makefile",'r').read() pattern = "PACKAGE = (.*?)\n\n" match = re.search(pattern,txt,re.DOTALL) packstd = match.group(1).replace("\\","").upper().split() pattern = "PACKUSER = (.*?)\n\n" match = re.search(pattern,txt,re.DOTALL) packuser = match.group(1).replace("\\","").upper().split() return packstd,packuser # uninstall package in LAMMPS src dir # package can be upper-case or lower-case def uninstall_package(package): package = package.lower() cmd = "cd %s; make no-%s" % (srcdir,package) commands.getoutput(cmd) print " uninstalled",package # install package in LAMMPS src dir # package can be upper-case or lower-case def install_package(package): package = package.lower() cmd = "cd %s; make yes-%s" % (srcdir,package) commands.getoutput(cmd) print " installed",package # re-parse list of packages input via -e switch # one or two flags may be appended to a package # convert into dict with value = list of flags def reparse_packages(packages): dict = {} last = "" for package in packages: upper = package.upper() flag = 0 if upper in packstd: flag = 1 elif upper in packuser: flag = 1 elif "USER-" + upper in packuser: flag = 1 if flag: dict[package] = [] last = package else: if not last: error("Invalid package in -e list") buildflags = dict[last] if len(buildflags) == 2: error("Too many machine flags appended to package %s" % last) buildflags.append(package) return dict # detect which packages are installed via "make package-status" command # return as list def detect_installed_packages(): cmd = "cd %s; make package-status" % srcdir output = commands.getoutput(cmd) pattern = "Installed\s*(.*): package (.*)" status = re.findall(pattern,output) installed = [] for entry in status: if entry[0] == "YES": installed.append(entry[1]) return installed # create dict of all LAMMPS *.cpp and *.h files with no duplicates # key = file # value = package dir if file in a package dir # value = empty if file is only in lammps/src # discard style_*.h files def lammps_files(): files = [] for dir in packstd: files += glob.glob(dir + "/*.cpp") files += glob.glob(dir + "/*.h") for dir in packuser: files += glob.glob(dir + "/*.cpp") files += glob.glob(dir + "/*.h") files += glob.glob("*.cpp") files += glob.glob("*.h") cfiles = {} hfiles = {} for file in files: dir = os.path.dirname(file) file = os.path.basename(file) if file.find("style_") == 0: continue if file[-2:] == ".h": if file not in hfiles: hfiles[file] = dir else: if file not in cfiles: cfiles[file] = dir return cfiles,hfiles # parse each cfile,hfile to find list of LAMMPS *.h files it includes # create cdep,hdep = dict with key = filename, value = list of *.h files # KLUDGE for accelerator_cuda.h to ignore the *.h files it includes # when "cuda" is not explicitly listed as a suffix, # this is b/c it has an ifdef that includes several *cuda*.h files def dependencies(): pattern = re.compile('^#include "(.+?)"',re.MULTILINE) cdep = {} for file in cfiles: if cfiles[file]: file = cfiles[file] + "/" + file txt = open(file,'r').read() possible = re.findall(pattern,txt) depends = [] for dfile in possible: if dfile in hfiles: depends.append(dfile) cdep[os.path.basename(file)] = depends hdep = {} for file in hfiles: if hfiles[file]: file = hfiles[file] + "/" + file txt = open(file,'r').read() possible = re.findall(pattern,txt) depends = [] for dfile in possible: if dfile in hfiles: depends.append(dfile) if file == "accelerator_cuda.h" and "cuda" not in suffixes: depends = [] hdep[os.path.basename(file)] = depends return cdep,hdep # add style files referenced in input script to lookup list # parse input script lines to look for them # add suffix for certain styles def need_from_input_script(file,lookup): lines = open(file,'r').readlines() # skip comment and blank lines # NOTE: need to treat concatenated lines # NOTE: need to handle quoted args when split into words # NOTE: need to treat if and run every and print, which nest commands cmds = {} for line in lines: if line.find("#") >= 0: line = line[:line.find("#")] line = line.strip() if len(line) == 0: continue words = line.split() cmds[words[0]] = words[1:] # for commands with styles, generate file associated with style name # suffixes induce multiple file variants # final else handles command styles if "CommandStyle" found in *.h file for cmd in cmds: args = cmds[cmd] files = [] if cmd == "atom_style": files.append("atom_vec_" + args[0]) for suffix in suffixes: files.append("atom_vec_" + args[0] + "/" + suffix) elif cmd == "pair_style": files.append("pair_" + args[0]) for suffix in suffixes: files.append("pair_" + args[0] + "/" + suffix) elif cmd == "bond_style": files.append("bond_" + args[0]) for suffix in suffixes: files.append("bond_" + args[0] + "/" + suffix) elif cmd == "angle_style": files.append("angle_" + args[0]) for suffix in suffixes: files.append("angle_" + args[0] + "/" + suffix) elif cmd == "dihedral_style": files.append("dihedral_" + args[0]) for suffix in suffixes: files.append("dihedral_" + args[0] + "/" + suffix) elif cmd == "improper_style": files.append("improper_" + args[0]) for suffix in suffixes: files.append("improper_" + args[0] + "/" + suffix) elif cmd == "kspace_style": files.append(args[0]) for suffix in suffixes: files.append(args[0] + "/" + suffix) elif cmd == "run_style": files.append(args[0]) for suffix in suffixes: files.append(args[0] + "/" + suffix) elif cmd == "min_style": files.append("min_" + args[0]) elif cmd == "compute": files.append("compute_" + args[2]) for suffix in suffixes: files.append("compute_" + args[2] + "/" + suffix) elif cmd == "dump": files.append("dump_" + args[2]) elif cmd == "fix": files.append("fix_" + args[2]) for suffix in suffixes: files.append("fix_" + args[2] + "/" + suffix) elif cmd == "region": files.append("region_" + args[1]) else: tmpfile = cmd + ".cpp" if tmpfile not in cfiles: continue if cfiles[tmpfile]: tmpfile = cfiles[tmpfile] + "/" + tmpfile txt = open(c2h(tmpfile)).read() if not "CommandStyle" in txt: continue files.append(cmd) for file in files: file = file.replace("/","_") + ".cpp" addfile(file,lookup) # add additional CPP files required to build LAMMPS to lookup list # always add main.cpp # always add atom_vec_atomic, # since Atom class creates it directly # always add compute_temp, compute_pe, compute_pressure, # since Output class creates these computes directly # always add verlet and min_cg, # since Update class creates them directly # always add src/neigh_*.cpp since are part of Neighbor class, # but only neighbor.cpp is inferred by neighbor.h # KLUDGE: # likewise add USER-OMP/neigh_*.cpp if any USER-OMP files are in lookup # likewise add USER-CUDA/neigh_*.cpp if any USER-CUDA files are in lookup def need_additional(lookup): addfile("main.cpp",lookup) addfile("atom_vec_atomic.cpp",lookup) addfile("compute_temp.cpp",lookup) addfile("compute_pe.cpp",lookup) addfile("compute_pressure.cpp",lookup) addfile("verlet.cpp",lookup) addfile("min_cg.cpp",lookup) user_cuda = user_omp = 0 for file in lookup: if file[-2:] == ".h": if hfiles[file] == "USER-CUDA": user_cuda = 1 if hfiles[file] == "USER-OMP": user_omp = 1 else: if cfiles[file] == "USER-CUDA": user_cuda = 1 if cfiles[file] == "USER-OMP": user_omp = 1 for file in cfiles: if file.find("neigh_") == 0: if cfiles[file] == "": addfile(file,lookup) if cfiles[file] == "USER-CUDA" and user_cuda: addfile(file,lookup) if cfiles[file] == "USER-OMP" and user_omp: addfile(file,lookup) # creq,hreq = list of all CPP and H files needed to build LAMMPS # inferred from lookup list and each file's dependencies in cdep,hdep # when an H file is added, also add corresponding CPP file to lookup # addfile insures no duplicates in creq,hreq def resolve_dependencies(lookup): creq = [] hreq = [] i = 0 while i < len(lookup): file = lookup[i] if file[-2:] == ".h": hreq.append(file) dfiles = hdep[file] addfile(h2c(file),lookup) else: creq.append(file) dfiles = cdep[file] for dfile in dfiles: addfile(dfile,lookup) i += 1 return creq,hreq # ----------------------------------------------------------------------- # main program # defaults infiles = [] packflag = 0 packages = [] unpackflag = 0 unpackages = [] extflag = 0 extpackages = [] newdir = "" build = "" suffixes = [] lammpsdir = "" jmake = 16 helpflag = 0 help = [] # parse command-line args args = sys.argv narg = len(args) if narg == 1: syntax() iarg = 1 while iarg < narg: if args[iarg] == "-i": if iarg+2 > narg: syntax() iarg += 1 while iarg < narg and args[iarg][0] != '-': infiles.append(args[iarg]) iarg += 1 elif args[iarg] == "-p": packflag = 1 iarg += 1 while iarg < narg and args[iarg][0] != '-': packages.append(args[iarg]) iarg += 1 elif args[iarg] == "-u": unpackflag = 1 iarg += 1 while iarg < narg and args[iarg][0] != '-': unpackages.append(args[iarg]) iarg += 1 elif args[iarg] == "-e": extflag = 1 iarg += 1 while iarg < narg and args[iarg][0] != '-': extpackages.append(args[iarg]) iarg += 1 elif args[iarg] == "-o": if iarg+2 > narg: syntax() newdir = args[iarg+1] iarg += 2 elif args[iarg] == "-b": if iarg+2 > narg: syntax() build = args[iarg+1] iarg += 2 elif args[iarg] == "-s": if iarg+2 > narg: syntax() iarg += 1 while iarg < narg and args[iarg][0] != '-': suffixes.append(args[iarg]) iarg += 1 elif args[iarg] == "-l": if iarg+2 > narg: syntax() lammpsdir = args[iarg+1] iarg += 2 elif args[iarg] == "-j": if iarg+2 > narg: syntax() jmake = int(args[iarg+1]) iarg += 1 elif args[iarg] == "-h": helpflag = 1 iarg += 1 while iarg < narg and args[iarg][0] == '-': help.append(args[iarg]) iarg += 1 else: syntax() # help if helpflag: helptxt(help) # error check if newdir: if not infiles: error("Cannot use -o without -i") if packflag: error("Cannot use -o with -p") if unpackages: error("Cannot use -o with -u") if suffixes: if not infiles: error("Cannot use -s without -i") # setup strings # srcdir = LAMMPS src dir # check that srcdir is valid via 2 "empty" files and version.h # libdir = LAMMPS lib dir # newdir = new src dir # makestr = -j N for parallel make if lammpsdir: srcdir = lammpsdir + "/src" else: srcdir = "." if not os.path.isfile(srcdir + "/Makefile.package.empty") \ or not os.path.isfile(srcdir + "/Makefile.package.settings.empty") \ or not os.path.isfile(srcdir + "/version.h"): error("Not running in LAMMPS src dir, use -l switch") if srcdir == ".": libdir = "../lib" else: libdir = srcdir[:-3] + "lib" if newdir: if srcdir == ".": newdir = "../" + newdir else: newdir = srcdir[:-3] + newdir if jmake == 0: makestr = "" else: makestr = "-j %d" % jmake # packstd,packuser = list of package dirs in lammps/src packstd,packuser = lammps_packages() # -i switch # cfiles,hfiles = all LAMMPS src files # cdep,hdep = src files with list of *.h files each depends on # lookup = needed *.cpp files = default + input script styles # creq,hreq = files needed to build LAMMPS = lookup + dependencies # packneed = needed packages if infiles: print "Scanning input scripts ..." cfiles,hfiles = lammps_files() cdep,hdep = dependencies() lookup = [] for file in infiles: need_from_input_script(file,lookup) need_additional(lookup) creq,hreq = resolve_dependencies(lookup) packneed = [] for file in creq: if cfiles[file] and cfiles[file] not in packneed: packneed.append(cfiles[file]) for file in hreq: if hfiles[file] and hfiles[file] not in packneed: packneed.append(hfiles[file]) print " scripts require %d LAMMPS *.cpp files" % len(creq) print " scripts require %d LAMMPS *.h files" % len(hreq) print " scripts require %d packages:" % len(packneed), print packneed # -u switch # if -i, add unneeded packages to list # add explicitly named packages to list # uninstall packages in list only if installed if unpackflag: print "Uninstalling packages ..." list = [] if infiles: for package in packstd: if package not in packneed: list.append(package) for package in packuser: if package not in packneed: list.append(package) for entry in unpackages: entry = entry.upper() if entry == "ALL": for package in packstd: if package not in list: list.append(package) for package in packuser: if package not in list: list.append(package) elif entry == "STANDARD": for package in packstd: if package not in list: list.append(package) elif entry == "USER": for package in packuser: if package not in list: list.append(package) elif entry in packstd: if entry not in list: list.append(entry) elif entry in packuser: if entry not in list: list.append(entry) elif "USER-" + entry in packuser: if "USER-" + entry not in list: list.append("USER-" + entry) else: error("Invalid package %s to uninstall" % entry.lower()) installed_packages = detect_installed_packages() for package in list: if package in installed_packages: uninstall_package(package) # -p switch # if -i, add needed packages to list # add explicitly named packages to list # install packages in list only if uninstalled if packflag: print "Installing packages ..." list = [] if infiles: for package in packneed: list.append(package) for entry in packages: entry = entry.upper() if entry == "ALL": for package in packstd: if package not in list: list.append(package) for package in packuser: if package not in list: list.append(package) elif entry == "STANDARD": for package in packstd: if package not in list: list.append(package) elif entry == "USER": for package in packuser: if package not in list: list.append(package) elif entry in packstd: if entry not in list: list.append(entry) elif entry in packuser: if entry not in list: list.append(entry) elif "USER-" + entry in packuser: if "USER-" + entry not in list: list.append("USER-" + entry) else: error("Invalid package %s to install" % entry.lower()) installed_packages = detect_installed_packages() for package in list: if package not in installed_packages: install_package(package) # -e switch # add explicitly named libs to list first, so can include arg1/arg2 # if -i, add needed libs to list # if none named, add libs for installed packages to list # use Makefile.arg1 and Makefile.lammps.arg1/arg2 if specified # force rebuild by doing clean first if extflag: print "Building external libraries ..." list = {} packages_with_flags = reparse_packages(extpackages) for package in packages_with_flags: upper = package.upper() if upper in extlibs and upper not in list: list[upper] = packages_with_flags[package] upper = "USER-" + upper if upper in extlibs and upper not in list: list[upper] = packages_with_flags[package] if infiles: for package in packneed: if package in extlibs and package not in list: list[package] = [] if not extpackages: installed_packages = detect_installed_packages() for package in installed_packages: if package in extlibs and package not in list: list[package] = [] for package in list: lib = extlibs[package] print " lib/%s/lib%s.a for package %s ..." % (lib,lib,package) args = list[package] # makefile = Makefile by default unless arg1 specified makefile = "Makefile" if args: makefile = "Makefile.%s" % args[0] if not os.path.isfile("%s/%s/%s" % (libdir,lib,makefile)): error("%s for external lib %s does not exist" % (makefile,lib)) # no makefile_lammps by default unless arg2 or arg1 specified makefile_lammps = "" if args and len(args) == 2: makefile_lammps = "Makefile.lammps.%s" % args[1] if not os.path.isfile("%s/%s/%s" % (libdir,lib,makefile_lammps)): error("%s for external lib %s does not exist" % (makefile,lib)) elif args: makefile_lammps = "Makefile.lammps.%s" % args[0] # target lib file # KLUDGE for cuda, since it is liblammpscuda.a instead of libcuda.a libfile = "%s/%s/lib%s.a" % (libdir,lib,lib) if lib == "cuda": libfile = "%s/%s/liblammpscuda.a" % (libdir,lib) # remove lib file if os.path.exists(libfile): os.remove(libfile) # make clean print " cleaning ..." cmd = "cd %s/%s; make -f %s clean" % (libdir,lib,makefile) output = commands.getoutput(cmd) # build the external lib and check if successful print " building ..." cmd = "cd %s/%s; make %s -f %s" % (libdir,lib,makestr,makefile) output = commands.getoutput(cmd) if os.path.exists(libfile): print " successfully built lib/%s/lib%s.a" % (lib,lib) else: print output error("Build of lib/%s/lib%s.a was unsuccessful" % (lib,lib)) # if it exists, copy makefile_lammps to Makefile.lammps if makefile_lammps: if os.path.isfile("%s/%s/%s" % (libdir,lib,makefile_lammps)): cmd = "cd %s/%s; cp %s Makefile.lammps" % (libdir,lib,makefile_lammps) commands.getoutput(cmd) # -n switch # create newdir with exactly the needed src files for scripts # newdir has support files and STUBS and MAKE, but no package dirs # insure Makefile.package and Makefile.package.settings are correct by # installing all needed packages in newdir, then delete package dirs if newdir: print "Creating %s ..." % newdir if os.path.exists(newdir): error("Directory %s already exists" % newdir) os.mkdir(newdir) os.mkdir(newdir + "/MAKE") os.mkdir(newdir + "/STUBS") for file in support: commands.getoutput("cp %s/%s %s" % (srcdir,file,newdir)) files = glob.glob("%s/MAKE/Makefile.*" % srcdir) fstr = " ".join(files) commands.getoutput("cp %s %s/MAKE" % (fstr,newdir)) commands.getoutput("cp %s/STUBS/Makefile %s/STUBS" % (srcdir,newdir)) commands.getoutput("cp %s/STUBS/mpi.c %s/STUBS" % (srcdir,newdir)) commands.getoutput("cp %s/STUBS/mpi.h %s/STUBS" % (srcdir,newdir)) for package in packneed: os.mkdir("%s/%s" % (newdir,package)) commands.getoutput("cp %s/%s/* %s/%s" % (srcdir,package,newdir,package)) commands.getoutput("cd %s; make yes-%s" % (newdir,package.lower())) commands.getoutput("rm -r %s/%s" % (newdir,package)) commands.getoutput("rm -r %s/*.cpp" % (newdir)) commands.getoutput("rm -r %s/*.h" % (newdir)) for file in creq: if cfiles[file]: file = cfiles[file] + "/" + file commands.getoutput("cp %s/%s %s" % (srcdir,file,newdir)) for file in hreq: if hfiles[file]: file = hfiles[file] + "/" + file commands.getoutput("cp %s/%s %s" % (srcdir,file,newdir)) # -b switch # build LAMMPS in src or newdir # assumes external package libs are already built # build STUBS lib if needed and not already built if build: print "Building LAMMPS for %s ..." % build if newdir: builddir = newdir else: builddir = srcdir makefile = "%s/MAKE/Makefile.%s" % (builddir,build) if not os.path.exists(makefile): error("%s does not exist" % makefile) txt = open(makefile,"r").read() if "../STUBS" in txt: if not os.path.exists("%s/STUBS/libmpi.a" % builddir): cmd = "cd %s/STUBS; make" % builddir output = commands.getoutput(cmd) if os.path.exists("%s/STUBS/libmpi.a" % builddir): print "Successfully built STUBS/libmpi.a" else: print output error("Build of STUBS/libmpi.a was unsuccessful") if os.path.exists("%s/lmp_%s" % (builddir,build)): os.remove("%s/lmp_%s" % (builddir,build)) cmd = "cd %s; make %s %s" % (builddir,makestr,build) output = commands.getoutput(cmd) if os.path.exists("%s/lmp_%s" % (builddir,build)): print "Successfully built %s/lmp_%s" % (builddir,build) else: print output error("Build of %s/lmp_%s was unsuccessful" % (builddir,build))
27,648
30.383655
80
py
LIGGGHTS-WITH-BONDS
LIGGGHTS-WITH-BONDS-master/python/install.py
#!/usr/bin/env python # copy LAMMPS src/liblammps.so and lammps.py to system dirs instructions = """ Syntax: python install.py [-h] [libdir] [pydir] libdir = target dir for src/liblammps.so, default = /usr/local/lib pydir = target dir for lammps.py, default = Python site-packages dir """ import sys,os,commands if (len(sys.argv) > 1 and sys.argv[1] == "-h") or len(sys.argv) > 3: print instructions sys.exit() if len(sys.argv) >= 2: libdir = sys.argv[1] else: libdir = "/usr/local/lib" if len(sys.argv) == 3: pydir = sys.argv[2] else: pydir = "" # copy C lib to libdir if it exists # warn if not in LD_LIBRARY_PATH or LD_LIBRARY_PATH is undefined if not os.path.isdir(libdir): print "ERROR: libdir %s does not exist" % libdir sys.exit() if "LD_LIBRARY_PATH" not in os.environ: print "WARNING: LD_LIBRARY_PATH undefined, cannot check libdir %s" % libdir else: libpaths = os.environ['LD_LIBRARY_PATH'].split(':') if libdir not in libpaths: print "WARNING: libdir %s not in LD_LIBRARY_PATH" % libdir str = "cp ../src/liblammps.so %s" % libdir print str outstr = commands.getoutput(str) if len(outstr.strip()): print outstr # copy lammps.py to pydir if it exists # if pydir not specified, install in site-packages via distutils setup() if pydir: if not os.path.isdir(pydir): print "ERROR: pydir %s does not exist" % pydir sys.exit() str = "cp ../python/lammps.py %s" % pydir print str outstr = commands.getoutput(str) if len(outstr.strip()): print outstr sys.exit() print "installing lammps.py in Python site-packages dir" os.chdir('../python') # in case invoked via make in src dir from distutils.core import setup sys.argv = ["setup.py","install"] # as if had run "python setup.py install" setup(name = "lammps", version = "15Aug12", author = "Steve Plimpton", author_email = "sjplimp@sandia.gov", url = "http://lammps.sandia.gov", description = "LAMMPS molecular dynamics library", py_modules = ["lammps"])
2,034
28.926471
78
py
LIGGGHTS-WITH-BONDS
LIGGGHTS-WITH-BONDS-master/python/lammps.py
# ---------------------------------------------------------------------- # LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator # http://lammps.sandia.gov, Sandia National Laboratories # Steve Plimpton, sjplimp@sandia.gov # # Copyright (2003) Sandia Corporation. Under the terms of Contract # DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains # certain rights in this software. This software is distributed under # the GNU General Public License. # # See the README file in the top-level LAMMPS directory. # ------------------------------------------------------------------------- # Python wrapper on LAMMPS library via ctypes import sys,traceback,types from ctypes import * class lammps: def __init__(self,name="",cmdargs=None): # load liblammps.so by default # if name = "g++", load liblammps_g++.so try: if not name: self.lib = CDLL("liblammps.so",RTLD_GLOBAL) else: self.lib = CDLL("liblammps_%s.so" % name,RTLD_GLOBAL) except: type,value,tb = sys.exc_info() traceback.print_exception(type,value,tb) raise OSError,"Could not load LAMMPS dynamic library" # create an instance of LAMMPS # don't know how to pass an MPI communicator from PyPar # no_mpi call lets LAMMPS use MPI_COMM_WORLD # cargs = array of C strings from args if cmdargs: cmdargs.insert(0,"lammps.py") narg = len(cmdargs) cargs = (c_char_p*narg)(*cmdargs) self.lmp = c_void_p() self.lib.lammps_open_no_mpi(narg,cargs,byref(self.lmp)) else: self.lmp = c_void_p() self.lib.lammps_open_no_mpi(0,None,byref(self.lmp)) # could use just this if LAMMPS lib interface supported it # self.lmp = self.lib.lammps_open_no_mpi(0,None) def __del__(self): if self.lmp: self.lib.lammps_close(self.lmp) def close(self): self.lib.lammps_close(self.lmp) self.lmp = None def file(self,file): self.lib.lammps_file(self.lmp,file) def command(self,cmd): self.lib.lammps_command(self.lmp,cmd) def extract_global(self,name,type): if type == 0: self.lib.lammps_extract_global.restype = POINTER(c_int) elif type == 1: self.lib.lammps_extract_global.restype = POINTER(c_double) else: return None ptr = self.lib.lammps_extract_global(self.lmp,name) return ptr[0] def extract_atom(self,name,type): if type == 0: self.lib.lammps_extract_atom.restype = POINTER(c_int) elif type == 1: self.lib.lammps_extract_atom.restype = POINTER(POINTER(c_int)) elif type == 2: self.lib.lammps_extract_atom.restype = POINTER(c_double) elif type == 3: self.lib.lammps_extract_atom.restype = POINTER(POINTER(c_double)) else: return None ptr = self.lib.lammps_extract_atom(self.lmp,name) return ptr def extract_compute(self,id,style,type): if type == 0: if style > 0: return None self.lib.lammps_extract_compute.restype = POINTER(c_double) ptr = self.lib.lammps_extract_compute(self.lmp,id,style,type) return ptr[0] if type == 1: self.lib.lammps_extract_compute.restype = POINTER(c_double) ptr = self.lib.lammps_extract_compute(self.lmp,id,style,type) return ptr if type == 2: self.lib.lammps_extract_compute.restype = POINTER(POINTER(c_double)) ptr = self.lib.lammps_extract_compute(self.lmp,id,style,type) return ptr return None # in case of global datum, free memory for 1 double via lammps_free() # double was allocated by library interface function def extract_fix(self,id,style,type,i=0,j=0): if type == 0: if style > 0: return None self.lib.lammps_extract_fix.restype = POINTER(c_double) ptr = self.lib.lammps_extract_fix(self.lmp,id,style,type,i,j) result = ptr[0] self.lib.lammps_free(ptr) return result if type == 1: self.lib.lammps_extract_fix.restype = POINTER(c_double) ptr = self.lib.lammps_extract_fix(self.lmp,id,style,type,i,j) return ptr if type == 2: self.lib.lammps_extract_fix.restype = POINTER(POINTER(c_double)) ptr = self.lib.lammps_extract_fix(self.lmp,id,style,type,i,j) return ptr return None # free memory for 1 double or 1 vector of doubles via lammps_free() # for vector, must copy nlocal returned values to local c_double vector # memory was allocated by library interface function def extract_variable(self,name,group,type): if type == 0: self.lib.lammps_extract_variable.restype = POINTER(c_double) ptr = self.lib.lammps_extract_variable(self.lmp,name,group) result = ptr[0] self.lib.lammps_free(ptr) return result if type == 1: self.lib.lammps_extract_global.restype = POINTER(c_int) nlocalptr = self.lib.lammps_extract_global(self.lmp,"nlocal") nlocal = nlocalptr[0] result = (c_double*nlocal)() self.lib.lammps_extract_variable.restype = POINTER(c_double) ptr = self.lib.lammps_extract_variable(self.lmp,name,group) for i in xrange(nlocal): result[i] = ptr[i] self.lib.lammps_free(ptr) return result return None # return total number of atoms in system def get_natoms(self): return self.lib.lammps_get_natoms(self.lmp) # return vector of atom properties gathered across procs, ordered by atom ID def gather_atoms(self,name,type,count): natoms = self.lib.lammps_get_natoms(self.lmp) if type == 0: data = ((count*natoms)*c_int)() self.lib.lammps_gather_atoms(self.lmp,name,type,count,data) elif type == 1: data = ((count*natoms)*c_double)() self.lib.lammps_gather_atoms(self.lmp,name,type,count,data) else: return None return data # scatter vector of atom properties across procs, ordered by atom ID # assume vector is of correct type and length, as created by gather_atoms() def scatter_atoms(self,name,type,count,data): self.lib.lammps_scatter_atoms(self.lmp,name,type,count,data)
6,013
34.797619
78
py
LIGGGHTS-WITH-BONDS
LIGGGHTS-WITH-BONDS-master/python/examples/vizplotgui_atomeye.py
#!/usr/bin/env python -i # preceeding line should have path for Python on your machine # vizplotgui_atomeye.py # Purpose: viz running LAMMPS simulation via AtomEye with plot and GUI # Syntax: vizplotgui_atomeye.py in.lammps Nfreq compute-ID # in.lammps = LAMMPS input script # Nfreq = plot data point and viz shapshot every this many steps # compute-ID = ID of compute that calculates temperature # (or any other scalar quantity) # IMPORTANT: this script cannot yet be run in parallel via Pypar, # because I can't seem to do a MPI-style broadcast in Pypar import sys,os,time sys.path.append("./pizza") # set this to point to AtomEye version 3 executable # first line if want AtomEye output to screen, 2nd line to file #ATOMEYE3 = "/home/sjplimp/tools/atomeye3/A3.i686-20060530" ATOMEYE3 = "/home/sjplimp/tools/atomeye3/A3.i686-20060530 > atomeye.out" # methods called by GUI def run(): global runflag runflag = 1 def stop(): global runflag runflag = 0 def settemp(value): global temptarget temptarget = slider.get() def quit(): global breakflag breakflag = 1 # method called by timestep loop every Nfreq steps # read dump snapshot and viz it, update plot with compute value def update(ntimestep): a.write("load_config tmp.cfg.%d\n" % ntimestep) a.flush() value = lmp.extract_compute(compute,0,0) xaxis.append(ntimestep) yaxis.append(value) gn.plot(xaxis,yaxis) # parse command line argv = sys.argv if len(argv) != 4: print "Syntax: vizplotgui_atomeye.py in.lammps Nfreq compute-ID" sys.exit() infile = sys.argv[1] nfreq = int(sys.argv[2]) compute = sys.argv[3] me = 0 # uncomment if running in parallel via Pypar #import pypar #me = pypar.rank() #nprocs = pypar.size() from lammps import lammps lmp = lammps() # run infile all at once # assumed to have no run command in it # dump a file in extended CFG format for AtomEye lmp.file(infile) lmp.command("thermo %d" % nfreq) lmp.command("dump python all cfg %d tmp.cfg.* id type xs ys zs" % nfreq) # initial 0-step run to generate initial 1-point plot, dump file, and image lmp.command("run 0 pre yes post no") value = lmp.extract_compute(compute,0,0) ntimestep = 0 xaxis = [ntimestep] yaxis = [value] breakflag = 0 runflag = 0 temptarget = 1.0 # wrapper on AtomEye # just proc 0 handles reading of dump file and viz if me == 0: a = os.popen(ATOMEYE3,'w') a.write("load_config tmp.cfg.0\n") a.flush() # display GUI with run/stop buttons and slider for temperature if me == 0: from Tkinter import * tkroot = Tk() tkroot.withdraw() root = Toplevel(tkroot) root.title("LAMMPS GUI") frame = Frame(root) Button(frame,text="Run",command=run).pack(side=LEFT) Button(frame,text="Stop",command=stop).pack(side=LEFT) slider = Scale(frame,from_=0.0,to=5.0,resolution=0.1, orient=HORIZONTAL,label="Temperature") slider.bind('<ButtonRelease-1>',settemp) slider.set(temptarget) slider.pack(side=LEFT) Button(frame,text="Quit",command=quit).pack(side=RIGHT) frame.pack() tkroot.update() # wrapper on GnuPlot via Pizza.py gnu tool if me == 0: from gnu import gnu gn = gnu() gn.plot(xaxis,yaxis) gn.title(compute,"Timestep","Temperature") # endless loop, checking status of GUI settings every Nfreq steps # run with pre yes/no and post yes/no depending on go/stop status # re-invoke fix langevin with new seed when temperature slider changes # after re-invoke of fix langevin, run with pre yes running = 0 temp = temptarget seed = 12345 lmp.command("fix 2 all langevin %g %g 0.1 %d" % (temp,temp,seed)) while 1: if me == 0: tkroot.update() if temp != temptarget: temp = temptarget seed += me+1 lmp.command("fix 2 all langevin %g %g 0.1 12345" % (temp,temp)) running = 0 if runflag and running: lmp.command("run %d pre no post no" % nfreq) ntimestep += nfreq if me == 0: update(ntimestep) elif runflag and not running: lmp.command("run %d pre yes post no" % nfreq) ntimestep += nfreq if me == 0: update(ntimestep) elif not runflag and running: lmp.command("run %d pre no post yes" % nfreq) ntimestep += nfreq if me == 0: update(ntimestep) if breakflag: break if runflag: running = 1 else: running = 0 time.sleep(0.01) lmp.command("run 0 pre no post yes") # uncomment if running in parallel via Pypar #print "Proc %d out of %d procs has" % (me,nprocs), lmp #pypar.finalize()
4,459
25.86747
75
py
LIGGGHTS-WITH-BONDS
LIGGGHTS-WITH-BONDS-master/python/examples/viz_gl.py
#!/usr/bin/env python -i # preceeding line should have path for Python on your machine # viz_gl.py # Purpose: viz running LAMMPS simulation via GL tool in Pizza.py # Syntax: viz_gl.py in.lammps Nfreq Nsteps # in.lammps = LAMMPS input script # Nfreq = dump and viz shapshot every this many steps # Nsteps = run for this many steps import sys sys.path.append("./pizza") # parse command line argv = sys.argv if len(argv) != 4: print "Syntax: viz_gl.py in.lammps Nfreq Nsteps" sys.exit() infile = sys.argv[1] nfreq = int(sys.argv[2]) nsteps = int(sys.argv[3]) me = 0 # uncomment if running in parallel via Pypar #import pypar #me = pypar.rank() #nprocs = pypar.size() from lammps import lammps lmp = lammps() # run infile all at once # assumed to have no run command in it # dump a file in native LAMMPS dump format for Pizza.py dump tool lmp.file(infile) lmp.command("thermo %d" % nfreq) lmp.command("dump python all atom %d tmp.dump" % nfreq) # initial 0-step run to generate dump file and image lmp.command("run 0 pre yes post no") ntimestep = 0 # wrapper on GL window via Pizza.py gl tool # just proc 0 handles reading of dump file and viz if me == 0: import Tkinter tkroot = Tkinter.Tk() tkroot.withdraw() from dump import dump from gl import gl d = dump("tmp.dump",0) g = gl(d) d.next() d.unscale() g.zoom(1) g.shift(0,0) g.rotate(0,270) g.q(10) g.box(1) g.show(ntimestep) # run nfreq steps at a time w/out pre/post, read dump snapshot, display it while ntimestep < nsteps: lmp.command("run %d pre no post no" % nfreq) ntimestep += nfreq if me == 0: d.next() d.unscale() g.show(ntimestep) lmp.command("run 0 pre no post yes") # uncomment if running in parallel via Pypar #print "Proc %d out of %d procs has" % (me,nprocs), lmp #pypar.finalize()
1,846
20.988095
74
py
LIGGGHTS-WITH-BONDS
LIGGGHTS-WITH-BONDS-master/python/examples/simple.py
#!/usr/bin/env python -i # preceeding line should have path for Python on your machine # simple.py # Purpose: mimic operation of couple/simple/simple.cpp via Python # Syntax: simple.py in.lammps # in.lammps = LAMMPS input script import sys # parse command line argv = sys.argv if len(argv) != 2: print "Syntax: simple.py in.lammps" sys.exit() infile = sys.argv[1] me = 0 # uncomment if running in parallel via Pypar #import pypar #me = pypar.rank() #nprocs = pypar.size() from lammps import lammps lmp = lammps() # run infile one line at a time lines = open(infile,'r').readlines() for line in lines: lmp.command(line) # run 10 more steps # get coords from LAMMPS # change coords of 1st atom # put coords back into LAMMPS # run a single step with changed coords lmp.command("run 10") x = lmp.gather_atoms("x",1,3) epsilon = 0.1 x[0] += epsilon lmp.scatter_atoms("x",1,3,x) lmp.command("run 1"); # uncomment if running in parallel via Pypar #print "Proc %d out of %d procs has" % (me,nprocs), lmp #pypar.finalize()
1,041
19.431373
65
py