code
stringlengths
17
6.64M
class SpeakerEmbedding(): def __init__(self, model: EmbeddingModel, device: Optional[torch.device]=None): self.model = model self.model.eval() self.device = device if (self.device is None): self.device = torch.device('cpu') self.model.to(self.device) se...
class OverlappedSpeechPenalty(): 'Applies a penalty on overlapping speech and low-confidence regions to speaker segmentation scores.\n\n .. note::\n For more information, see `"Overlap-Aware Low-Latency Online Speaker Diarization\n based on End-to-End Local Segmentation" <https://github.com/juanm...
class EmbeddingNormalization(): def __init__(self, norm: Union[(float, torch.Tensor)]=1): self.norm = norm if (isinstance(self.norm, torch.Tensor) and (self.norm.ndim == 2)): self.norm = self.norm.unsqueeze(0) def __call__(self, embeddings: torch.Tensor) -> torch.Tensor: ...
class OverlapAwareSpeakerEmbedding(): "\n Extract overlap-aware speaker embeddings given an audio chunk and its segmentation.\n\n Parameters\n ----------\n model: EmbeddingModel\n A pre-trained embedding model.\n gamma: float, optional\n Exponent to lower low-confidence predictions.\n...
class SpeakerSegmentation(): def __init__(self, model: SegmentationModel, device: Optional[torch.device]=None): self.model = model self.model.eval() self.device = device if (self.device is None): self.device = torch.device('cpu') self.model.to(self.device) ...
class Binarize(): '\n Transform a speaker segmentation from the discrete-time domain\n into a continuous-time speaker segmentation.\n\n Parameters\n ----------\n threshold: float\n Probability threshold to determine if a speaker is active at a given frame.\n uri: Optional[Text]\n U...
class Resample(): 'Dynamically resample audio chunks.\n\n Parameters\n ----------\n sample_rate: int\n Original sample rate of the input audio\n resample_rate: int\n Sample rate of the output\n ' def __init__(self, sample_rate: int, resample_rate: int, device: Optional[torch.devi...
class AdjustVolume(): 'Change the volume of an audio chunk.\n\n Notice that the output volume might be different to avoid saturation.\n\n Parameters\n ----------\n volume_in_db: float\n Target volume in dB.\n ' def __init__(self, volume_in_db: float): self.target_db = volume_in_...
class VoiceActivityDetectionConfig(base.PipelineConfig): def __init__(self, segmentation: (m.SegmentationModel | None)=None, duration: float=5, step: float=0.5, latency: ((float | Literal[('max', 'min')]) | None)=None, tau_active: float=0.6, device: (torch.device | None)=None, sample_rate: int=16000, **kwargs): ...
class VoiceActivityDetection(base.Pipeline): def __init__(self, config: (VoiceActivityDetectionConfig | None)=None): self._config = (VoiceActivityDetectionConfig() if (config is None) else config) msg = f'Latency should be in the range [{self._config.step}, {self._config.duration}]' asser...
def run(): parser = argparse.ArgumentParser() parser.add_argument('root', type=Path, help='Directory with audio files CONVERSATION.(wav|flac|m4a|...)') parser.add_argument('--pipeline', default='SpeakerDiarization', type=str, help="Class of the pipeline to optimize. Defaults to 'SpeakerDiarization'") ...
def send_audio(ws: WebSocket, source: Text, step: float, sample_rate: int): source_components = source.split(':') if (source_components[0] != 'microphone'): audio_source = src.FileAudioSource(source, sample_rate, block_duration=step) else: device = (int(source_components[1]) if (len(source...
def receive_audio(ws: WebSocket, output: Optional[Path]): while True: message = ws.recv() print(f'Received: {message}', end='') if (output is not None): with open(output, 'a') as file: file.write(message)
def run(): parser = argparse.ArgumentParser() parser.add_argument('source', type=str, help="Path to an audio file | 'microphone' | 'microphone:<DEVICE_ID>'") parser.add_argument('--host', required=True, type=str, help='Server host') parser.add_argument('--port', required=True, type=int, help='Server p...
def run(): parser = argparse.ArgumentParser() parser.add_argument('--host', default='0.0.0.0', type=str, help='Server host') parser.add_argument('--port', default=7007, type=int, help='Server port') parser.add_argument('--pipeline', default='SpeakerDiarization', type=str, help="Class of the pipeline t...
def run(): parser = argparse.ArgumentParser() parser.add_argument('source', type=str, help="Path to an audio file | 'microphone' | 'microphone:<DEVICE_ID>'") parser.add_argument('--pipeline', default='SpeakerDiarization', type=str, help="Class of the pipeline to optimize. Defaults to 'SpeakerDiarization'"...
def run(): parser = argparse.ArgumentParser() parser.add_argument('root', type=str, help='Directory with audio files CONVERSATION.(wav|flac|m4a|...)') parser.add_argument('--reference', required=True, type=str, help='Directory with RTTM files CONVERSATION.rttm. Names must match audio files') parser.ad...
class TemporalFeatureFormatterState(ABC): '\n Represents the recorded type of a temporal feature formatter.\n Its job is to transform temporal features into tensors and\n recover the original format on other features.\n ' @abstractmethod def to_tensor(self, features: TemporalFeatures) -> torc...
class SlidingWindowFeatureFormatterState(TemporalFeatureFormatterState): def __init__(self, duration: float): self.duration = duration self._cur_start_time = 0 def to_tensor(self, features: SlidingWindowFeature) -> torch.Tensor: msg = 'Features sliding window duration and step must b...
class NumpyArrayFormatterState(TemporalFeatureFormatterState): def to_tensor(self, features: np.ndarray) -> torch.Tensor: return torch.from_numpy(features) def to_internal_type(self, features: torch.Tensor) -> TemporalFeatures: return features.cpu().numpy()
class PytorchTensorFormatterState(TemporalFeatureFormatterState): def to_tensor(self, features: torch.Tensor) -> torch.Tensor: return features def to_internal_type(self, features: torch.Tensor) -> TemporalFeatures: return features
class TemporalFeatureFormatter(): '\n Manages the typing and format of temporal features.\n When casting temporal features as torch.Tensor, it remembers its\n type and format so it can lately restore it on other temporal features.\n ' def __init__(self): self.state: Optional[TemporalFeatu...
def overlapped_speech_penalty(segmentation: torch.Tensor, gamma: float=3, beta: float=10): probs = torch.softmax((beta * segmentation), dim=(- 1)) weights = (torch.pow(segmentation, gamma) * torch.pow(probs, gamma)) weights[(weights < 1e-08)] = 1e-08 return weights
def normalize_embeddings(embeddings: torch.Tensor, norm: (float | torch.Tensor)=1) -> torch.Tensor: if (embeddings.ndim == 2): embeddings = embeddings.unsqueeze(0) if isinstance(norm, torch.Tensor): (batch_size1, num_speakers1, _) = norm.shape (batch_size2, num_speakers2, _) = embeddin...
class StreamingInference(): "Performs inference in real time given a pipeline and an audio source.\n Streams an audio source to an online speaker diarization pipeline.\n It allows users to attach a chain of operations in the form of hooks.\n\n Parameters\n ----------\n pipeline: StreamingPipeline\n...
class Benchmark(): '\n Run an online speaker diarization pipeline on a set of audio files in batches.\n Write predictions to a given output directory.\n\n If the reference is given, calculate the average diarization error rate.\n\n Parameters\n ----------\n speech_path: Text or Path\n Dir...
class Parallelize(): 'Wrapper to parallelize the execution of a `Benchmark` instance.\n Note that models will be copied in each worker instead of being reused.\n\n Parameters\n ----------\n benchmark: Benchmark\n Benchmark instance to execute in parallel.\n num_workers: int\n Number o...
class PowersetAdapter(nn.Module): def __init__(self, segmentation_model: nn.Module): super().__init__() self.model = segmentation_model specs = self.model.specifications max_speakers_per_frame = specs.powerset_max_classes max_speakers_per_chunk = len(specs.classes) ...
class PyannoteLoader(): def __init__(self, model_info, hf_token: Union[(Text, bool, None)]=True): super().__init__() self.model_info = model_info self.hf_token = hf_token def __call__(self) -> Callable: try: model = Model.from_pretrained(self.model_info, use_auth_...
class ONNXLoader(): def __init__(self, path: (str | Path), input_names: List[str], output_name: str): super().__init__() self.path = Path(path) self.input_names = input_names self.output_name = output_name def __call__(self) -> ONNXModel: return ONNXModel(self.path, s...
class ONNXModel(): def __init__(self, path: Path, input_names: List[str], output_name: str): super().__init__() self.path = path self.input_names = input_names self.output_name = output_name self.device = torch.device('cpu') self.session = None self.recreat...
class LazyModel(ABC): def __init__(self, loader: Callable[([], Callable)]): super().__init__() self.get_model = loader self.model: Optional[Callable] = None def is_in_memory(self) -> bool: 'Return whether the model has been loaded into memory' return (self.model is no...
class SegmentationModel(LazyModel): '\n Minimal interface for a segmentation model.\n ' @staticmethod def from_pyannote(model, use_hf_token: Union[(Text, bool, None)]=True) -> 'SegmentationModel': '\n Returns a `SegmentationModel` wrapping a pyannote model.\n\n Parameters\n ...
class EmbeddingModel(LazyModel): 'Minimal interface for an embedding model.' @staticmethod def from_pyannote(model, use_hf_token: Union[(Text, bool, None)]=True) -> 'EmbeddingModel': '\n Returns an `EmbeddingModel` wrapping a pyannote model.\n\n Parameters\n ----------\n ...
class Optimizer(): def __init__(self, pipeline_class: type, speech_path: Union[(Text, Path)], reference_path: Union[(Text, Path)], study_or_path: Union[(FilePath, Study)], batch_size: int=32, hparams: Optional[Sequence[blocks.base.HyperParameter]]=None, base_config: Optional[blocks.PipelineConfig]=None, do_kicks...
class ProgressBar(ABC): @abstractmethod def create(self, total: int, description: Optional[Text]=None, unit: Text='it', **kwargs): pass @abstractmethod def start(self): pass @abstractmethod def update(self, n: int=1): pass @abstractmethod def write(self, tex...
class RichProgressBar(ProgressBar): def __init__(self, description: Optional[Text]=None, color: Text='green', leave: bool=True, do_close: bool=True): self.description = description self.color = color self.do_close = do_close self.bar = Progress(transient=(not leave)) self....
class TQDMProgressBar(ProgressBar): def __init__(self, description: Optional[Text]=None, leave: bool=True, position: Optional[int]=None, do_close: bool=True): self.description = description self.leave = leave self.position = position self.do_close = do_close self.pbar: Opt...
class WindowClosedException(Exception): pass
def _extract_prediction(value: Union[(Tuple, Annotation)]) -> Annotation: if isinstance(value, tuple): return value[0] if isinstance(value, Annotation): return value msg = f'Expected tuple or Annotation, but got {type(value)}' raise ValueError(msg)
class RTTMWriter(Observer): def __init__(self, uri: Text, path: Union[(Path, Text)], patch_collar: float=0.05): super().__init__() self.uri = uri self.patch_collar = patch_collar self.path = Path(path).expanduser() if self.path.exists(): self.path.unlink() ...
class PredictionAccumulator(Observer): def __init__(self, uri: Optional[Text]=None, patch_collar: float=0.05): super().__init__() self.uri = uri self.patch_collar = patch_collar self._prediction: Optional[Annotation] = None def patch(self): 'Stitch same-speaker turns ...
class StreamingPlot(Observer): def __init__(self, duration: float, latency: float, visualization: Literal[('slide', 'accumulate')]='slide', reference: Optional[Union[(Path, Text)]]=None): super().__init__() assert (visualization in ['slide', 'accumulate']) self.visualization = visualizati...
class Chronometer(): def __init__(self, unit: Text, progress_bar: Optional[ProgressBar]=None): self.unit = unit self.progress_bar = progress_bar self.current_start_time = None self.history = [] @property def is_running(self): return (self.current_start_time is not...
def parse_hf_token_arg(hf_token: Union[(bool, Text)]) -> Union[(bool, Text)]: if isinstance(hf_token, bool): return hf_token if (hf_token.lower() == 'true'): return True if (hf_token.lower() == 'false'): return False return hf_token
def encode_audio(waveform: np.ndarray) -> Text: data = waveform.astype(np.float32).tobytes() return base64.b64encode(data).decode('utf-8')
def decode_audio(data: Text) -> np.ndarray: byte_samples = base64.decodebytes(data.encode('utf-8')) samples = np.frombuffer(byte_samples, dtype=np.float32) return samples.reshape(1, (- 1))
def get_padding_left(stream_duration: float, chunk_duration: float) -> float: if (stream_duration < chunk_duration): return (chunk_duration - stream_duration) return 0
def repeat_label(label: Text): while True: (yield label)
def get_pipeline_class(class_name: Text) -> type: pipeline_class = getattr(blocks, class_name, None) msg = f"Pipeline '{class_name}' doesn't exist" assert (pipeline_class is not None), msg return pipeline_class
def get_padding_right(latency: float, step: float) -> float: return (latency - step)
def visualize_feature(duration: Optional[float]=None): def apply(feature: SlidingWindowFeature): if (duration is None): notebook.crop = feature.extent else: notebook.crop = Segment((feature.extent.end - duration), feature.extent.end) plt.rcParams['figure.figsize'] ...
def visualize_annotation(duration: Optional[float]=None): def apply(annotation: Annotation): extent = annotation.get_timeline().extent() if (duration is None): notebook.crop = extent else: notebook.crop = Segment((extent.end - duration), extent.end) plt.rcP...
class MultiHeadAttn(nn.Module): def __init__(self, dim_q, dim_k, dim_v, dim_out, num_heads=8): super().__init__() self.num_heads = num_heads self.dim_out = dim_out self.fc_q = nn.Linear(dim_q, dim_out, bias=False) self.fc_k = nn.Linear(dim_k, dim_out, bias=False) s...
class SelfAttn(MultiHeadAttn): def __init__(self, dim_in, dim_out, num_heads=8): super().__init__(dim_in, dim_in, dim_in, dim_out, num_heads) def forward(self, x, mask=None): return super().forward(x, x, x, mask=mask)
def build_mlp(dim_in, dim_hid, dim_out, depth): modules = [nn.Linear(dim_in, dim_hid), nn.ReLU(True)] for _ in range((depth - 2)): modules.append(nn.Linear(dim_hid, dim_hid)) modules.append(nn.ReLU(True)) modules.append(nn.Linear(dim_hid, dim_out)) return nn.Sequential(*modules)
class PoolingEncoder(nn.Module): def __init__(self, dim_x=1, dim_y=1, dim_hid=128, dim_lat=None, self_attn=False, pre_depth=4, post_depth=2): super().__init__() self.use_lat = (dim_lat is not None) self.net_pre = (build_mlp((dim_x + dim_y), dim_hid, dim_hid, pre_depth) if (not self_attn) ...
class CrossAttnEncoder(nn.Module): def __init__(self, dim_x=1, dim_y=1, dim_hid=128, dim_lat=None, self_attn=True, v_depth=4, qk_depth=2): super().__init__() self.use_lat = (dim_lat is not None) if (not self_attn): self.net_v = build_mlp((dim_x + dim_y), dim_hid, dim_hid, v_de...
class Decoder(nn.Module): def __init__(self, dim_x=1, dim_y=1, dim_enc=128, dim_hid=128, depth=3): super().__init__() self.fc = nn.Linear((dim_x + dim_enc), dim_hid) self.dim_hid = dim_hid modules = [nn.ReLU(True)] for _ in range((depth - 2)): modules.append(nn...
def get_logger(filename, mode='a'): logging.basicConfig(level=logging.INFO, format='%(message)s') logger = logging.getLogger() logger.addHandler(logging.FileHandler(filename, mode=mode)) return logger
class RunningAverage(object): def __init__(self, *keys): self.sum = OrderedDict() self.cnt = OrderedDict() self.clock = time.time() for key in keys: self.sum[key] = 0 self.cnt[key] = 0 def update(self, key, val): if isinstance(val, torch.Tensor...
def gen_load_func(parser, func): def load(args, cmdline): (sub_args, cmdline) = parser.parse_known_args(cmdline) for (k, v) in sub_args.__dict__.items(): args.__dict__[k] = v return (func(**sub_args.__dict__), cmdline) return load
def load_module(filename): module_name = os.path.splitext(os.path.basename(filename))[0] return SourceFileLoader(module_name, filename).load_module()
def logmeanexp(x, dim=0): return (x.logsumexp(dim) - math.log(x.shape[dim]))
def stack(x, num_samples=None, dim=0): return (x if (num_samples is None) else torch.stack(([x] * num_samples), dim=dim))
def main(): parser = argparse.ArgumentParser() parser.add_argument('--mode', choices=['train', 'eval', 'plot', 'ensemble'], default='train') parser.add_argument('--expid', type=str, default='trial') parser.add_argument('--resume', action='store_true', default=False) parser.add_argument('--gpu', ty...
def train(args, model): if (not osp.isdir(args.root)): os.makedirs(args.root) with open(osp.join(args.root, 'args.yaml'), 'w') as f: yaml.dump(args.__dict__, f) train_ds = CelebA(train=True) eval_ds = CelebA(train=False) train_loader = torch.utils.data.DataLoader(train_ds, batch_si...
def gen_evalset(args): torch.manual_seed(args.eval_seed) torch.cuda.manual_seed(args.eval_seed) eval_ds = CelebA(train=False) eval_loader = torch.utils.data.DataLoader(eval_ds, batch_size=args.eval_batch_size, shuffle=False, num_workers=4) batches = [] for (x, _) in tqdm(eval_loader): ...
def eval(args, model): if (args.mode == 'eval'): ckpt = torch.load(osp.join(args.root, 'ckpt.tar')) model.load_state_dict(ckpt.model) if (args.eval_logfile is None): eval_logfile = f'eval' if (args.t_noise is not None): eval_logfile += f'_{args.t_noi...
def ensemble(args, model): num_runs = 5 models = [] for i in range(num_runs): model_ = deepcopy(model) ckpt = torch.load(osp.join(results_path, 'celeba', args.model, f'run{(i + 1)}', 'ckpt.tar')) model_.load_state_dict(ckpt['model']) model_.cuda() model_.eval() ...
class CelebA(object): def __init__(self, train=True): (self.data, self.targets) = torch.load(osp.join(datasets_path, 'celeba', ('train.pt' if train else 'eval.pt'))) self.data = (self.data.float() / 255.0) if train: (self.data, self.targets) = (self.data, self.targets) ...
class EMNIST(tvds.EMNIST): def __init__(self, train=True, class_range=[0, 47], device='cpu', download=True): super().__init__(datasets_path, train=train, split='balanced', download=download) self.data = self.data.unsqueeze(1).float().div(255).transpose((- 1), (- 2)).to(device) self.target...
def main(): parser = argparse.ArgumentParser() parser.add_argument('--mode', choices=['train', 'eval', 'plot', 'ensemble'], default='train') parser.add_argument('--expid', type=str, default='trial') parser.add_argument('--resume', action='store_true', default=False) parser.add_argument('--gpu', ty...
def train(args, model): if (not osp.isdir(args.root)): os.makedirs(args.root) with open(osp.join(args.root, 'args.yaml'), 'w') as f: yaml.dump(args.__dict__, f) train_ds = EMNIST(train=True, class_range=args.class_range) eval_ds = EMNIST(train=False, class_range=args.class_range) t...
def gen_evalset(args): torch.manual_seed(args.eval_seed) torch.cuda.manual_seed(args.eval_seed) eval_ds = EMNIST(train=False, class_range=args.class_range) eval_loader = torch.utils.data.DataLoader(eval_ds, batch_size=args.eval_batch_size, shuffle=False, num_workers=4) batches = [] for (x, _) ...
def eval(args, model): if (args.mode == 'eval'): ckpt = torch.load(osp.join(args.root, 'ckpt.tar')) model.load_state_dict(ckpt.model) if (args.eval_logfile is None): (c1, c2) = args.class_range eval_logfile = f'eval_{c1}-{c2}' if (args.t_noise is not Non...
def ensemble(args, model): num_runs = 5 models = [] for i in range(num_runs): model_ = deepcopy(model) ckpt = torch.load(osp.join(results_path, 'emnist', args.model, f'run{(i + 1)}', 'ckpt.tar')) model_.load_state_dict(ckpt['model']) model_.cuda() model_.eval() ...
class MultiHeadAttn(nn.Module): def __init__(self, dim_q, dim_k, dim_v, dim_out, num_heads=8): super().__init__() self.num_heads = num_heads self.dim_out = dim_out self.fc_q = nn.Linear(dim_q, dim_out, bias=False) self.fc_k = nn.Linear(dim_k, dim_out, bias=False) s...
class SelfAttn(MultiHeadAttn): def __init__(self, dim_in, dim_out, num_heads=8): super().__init__(dim_in, dim_in, dim_in, dim_out, num_heads) def forward(self, x, mask=None): return super().forward(x, x, x, mask=mask)
def build_mlp(dim_in, dim_hid, dim_out, depth): modules = [nn.Linear(dim_in, dim_hid), nn.ReLU(True)] for _ in range((depth - 2)): modules.append(nn.Linear(dim_hid, dim_hid)) modules.append(nn.ReLU(True)) modules.append(nn.Linear(dim_hid, dim_out)) return nn.Sequential(*modules)
class PoolingEncoder(nn.Module): def __init__(self, dim_x=1, dim_y=1, dim_hid=128, dim_lat=None, self_attn=False, pre_depth=4, post_depth=2): super().__init__() self.use_lat = (dim_lat is not None) self.net_pre = (build_mlp((dim_x + dim_y), dim_hid, dim_hid, pre_depth) if (not self_attn) ...
class CrossAttnEncoder(nn.Module): def __init__(self, dim_x=1, dim_y=1, dim_hid=128, dim_lat=None, self_attn=True, v_depth=4, qk_depth=2): super().__init__() self.use_lat = (dim_lat is not None) if (not self_attn): self.net_v = build_mlp((dim_x + dim_y), dim_hid, dim_hid, v_de...
class Decoder(nn.Module): def __init__(self, dim_x=1, dim_y=1, dim_enc=128, dim_hid=128, depth=3): super().__init__() self.fc = nn.Linear((dim_x + dim_enc), dim_hid) self.dim_hid = dim_hid modules = [nn.ReLU(True)] for _ in range((depth - 2)): modules.append(nn...
def get_logger(filename, mode='a'): logging.basicConfig(level=logging.INFO, format='%(message)s') logger = logging.getLogger() logger.addHandler(logging.FileHandler(filename, mode=mode)) return logger
class RunningAverage(object): def __init__(self, *keys): self.sum = OrderedDict() self.cnt = OrderedDict() self.clock = time.time() for key in keys: self.sum[key] = 0 self.cnt[key] = 0 def update(self, key, val): if isinstance(val, torch.Tensor...
def gen_load_func(parser, func): def load(args, cmdline): (sub_args, cmdline) = parser.parse_known_args(cmdline) for (k, v) in sub_args.__dict__.items(): args.__dict__[k] = v return (func(**sub_args.__dict__), cmdline) return load
def load_module(filename): module_name = os.path.splitext(os.path.basename(filename))[0] return SourceFileLoader(module_name, filename).load_module()
def logmeanexp(x, dim=0): return (x.logsumexp(dim) - math.log(x.shape[dim]))
def stack(x, num_samples=None, dim=0): return (x if (num_samples is None) else torch.stack(([x] * num_samples), dim=dim))
class SetTransformer(nn.Module): def __init__(self, dim_input=3, num_outputs=1, dim_output=40, num_inds=32, dim_hidden=128, num_heads=4, ln=False): super(SetTransformer, self).__init__() self.enc = nn.Sequential(ISAB(dim_input, dim_hidden, num_heads, num_inds, ln=ln), ISAB(dim_hidden, dim_hidden,...
def gen_data(batch_size, max_length=10, test=False): length = np.random.randint(1, (max_length + 1)) x = np.random.randint(1, 100, (batch_size, length)) y = np.max(x, axis=1) (x, y) = (np.expand_dims(x, axis=2), np.expand_dims(y, axis=1)) return (x, y)
class SmallDeepSet(nn.Module): def __init__(self, pool='max'): super().__init__() self.enc = nn.Sequential(nn.Linear(in_features=1, out_features=64), nn.ReLU(), nn.Linear(in_features=64, out_features=64), nn.ReLU(), nn.Linear(in_features=64, out_features=64), nn.ReLU(), nn.Linear(in_features=64, ...
class SmallSetTransformer(nn.Module): def __init__(self): super().__init__() self.enc = nn.Sequential(SAB(dim_in=1, dim_out=64, num_heads=4), SAB(dim_in=64, dim_out=64, num_heads=4)) self.dec = nn.Sequential(PMA(dim=64, num_heads=4, num_seeds=1), nn.Linear(in_features=64, out_features=1))...
def train(model): model = model.cuda() optimizer = torch.optim.Adam(model.parameters(), lr=0.0001) criterion = nn.L1Loss().cuda() losses = [] for _ in range(500): (x, y) = gen_data(batch_size=(2 ** 10), max_length=10) (x, y) = (torch.from_numpy(x).float().cuda(), torch.from_numpy(y...
class MultivariateNormal(object): def __init__(self, dim): self.dim = dim def sample(self, B, K, labels): raise NotImplementedError def log_prob(self, X, params): raise NotImplementedError def stats(self): raise NotImplementedError def parse(self, raw): ...
class MixtureOfMVNs(object): def __init__(self, mvn): self.mvn = mvn def sample(self, B, N, K, return_gt=False): device = ('cpu' if (not torch.cuda.is_available()) else torch.cuda.current_device()) pi = Dirichlet(torch.ones(K)).sample(torch.Size([B])).to(device) labels = Cate...
class DeepSet(nn.Module): def __init__(self, dim_input, num_outputs, dim_output, dim_hidden=128): super(DeepSet, self).__init__() self.num_outputs = num_outputs self.dim_output = dim_output self.enc = nn.Sequential(nn.Linear(dim_input, dim_hidden), nn.ReLU(), nn.Linear(dim_hidden,...
class SetTransformer(nn.Module): def __init__(self, dim_input, num_outputs, dim_output, num_inds=32, dim_hidden=128, num_heads=4, ln=False): super(SetTransformer, self).__init__() self.enc = nn.Sequential(ISAB(dim_input, dim_hidden, num_heads, num_inds, ln=ln), ISAB(dim_hidden, dim_hidden, num_he...
class MAB(nn.Module): def __init__(self, dim_Q, dim_K, dim_V, num_heads, ln=False): super(MAB, self).__init__() self.dim_V = dim_V self.num_heads = num_heads self.fc_q = nn.Linear(dim_Q, dim_V) self.fc_k = nn.Linear(dim_K, dim_V) self.fc_v = nn.Linear(dim_K, dim_V)...
class SAB(nn.Module): def __init__(self, dim_in, dim_out, num_heads, ln=False): super(SAB, self).__init__() self.mab = MAB(dim_in, dim_in, dim_out, num_heads, ln=ln) def forward(self, X): return self.mab(X, X)