# AOT ID: ['0_forward']
from ctypes import c_void_p, c_long, c_int
import torch
import math
import random
import os
import tempfile
from math import inf, nan
from torch._inductor.hooks import run_intermediate_hooks
from torch._inductor.utils import maybe_profile
from torch._inductor.codegen.memory_planning import _align as align
from torch import device, empty_strided
from torch._inductor.async_compile import AsyncCompile
from torch._inductor.select_algorithm import extern_kernels
from torch._inductor.codegen.multi_kernel import MultiKernelCall
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid, split_scan_grid, grid_combo_kernels, start_graph, end_graph
from torch._C import _cuda_getCurrentRawStream as get_raw_stream

aten = torch.ops.aten
inductor_ops = torch.ops.inductor
_quantized = torch.ops._quantized
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cpu = torch._C._dynamo.guards._empty_strided_cpu
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
empty_strided_xpu = torch._C._dynamo.guards._empty_strided_xpu
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
alloc_from_pool = torch.ops.inductor._alloc_from_pool
async_compile = AsyncCompile()


# kernel path: runs/run_shard_4/inductor_cache/ms/cmsuzohbg5nq52jnvirovzkvykrzzko5xomu7zyu5e5u2lhegppw.py
# Topologically Sorted Source Nodes: [x], Original ATen: [aten.cat]
# Source node to ATen node mapping:
#   x => cat
# Graph fragment:
#   %cat : [num_users=2] = call_function[target=torch.ops.aten.cat.default](args = ([%primals_1, %primals_2], 1), kwargs = {})
triton_poi_fused_cat_0 = async_compile.triton('triton_poi_fused_cat_0', '''
import triton
import triton.language as tl
from triton.compiler.compiler import AttrsDescriptor

from torch._inductor.runtime import triton_helpers, triton_heuristics
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
from torch._inductor.runtime.hints import AutotuneHint, ReductionHint, TileHint, instance_descriptor, DeviceProperties

@triton_heuristics.pointwise(
    size_hints=[32], 
    filename=__file__,
    triton_meta={'signature': {0: '*fp32', 1: '*fp32', 2: '*fp32', 3: 'i32'}, 'device': DeviceProperties(type='cuda', index=0, cc=80, major=8, regs_per_multiprocessor=65536, max_threads_per_multi_processor=2048, multi_processor_count=108), 'constants': {}, 'configs': [AttrsDescriptor(divisible_by_16=(0, 1, 2, 3), equal_to_1=())]},
    inductor_meta={'autotune_hints': set(), 'kernel_name': 'triton_poi_fused_cat_0', 'mutated_arg_names': [], 'no_x_dim': False, 'num_load': 2, 'num_reduction': 0, 'backend_hash': 'A9C866B4A14FD3277824029365D703C2427B2E685E54EC9B3EF4ADC8D1EEAC1D', 'are_deterministic_algorithms_enabled': False, 'assert_indirect_indexing': True, 'autotune_local_cache': True, 'autotune_pointwise': True, 'autotune_remote_cache': None, 'force_disable_caches': False, 'dynamic_scale_rblock': True, 'max_autotune': False, 'max_autotune_pointwise': False, 'min_split_scan_rblock': 256, 'spill_threshold': 16, 'store_cubin': False},
    min_elem_per_thread=0
)
@triton.jit
def triton_poi_fused_cat_0(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK : tl.constexpr):
    xnumel = 32
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x0 = xindex % 8
    x1 = (xindex // 8)
    x2 = xindex
    tmp0 = x0
    tmp1 = tl.full([1], 0, tl.int64)
    tmp2 = tmp0 >= tmp1
    tmp3 = tl.full([1], 4, tl.int64)
    tmp4 = tmp0 < tmp3
    tmp5 = tl.load(in_ptr0 + ((4*x1) + x0), tmp4 & xmask, eviction_policy='evict_last', other=0.0)
    tmp6 = tmp0 >= tmp3
    tmp7 = tl.full([1], 8, tl.int64)
    tmp8 = tmp0 < tmp7
    tmp9 = tl.load(in_ptr1 + ((4*x1) + ((-4) + x0)), tmp6 & xmask, eviction_policy='evict_last', other=0.0)
    tmp10 = tl.where(tmp4, tmp5, tmp9)
    tl.store(out_ptr0 + (x2), tmp10, xmask)
''', device_str='cuda')


# kernel path: runs/run_shard_4/inductor_cache/on/coniknpwvxirxpmgesz5trl5e5vowzvika3evwvgzfy7egqn5r3x.py
# Topologically Sorted Source Nodes: [x_1], Original ATen: [aten.leaky_relu]
# Source node to ATen node mapping:
#   x_1 => gt, mul, where
# Graph fragment:
#   %add_tensor_1 : [num_users=3] = call_function[target=torch.ops.aten.add.Tensor](args = (%mm_default_1, %primals_4), kwargs = {})
#   %gt : [num_users=2] = call_function[target=torch.ops.aten.gt.Scalar](args = (%add_tensor_1, 0), kwargs = {})
#   %mul : [num_users=1] = call_function[target=torch.ops.aten.mul.Tensor](args = (%add_tensor_1, 0.2), kwargs = {})
#   %where : [num_users=2] = call_function[target=torch.ops.aten.where.self](args = (%gt, %add_tensor_1, %mul), kwargs = {})
triton_poi_fused_leaky_relu_1 = async_compile.triton('triton_poi_fused_leaky_relu_1', '''
import triton
import triton.language as tl
from triton.compiler.compiler import AttrsDescriptor

from torch._inductor.runtime import triton_helpers, triton_heuristics
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
from torch._inductor.runtime.hints import AutotuneHint, ReductionHint, TileHint, instance_descriptor, DeviceProperties

@triton_heuristics.pointwise(
    size_hints=[16], 
    filename=__file__,
    triton_meta={'signature': {0: '*fp32', 1: '*fp32', 2: '*i1', 3: '*fp32', 4: 'i32'}, 'device': DeviceProperties(type='cuda', index=0, cc=80, major=8, regs_per_multiprocessor=65536, max_threads_per_multi_processor=2048, multi_processor_count=108), 'constants': {}, 'configs': [AttrsDescriptor(divisible_by_16=(0, 1, 2, 3, 4), equal_to_1=())]},
    inductor_meta={'autotune_hints': set(), 'kernel_name': 'triton_poi_fused_leaky_relu_1', 'mutated_arg_names': [], 'no_x_dim': False, 'num_load': 2, 'num_reduction': 0, 'backend_hash': 'A9C866B4A14FD3277824029365D703C2427B2E685E54EC9B3EF4ADC8D1EEAC1D', 'are_deterministic_algorithms_enabled': False, 'assert_indirect_indexing': True, 'autotune_local_cache': True, 'autotune_pointwise': True, 'autotune_remote_cache': None, 'force_disable_caches': False, 'dynamic_scale_rblock': True, 'max_autotune': False, 'max_autotune_pointwise': False, 'min_split_scan_rblock': 256, 'spill_threshold': 16, 'store_cubin': False},
    min_elem_per_thread=0
)
@triton.jit
def triton_poi_fused_leaky_relu_1(in_ptr0, in_ptr1, out_ptr0, out_ptr1, xnumel, XBLOCK : tl.constexpr):
    xnumel = 16
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x2 = xindex
    x0 = xindex % 4
    tmp0 = tl.load(in_ptr0 + (x2), xmask)
    tmp1 = tl.load(in_ptr1 + (x0), xmask, eviction_policy='evict_last')
    tmp2 = tmp0 + tmp1
    tmp3 = 0.0
    tmp4 = tmp2 > tmp3
    tmp5 = 0.2
    tmp6 = tmp2 * tmp5
    tmp7 = tl.where(tmp4, tmp2, tmp6)
    tl.store(out_ptr0 + (x2), tmp4, xmask)
    tl.store(out_ptr1 + (x2), tmp7, xmask)
''', device_str='cuda')


# kernel path: runs/run_shard_4/inductor_cache/b7/cb7iq44xucvx4o4uio3etz5hrrkllxx5igr3vjyglpwcku6mi232.py
# Topologically Sorted Source Nodes: [sigmoid], Original ATen: [aten.sigmoid]
# Source node to ATen node mapping:
#   sigmoid => sigmoid
# Graph fragment:
#   %add_tensor : [num_users=1] = call_function[target=torch.ops.aten.add.Tensor](args = (%mm_default, %primals_6), kwargs = {})
#   %sigmoid : [num_users=1] = call_function[target=torch.ops.aten.sigmoid.default](args = (%add_tensor,), kwargs = {})
triton_poi_fused_sigmoid_2 = async_compile.triton('triton_poi_fused_sigmoid_2', '''
import triton
import triton.language as tl
from triton.compiler.compiler import AttrsDescriptor

from torch._inductor.runtime import triton_helpers, triton_heuristics
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
from torch._inductor.runtime.hints import AutotuneHint, ReductionHint, TileHint, instance_descriptor, DeviceProperties

@triton_heuristics.pointwise(
    size_hints=[4], 
    filename=__file__,
    triton_meta={'signature': {0: '*fp32', 1: '*fp32', 2: 'i32'}, 'device': DeviceProperties(type='cuda', index=0, cc=80, major=8, regs_per_multiprocessor=65536, max_threads_per_multi_processor=2048, multi_processor_count=108), 'constants': {}, 'configs': [AttrsDescriptor(divisible_by_16=(0, 1), equal_to_1=())]},
    inductor_meta={'autotune_hints': set(), 'kernel_name': 'triton_poi_fused_sigmoid_2', 'mutated_arg_names': ['in_out_ptr0'], 'no_x_dim': False, 'num_load': 2, 'num_reduction': 0, 'backend_hash': 'A9C866B4A14FD3277824029365D703C2427B2E685E54EC9B3EF4ADC8D1EEAC1D', 'are_deterministic_algorithms_enabled': False, 'assert_indirect_indexing': True, 'autotune_local_cache': True, 'autotune_pointwise': True, 'autotune_remote_cache': None, 'force_disable_caches': False, 'dynamic_scale_rblock': True, 'max_autotune': False, 'max_autotune_pointwise': False, 'min_split_scan_rblock': 256, 'spill_threshold': 16, 'store_cubin': False},
    min_elem_per_thread=0
)
@triton.jit
def triton_poi_fused_sigmoid_2(in_out_ptr0, in_ptr0, xnumel, XBLOCK : tl.constexpr):
    xnumel = 4
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x0 = xindex
    tmp0 = tl.load(in_out_ptr0 + (x0), xmask)
    tmp1 = tl.load(in_ptr0 + (0))
    tmp2 = tl.broadcast_to(tmp1, [XBLOCK])
    tmp3 = tmp0 + tmp2
    tmp4 = tl.sigmoid(tmp3)
    tl.store(in_out_ptr0 + (x0), tmp4, xmask)
''', device_str='cuda')


async_compile.wait(globals())
del async_compile

def call(args):
    primals_1, primals_2, primals_3, primals_4, primals_5, primals_6 = args
    args.clear()
    assert_size_stride(primals_1, (4, 4), (4, 1))
    assert_size_stride(primals_2, (4, 4), (4, 1))
    assert_size_stride(primals_3, (4, 8), (8, 1))
    assert_size_stride(primals_4, (4, ), (1, ))
    assert_size_stride(primals_5, (1, 4), (4, 1))
    assert_size_stride(primals_6, (1, ), (1, ))
    with torch.cuda._DeviceGuard(0):
        torch.cuda.set_device(0)
        buf0 = empty_strided_cuda((4, 8), (8, 1), torch.float32)
        # Topologically Sorted Source Nodes: [x], Original ATen: [aten.cat]
        stream0 = get_raw_stream(0)
        triton_poi_fused_cat_0.run(primals_1, primals_2, buf0, 32, grid=grid(32), stream=stream0)
        del primals_1
        del primals_2
        buf1 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
        # Topologically Sorted Source Nodes: [], Original ATen: []
        extern_kernels.mm(buf0, reinterpret_tensor(primals_3, (8, 4), (1, 8), 0), out=buf1)
        del primals_3
        buf2 = empty_strided_cuda((4, 4), (4, 1), torch.bool)
        buf3 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
        # Topologically Sorted Source Nodes: [x_1], Original ATen: [aten.leaky_relu]
        triton_poi_fused_leaky_relu_1.run(buf1, primals_4, buf2, buf3, 16, grid=grid(16), stream=stream0)
        del buf1
        del primals_4
        buf4 = empty_strided_cuda((4, 1), (1, 1), torch.float32)
        # Topologically Sorted Source Nodes: [], Original ATen: []
        extern_kernels.mm(buf3, reinterpret_tensor(primals_5, (4, 1), (1, 4), 0), out=buf4)
        buf5 = buf4; del buf4  # reuse
        # Topologically Sorted Source Nodes: [sigmoid], Original ATen: [aten.sigmoid]
        triton_poi_fused_sigmoid_2.run(buf5, primals_6, 4, grid=grid(4), stream=stream0)
        del primals_6
    return (buf5, buf0, buf2, buf3, buf5, primals_5, )


def benchmark_compiled_module(times=10, repeat=10):
    from torch._dynamo.testing import rand_strided
    from torch._inductor.utils import print_performance
    primals_1 = rand_strided((4, 4), (4, 1), device='cuda:0', dtype=torch.float32)
    primals_2 = rand_strided((4, 4), (4, 1), device='cuda:0', dtype=torch.float32)
    primals_3 = rand_strided((4, 8), (8, 1), device='cuda:0', dtype=torch.float32)
    primals_4 = rand_strided((4, ), (1, ), device='cuda:0', dtype=torch.float32)
    primals_5 = rand_strided((1, 4), (4, 1), device='cuda:0', dtype=torch.float32)
    primals_6 = rand_strided((1, ), (1, ), device='cuda:0', dtype=torch.float32)
    fn = lambda: call([primals_1, primals_2, primals_3, primals_4, primals_5, primals_6])
    return print_performance(fn, times=times, repeat=repeat)


if __name__ == "__main__":
    from torch._inductor.wrapper_benchmark import compiled_module_main
    compiled_module_main('None', benchmark_compiled_module)

import torch
import numpy as np
import matplotlib.pyplot as plt
import torch.nn as nn
import torch.optim as optim


class GaussianNoise(nn.Module):
    """Gaussian noise regularizer"""

    def __init__(self, device, sigma=0.1):
        super().__init__()
        self.device = device
        self.sigma = sigma

    def forward(self, x):
        if self.training and self.sigma != 0.0:
            sampled_noise = torch.randn(*x.size(), device=self.device
                ) * self.sigma
            x = x + sampled_noise
        return x


class NetUtils:
    """Contains utils to be inherited by other nets in this project"""

    def __init__(self):
        self.epoch = 0
        self.streaming_weight_history = {}
        self.streaming_gradient_history = {}
        self.histogram_weight_history = {}
        self.histogram_gradient_history = {}
        self.gnorm_history = {}
        self.gnorm_total_history = []
        self.wnorm_history = {}
        self.wnorm_total_history = []
        self.layer_list = []
        self.layer_list_names = []
        self.loss = []
        self.losses = []
        self.norm_num = 2
        self.bins = 20

    def init_layer_list(self):
        """Initializes list of layers for tracking history"""
        nn_module_ignore_list = {'batchnorm', 'activation', 'loss', 'Noise',
            'CustomCatGANLayer'}
        self.layer_list = [x for x in self._modules.values() if not any(
            excl in str(type(x)) for excl in nn_module_ignore_list)]
        self.layer_list_names = [x for x in self._modules.keys() if not any
            (excl in str(type(self._modules[x])) for excl in
            nn_module_ignore_list)]

    def init_history(self):
        """Initializes objects for storing history based on layer_list"""
        for layer in self.layer_list:
            self.streaming_weight_history[layer] = {'weight': [], 'bias': []}
            self.streaming_gradient_history[layer] = {'weight': [], 'bias': []}
            self.histogram_weight_history[layer] = {'weight': [], 'bias': []}
            self.histogram_gradient_history[layer] = {'weight': [], 'bias': []}
            self.wnorm_history[layer] = {'weight': [], 'bias': []}
            self.gnorm_history[layer] = {'weight': [], 'bias': []}

    def next_epoch(self):
        """Resets internal storage of training history to stream next epoch"""
        self.epoch += 1
        self.losses.append(np.mean(self.loss))
        self.loss = []
        self.update_wnormz()
        self.update_gnormz()
        self.update_hist_list()
        for layer in self.layer_list:
            self.streaming_weight_history[layer] = {'weight': [], 'bias': []}
            self.streaming_gradient_history[layer] = {'weight': [], 'bias': []}

    def store_weight_and_grad_norms(self):
        """
        Appends training history for summarization and visualization later. Scales each norm by the number of elements.
        Should be ran once per step per subnet.
        """
        for layer in self.layer_list:
            self.streaming_weight_history[layer]['weight'].append(layer.
                weight.norm(self.norm_num).detach().cpu().numpy().take(0) /
                layer.weight.numel())
            self.streaming_weight_history[layer]['bias'].append(layer.bias.
                norm(self.norm_num).detach().cpu().numpy().take(0) / layer.
                bias.numel())
            self.streaming_gradient_history[layer]['weight'].append(layer.
                weight.grad.norm(self.norm_num).detach().cpu().numpy().take
                (0) / layer.weight.grad.numel())
            self.streaming_gradient_history[layer]['bias'].append(layer.
                bias.grad.norm(self.norm_num).detach().cpu().numpy().take(0
                ) / layer.bias.grad.numel())

    def update_hist_list(self):
        """
        Updates the histogram history based on the weights at the end of an epoch.
        Should be ran once per epoch per subnet.
        """
        for layer in self.layer_list:
            self.histogram_weight_history[layer]['weight'].append(np.
                histogram(layer.weight.detach().cpu().numpy().reshape(-1),
                bins=self.bins))
            self.histogram_weight_history[layer]['bias'].append(np.
                histogram(layer.bias.detach().cpu().numpy().reshape(-1),
                bins=self.bins))
            if self.epoch == 0:
                self.histogram_gradient_history[layer]['weight'].append(None)
                self.histogram_gradient_history[layer]['bias'].append(None)
            else:
                self.histogram_gradient_history[layer]['weight'].append(np.
                    histogram(layer.weight.grad.detach().cpu().numpy().
                    reshape(-1), bins=self.bins))
                self.histogram_gradient_history[layer]['bias'].append(np.
                    histogram(layer.bias.grad.detach().cpu().numpy().
                    reshape(-1), bins=self.bins))

    def update_wnormz(self):
        """
        Tracks history of desired norm of weights.
        Should be ran once per epoch per subnet.
        :param norm_num: 1 = l1 norm, 2 = l2 norm
        :return: list of norms of weights by layer, as well as overall weight norm
        """
        total_norm = 0
        for layer in self.wnorm_history:
            w_norm = np.linalg.norm(self.streaming_weight_history[layer][
                'weight'], self.norm_num)
            b_norm = np.linalg.norm(self.streaming_weight_history[layer][
                'bias'], self.norm_num)
            self.wnorm_history[layer]['weight'].append(w_norm)
            self.wnorm_history[layer]['bias'].append(b_norm)
            if self.norm_num == 1:
                total_norm += abs(w_norm) + abs(b_norm)
            else:
                total_norm += w_norm ** self.norm_num + b_norm ** self.norm_num
        total_norm = total_norm ** (1.0 / self.norm_num)
        self.wnorm_total_history.append(total_norm)

    def update_gnormz(self):
        """
        Calculates gradient norms by layer as well as overall. Scales each norm by the number of elements.
        Should be ran once per epoch per subnet.
        :param norm_num: 1 = l1 norm, 2 = l2 norm
        :return: list of gradient norms by layer, as well as overall gradient norm
        """
        total_norm = 0
        for layer in self.gnorm_history:
            w_norm = np.linalg.norm(self.streaming_gradient_history[layer][
                'weight'], self.norm_num) / len(self.
                streaming_gradient_history[layer]['weight'])
            b_norm = np.linalg.norm(self.streaming_gradient_history[layer][
                'bias'], self.norm_num) / len(self.
                streaming_gradient_history[layer]['bias'])
            self.gnorm_history[layer]['weight'].append(w_norm)
            self.gnorm_history[layer]['bias'].append(b_norm)
            if self.norm_num == 1:
                total_norm += abs(w_norm) + abs(b_norm)
            else:
                total_norm += w_norm ** self.norm_num + b_norm ** self.norm_num
        total_norm = total_norm ** (1.0 / self.norm_num) / len(self.
            gnorm_history)
        self.gnorm_total_history.append(total_norm)

    def weights_init(self):
        """
        Custom weights initialization for subnets
        Should only be run when first creating net. Will reset effects of training if run after training.
        """
        for layer_name in self._modules:
            m = self._modules[layer_name]
            classname = m.__class__.__name__
            if classname.find('Linear') != -1:
                nn.init.normal_(m.weight.data, 0.0, 0.02)
                nn.init.constant_(m.bias.data, 0)
            elif classname.find('Conv') != -1:
                nn.init.normal_(m.weight.data, 0.0, 0.02)
                nn.init.constant_(m.bias.data, 0)
            elif classname.find('BatchNorm') != -1:
                nn.init.normal_(m.weight.data, 1.0, 0.02)
                nn.init.constant_(m.bias.data, 0)

    def plot_layer_scatters(self, figsize=(20, 10), show=True, save=None):
        """Plot weight and gradient norm history for each layer in layer_list across epochs"""
        assert self.epoch > 0, 'Model needs to be trained first'
        if save is None:
            save = self.path
        f, axes = plt.subplots(len(self.layer_list), 4, figsize=figsize,
            sharex=True)
        axes[0, 0].title.set_text('Weight Norms')
        axes[0, 1].title.set_text('Weight Gradient Norms')
        axes[0, 2].title.set_text('Bias Norms')
        axes[0, 3].title.set_text('Bias Gradient Norms')
        for i in range(4):
            axes[len(self.layer_list) - 1, i].set_xlabel('epochs')
        for i, layer in enumerate(self.layer_list):
            axes[i, 0].set_ylabel(self.layer_list_names[i])
            axes[i, 0].plot(self.wnorm_history[layer]['weight'])
            axes[i, 1].plot(self.gnorm_history[layer]['weight'])
            axes[i, 2].plot(self.wnorm_history[layer]['bias'])
            axes[i, 3].plot(self.gnorm_history[layer]['bias'])
        sup = self.name + ' Layer Weight and Gradient Norms'
        st = f.suptitle(sup, fontsize='x-large')
        f.tight_layout()
        st.set_y(0.96)
        f.subplots_adjust(top=0.9)
        if show:
            f.show()
        if save:
            assert os.path.exists(save
                ), 'Check that the desired save path exists.'
            os.makedirs(os.path.join(save, 'layer_scatters'), exist_ok=True)
            f.savefig(os.path.join(save, 'layer_scatters', self.name +
                '_layer_scatters.png'))

    def plot_layer_hists(self, epoch=None, figsize=(20, 10), show=True,
        save=None):
        """Plots histograms of weight and gradients for each layer in layer_list at the desired epoch"""
        if epoch is None:
            epoch = self.epoch
        if save is None:
            save = self.path
        f, axes = plt.subplots(len(self.layer_list), 4, figsize=figsize,
            sharex=False)
        axes[0, 0].title.set_text('Weight Histograms')
        axes[0, 1].title.set_text('Weight Gradient Histograms')
        axes[0, 2].title.set_text('Bias Histograms')
        axes[0, 3].title.set_text('Bias Gradient Histograms')
        for i in range(4):
            axes[len(self.layer_list) - 1, i].set_xlabel('Value')
        for i, layer in enumerate(self.layer_list):
            axes[i, 0].set_ylabel(self.layer_list_names[i])
            plt.sca(axes[i, 0])
            uu.convert_np_hist_to_plot(self.histogram_weight_history[layer]
                ['weight'][epoch])
            plt.sca(axes[i, 2])
            uu.convert_np_hist_to_plot(self.histogram_weight_history[layer]
                ['bias'][epoch])
            if epoch == 0:
                pass
            else:
                plt.sca(axes[i, 1])
                uu.convert_np_hist_to_plot(self.histogram_gradient_history[
                    layer]['weight'][epoch])
                plt.sca(axes[i, 3])
                uu.convert_np_hist_to_plot(self.histogram_gradient_history[
                    layer]['bias'][epoch])
        sup = (self.name + ' Layer Weight and Gradient Histograms - Epoch ' +
            str(epoch))
        st = f.suptitle(sup, fontsize='x-large')
        f.tight_layout()
        st.set_y(0.96)
        f.subplots_adjust(top=0.9)
        if show:
            f.show()
        if save:
            assert os.path.exists(save
                ), 'Check that the desired save path exists.'
            os.makedirs(os.path.join(save, 'layer_histograms'), exist_ok=True)
            f.savefig(os.path.join(save, 'layer_histograms', self.name +
                '_epoch_' + str(epoch) + '_layer_histograms.png'))

    def build_hist_gif(self, path=None, start=0, stop=None, freq=1, fps=5,
        final_img_frames=20):
        """
        Loop through self.histogram_weight_history and saves the images to a folder.
        :param path: Path to folder to save images. Folder will be created if it does not already exist.
        :param start: Epoch to start gif on. Default 0.
        :param stop: Epoch to end gif on. Default self.epoch (number of epochs trained so far).
        :param freq: Interval of skipping epochs. Defaults to 1 (no skipping).
        :param fps: Number of frames to display per second in gif. Defaults to 5.
        :param final_img_frames: Number of times to repeat final image of gif before it will restart. Defaults to 20 (4 seconds with 5 fps).
        :return: Saves a gif with the title net + _histogram_generation_animation.gif (as well as the images comprising the gif into the layer_histograms folder)
        """
        assert len(self.histogram_weight_history[self.layer_list[0]]['weight']
            ) > 1, 'Model not yet trained'
        if path is None:
            path = self.path
        if stop is None:
            stop = self.epoch
        ims = []
        for epoch in range(start, stop + freq, freq):
            self.plot_layer_hists(epoch=epoch, show=False, save=path)
            img_name = os.path.join(path, 'layer_histograms', self.name +
                '_epoch_' + str(epoch) + '_layer_histograms.png')
            ims.append(imageio.imread(img_name))
            plt.close()
            if epoch == stop + freq:
                for i in range(final_img_frames):
                    ims.append(imageio.imread(img_name))
                    plt.close()
        imageio.mimsave(os.path.join(path, self.name +
            '_histogram_generation_animation.gif'), ims, fps=fps)

    @torch.utils.hooks.unserializable_hook
    def activations_hook(self, grad):
        """
        Used for Grad CAM
        Hook for the gradients of the activations
        Used on the final convolutional layer
        """
        self.gradients = grad

    def get_activations_gradient(self):
        """Grad CAM Helper Function"""
        return self.gradients

    def get_activations(self):
        """Grad CAM Helper Function"""
        return self.final_conv_output


class TabularNetD(nn.Module, NetUtils):

    def __init__(self, device, H, out_dim, nc, noise, lr=0.0002, beta1=0.5,
        beta2=0.999, wd=0):
        super().__init__()
        NetUtils.__init__(self)
        self.name = 'Discriminator'
        self.device = device
        self.loss_real = None
        self.loss_fake = None
        self.noise = GaussianNoise(device=self.device, sigma=noise)
        self.fc1 = nn.Linear(out_dim + nc, H, bias=True)
        self.output = nn.Linear(H, 1, bias=True)
        self.act = nn.LeakyReLU(0.2)
        self.m = nn.Sigmoid()
        self.loss_fn = nn.BCELoss()
        self.opt = optim.Adam(self.parameters(), lr=lr, betas=(beta1, beta2
            ), weight_decay=wd)
        self.init_layer_list()
        self.init_history()
        self.update_hist_list()
        self.D_x = []
        self.Avg_D_reals = []
        self.D_G_z1 = []
        self.Avg_D_fakes = []
        self.weights_init()

    def forward(self, row, labels):
        """
        :param row: Row of input data to discriminate on
        :param labels: Label embedding
        :return: Binary classification (sigmoid activation on a single unit hidden layer)
        """
        row = self.noise(row)
        x = torch.cat([row, labels], 1)
        x = self.act(self.fc1(x))
        return self.m(self.output(x))

    def train_one_step_real(self, output, label):
        self.zero_grad()
        self.loss_real = self.loss_fn(output, label)
        self.loss_real.backward()
        self.D_x.append(output.mean().item())

    def train_one_step_fake(self, output, label):
        self.loss_fake = self.loss_fn(output, label)
        self.loss_fake.backward()
        self.D_G_z1.append(output.mean().item())

    def combine_and_update_opt(self):
        self.loss.append(self.loss_real.item() + self.loss_fake.item())
        self.opt.step()
        self.store_weight_and_grad_norms()

    def next_epoch_discrim(self):
        """Discriminator specific actions"""
        self.Avg_D_reals.append(np.mean(self.D_x))
        self.D_x = []
        self.Avg_D_fakes.append(np.mean(self.D_G_z1))
        self.D_G_z1 = []


def get_inputs():
    return [torch.rand([4, 4]), torch.rand([4, 4])]


def get_init_inputs():
    return [[], {'device': 0, 'H': 4, 'out_dim': 4, 'nc': 4, 'noise': 4}]

import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import numpy as np
import matplotlib.pyplot as plt
import torch.nn as nn
import torch.optim as optim
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor


@triton.jit
def triton_poi_fused_cat_0(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.
    constexpr):
    xnumel = 32
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x0 = xindex % 8
    x1 = xindex // 8
    x2 = xindex
    tmp0 = x0
    tl.full([1], 0, tl.int64)
    tmp3 = tl.full([1], 4, tl.int64)
    tmp4 = tmp0 < tmp3
    tmp5 = tl.load(in_ptr0 + (4 * x1 + x0), tmp4 & xmask, eviction_policy=
        'evict_last', other=0.0)
    tmp6 = tmp0 >= tmp3
    tl.full([1], 8, tl.int64)
    tmp9 = tl.load(in_ptr1 + (4 * x1 + (-4 + x0)), tmp6 & xmask,
        eviction_policy='evict_last', other=0.0)
    tmp10 = tl.where(tmp4, tmp5, tmp9)
    tl.store(out_ptr0 + x2, tmp10, xmask)


@triton.jit
def triton_poi_fused_leaky_relu_1(in_ptr0, in_ptr1, out_ptr0, out_ptr1,
    xnumel, XBLOCK: tl.constexpr):
    xnumel = 16
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x2 = xindex
    x0 = xindex % 4
    tmp0 = tl.load(in_ptr0 + x2, xmask)
    tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
    tmp2 = tmp0 + tmp1
    tmp3 = 0.0
    tmp4 = tmp2 > tmp3
    tmp5 = 0.2
    tmp6 = tmp2 * tmp5
    tmp7 = tl.where(tmp4, tmp2, tmp6)
    tl.store(out_ptr0 + x2, tmp4, xmask)
    tl.store(out_ptr1 + x2, tmp7, xmask)


@triton.jit
def triton_poi_fused_sigmoid_2(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.
    constexpr):
    xnumel = 4
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x0 = xindex
    tmp0 = tl.load(in_out_ptr0 + x0, xmask)
    tmp1 = tl.load(in_ptr0 + 0)
    tmp2 = tl.broadcast_to(tmp1, [XBLOCK])
    tmp3 = tmp0 + tmp2
    tmp4 = tl.sigmoid(tmp3)
    tl.store(in_out_ptr0 + x0, tmp4, xmask)


def call(args):
    primals_1, primals_2, primals_3, primals_4, primals_5, primals_6 = args
    args.clear()
    assert_size_stride(primals_1, (4, 4), (4, 1))
    assert_size_stride(primals_2, (4, 4), (4, 1))
    assert_size_stride(primals_3, (4, 8), (8, 1))
    assert_size_stride(primals_4, (4,), (1,))
    assert_size_stride(primals_5, (1, 4), (4, 1))
    assert_size_stride(primals_6, (1,), (1,))
    with torch.cuda._DeviceGuard(0):
        torch.cuda.set_device(0)
        buf0 = empty_strided_cuda((4, 8), (8, 1), torch.float32)
        get_raw_stream(0)
        triton_poi_fused_cat_0[grid(32)](primals_1, primals_2, buf0, 32,
            XBLOCK=32, num_warps=1, num_stages=1)
        del primals_1
        del primals_2
        buf1 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
        extern_kernels.mm(buf0, reinterpret_tensor(primals_3, (8, 4), (1, 8
            ), 0), out=buf1)
        del primals_3
        buf2 = empty_strided_cuda((4, 4), (4, 1), torch.bool)
        buf3 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
        triton_poi_fused_leaky_relu_1[grid(16)](buf1, primals_4, buf2, buf3,
            16, XBLOCK=16, num_warps=1, num_stages=1)
        del buf1
        del primals_4
        buf4 = empty_strided_cuda((4, 1), (1, 1), torch.float32)
        extern_kernels.mm(buf3, reinterpret_tensor(primals_5, (4, 1), (1, 4
            ), 0), out=buf4)
        buf5 = buf4
        del buf4
        triton_poi_fused_sigmoid_2[grid(4)](buf5, primals_6, 4, XBLOCK=4,
            num_warps=1, num_stages=1)
        del primals_6
    return buf5, buf0, buf2, buf3, buf5, primals_5


class GaussianNoise(nn.Module):
    """Gaussian noise regularizer"""

    def __init__(self, device, sigma=0.1):
        super().__init__()
        self.device = device
        self.sigma = sigma

    def forward(self, x):
        if self.training and self.sigma != 0.0:
            sampled_noise = torch.randn(*x.size(), device=self.device
                ) * self.sigma
            x = x + sampled_noise
        return x


class NetUtils:
    """Contains utils to be inherited by other nets in this project"""

    def __init__(self):
        self.epoch = 0
        self.streaming_weight_history = {}
        self.streaming_gradient_history = {}
        self.histogram_weight_history = {}
        self.histogram_gradient_history = {}
        self.gnorm_history = {}
        self.gnorm_total_history = []
        self.wnorm_history = {}
        self.wnorm_total_history = []
        self.layer_list = []
        self.layer_list_names = []
        self.loss = []
        self.losses = []
        self.norm_num = 2
        self.bins = 20

    def init_layer_list(self):
        """Initializes list of layers for tracking history"""
        nn_module_ignore_list = {'batchnorm', 'activation', 'loss', 'Noise',
            'CustomCatGANLayer'}
        self.layer_list = [x for x in self._modules.values() if not any(
            excl in str(type(x)) for excl in nn_module_ignore_list)]
        self.layer_list_names = [x for x in self._modules.keys() if not any
            (excl in str(type(self._modules[x])) for excl in
            nn_module_ignore_list)]

    def init_history(self):
        """Initializes objects for storing history based on layer_list"""
        for layer in self.layer_list:
            self.streaming_weight_history[layer] = {'weight': [], 'bias': []}
            self.streaming_gradient_history[layer] = {'weight': [], 'bias': []}
            self.histogram_weight_history[layer] = {'weight': [], 'bias': []}
            self.histogram_gradient_history[layer] = {'weight': [], 'bias': []}
            self.wnorm_history[layer] = {'weight': [], 'bias': []}
            self.gnorm_history[layer] = {'weight': [], 'bias': []}

    def next_epoch(self):
        """Resets internal storage of training history to stream next epoch"""
        self.epoch += 1
        self.losses.append(np.mean(self.loss))
        self.loss = []
        self.update_wnormz()
        self.update_gnormz()
        self.update_hist_list()
        for layer in self.layer_list:
            self.streaming_weight_history[layer] = {'weight': [], 'bias': []}
            self.streaming_gradient_history[layer] = {'weight': [], 'bias': []}

    def store_weight_and_grad_norms(self):
        """
        Appends training history for summarization and visualization later. Scales each norm by the number of elements.
        Should be ran once per step per subnet.
        """
        for layer in self.layer_list:
            self.streaming_weight_history[layer]['weight'].append(layer.
                weight.norm(self.norm_num).detach().cpu().numpy().take(0) /
                layer.weight.numel())
            self.streaming_weight_history[layer]['bias'].append(layer.bias.
                norm(self.norm_num).detach().cpu().numpy().take(0) / layer.
                bias.numel())
            self.streaming_gradient_history[layer]['weight'].append(layer.
                weight.grad.norm(self.norm_num).detach().cpu().numpy().take
                (0) / layer.weight.grad.numel())
            self.streaming_gradient_history[layer]['bias'].append(layer.
                bias.grad.norm(self.norm_num).detach().cpu().numpy().take(0
                ) / layer.bias.grad.numel())

    def update_hist_list(self):
        """
        Updates the histogram history based on the weights at the end of an epoch.
        Should be ran once per epoch per subnet.
        """
        for layer in self.layer_list:
            self.histogram_weight_history[layer]['weight'].append(np.
                histogram(layer.weight.detach().cpu().numpy().reshape(-1),
                bins=self.bins))
            self.histogram_weight_history[layer]['bias'].append(np.
                histogram(layer.bias.detach().cpu().numpy().reshape(-1),
                bins=self.bins))
            if self.epoch == 0:
                self.histogram_gradient_history[layer]['weight'].append(None)
                self.histogram_gradient_history[layer]['bias'].append(None)
            else:
                self.histogram_gradient_history[layer]['weight'].append(np.
                    histogram(layer.weight.grad.detach().cpu().numpy().
                    reshape(-1), bins=self.bins))
                self.histogram_gradient_history[layer]['bias'].append(np.
                    histogram(layer.bias.grad.detach().cpu().numpy().
                    reshape(-1), bins=self.bins))

    def update_wnormz(self):
        """
        Tracks history of desired norm of weights.
        Should be ran once per epoch per subnet.
        :param norm_num: 1 = l1 norm, 2 = l2 norm
        :return: list of norms of weights by layer, as well as overall weight norm
        """
        total_norm = 0
        for layer in self.wnorm_history:
            w_norm = np.linalg.norm(self.streaming_weight_history[layer][
                'weight'], self.norm_num)
            b_norm = np.linalg.norm(self.streaming_weight_history[layer][
                'bias'], self.norm_num)
            self.wnorm_history[layer]['weight'].append(w_norm)
            self.wnorm_history[layer]['bias'].append(b_norm)
            if self.norm_num == 1:
                total_norm += abs(w_norm) + abs(b_norm)
            else:
                total_norm += w_norm ** self.norm_num + b_norm ** self.norm_num
        total_norm = total_norm ** (1.0 / self.norm_num)
        self.wnorm_total_history.append(total_norm)

    def update_gnormz(self):
        """
        Calculates gradient norms by layer as well as overall. Scales each norm by the number of elements.
        Should be ran once per epoch per subnet.
        :param norm_num: 1 = l1 norm, 2 = l2 norm
        :return: list of gradient norms by layer, as well as overall gradient norm
        """
        total_norm = 0
        for layer in self.gnorm_history:
            w_norm = np.linalg.norm(self.streaming_gradient_history[layer][
                'weight'], self.norm_num) / len(self.
                streaming_gradient_history[layer]['weight'])
            b_norm = np.linalg.norm(self.streaming_gradient_history[layer][
                'bias'], self.norm_num) / len(self.
                streaming_gradient_history[layer]['bias'])
            self.gnorm_history[layer]['weight'].append(w_norm)
            self.gnorm_history[layer]['bias'].append(b_norm)
            if self.norm_num == 1:
                total_norm += abs(w_norm) + abs(b_norm)
            else:
                total_norm += w_norm ** self.norm_num + b_norm ** self.norm_num
        total_norm = total_norm ** (1.0 / self.norm_num) / len(self.
            gnorm_history)
        self.gnorm_total_history.append(total_norm)

    def weights_init(self):
        """
        Custom weights initialization for subnets
        Should only be run when first creating net. Will reset effects of training if run after training.
        """
        for layer_name in self._modules:
            m = self._modules[layer_name]
            classname = m.__class__.__name__
            if classname.find('Linear') != -1:
                nn.init.normal_(m.weight.data, 0.0, 0.02)
                nn.init.constant_(m.bias.data, 0)
            elif classname.find('Conv') != -1:
                nn.init.normal_(m.weight.data, 0.0, 0.02)
                nn.init.constant_(m.bias.data, 0)
            elif classname.find('BatchNorm') != -1:
                nn.init.normal_(m.weight.data, 1.0, 0.02)
                nn.init.constant_(m.bias.data, 0)

    def plot_layer_scatters(self, figsize=(20, 10), show=True, save=None):
        """Plot weight and gradient norm history for each layer in layer_list across epochs"""
        assert self.epoch > 0, 'Model needs to be trained first'
        if save is None:
            save = self.path
        f, axes = plt.subplots(len(self.layer_list), 4, figsize=figsize,
            sharex=True)
        axes[0, 0].title.set_text('Weight Norms')
        axes[0, 1].title.set_text('Weight Gradient Norms')
        axes[0, 2].title.set_text('Bias Norms')
        axes[0, 3].title.set_text('Bias Gradient Norms')
        for i in range(4):
            axes[len(self.layer_list) - 1, i].set_xlabel('epochs')
        for i, layer in enumerate(self.layer_list):
            axes[i, 0].set_ylabel(self.layer_list_names[i])
            axes[i, 0].plot(self.wnorm_history[layer]['weight'])
            axes[i, 1].plot(self.gnorm_history[layer]['weight'])
            axes[i, 2].plot(self.wnorm_history[layer]['bias'])
            axes[i, 3].plot(self.gnorm_history[layer]['bias'])
        sup = self.name + ' Layer Weight and Gradient Norms'
        st = f.suptitle(sup, fontsize='x-large')
        f.tight_layout()
        st.set_y(0.96)
        f.subplots_adjust(top=0.9)
        if show:
            f.show()
        if save:
            assert os.path.exists(save
                ), 'Check that the desired save path exists.'
            os.makedirs(os.path.join(save, 'layer_scatters'), exist_ok=True)
            f.savefig(os.path.join(save, 'layer_scatters', self.name +
                '_layer_scatters.png'))

    def plot_layer_hists(self, epoch=None, figsize=(20, 10), show=True,
        save=None):
        """Plots histograms of weight and gradients for each layer in layer_list at the desired epoch"""
        if epoch is None:
            epoch = self.epoch
        if save is None:
            save = self.path
        f, axes = plt.subplots(len(self.layer_list), 4, figsize=figsize,
            sharex=False)
        axes[0, 0].title.set_text('Weight Histograms')
        axes[0, 1].title.set_text('Weight Gradient Histograms')
        axes[0, 2].title.set_text('Bias Histograms')
        axes[0, 3].title.set_text('Bias Gradient Histograms')
        for i in range(4):
            axes[len(self.layer_list) - 1, i].set_xlabel('Value')
        for i, layer in enumerate(self.layer_list):
            axes[i, 0].set_ylabel(self.layer_list_names[i])
            plt.sca(axes[i, 0])
            uu.convert_np_hist_to_plot(self.histogram_weight_history[layer]
                ['weight'][epoch])
            plt.sca(axes[i, 2])
            uu.convert_np_hist_to_plot(self.histogram_weight_history[layer]
                ['bias'][epoch])
            if epoch == 0:
                pass
            else:
                plt.sca(axes[i, 1])
                uu.convert_np_hist_to_plot(self.histogram_gradient_history[
                    layer]['weight'][epoch])
                plt.sca(axes[i, 3])
                uu.convert_np_hist_to_plot(self.histogram_gradient_history[
                    layer]['bias'][epoch])
        sup = (self.name + ' Layer Weight and Gradient Histograms - Epoch ' +
            str(epoch))
        st = f.suptitle(sup, fontsize='x-large')
        f.tight_layout()
        st.set_y(0.96)
        f.subplots_adjust(top=0.9)
        if show:
            f.show()
        if save:
            assert os.path.exists(save
                ), 'Check that the desired save path exists.'
            os.makedirs(os.path.join(save, 'layer_histograms'), exist_ok=True)
            f.savefig(os.path.join(save, 'layer_histograms', self.name +
                '_epoch_' + str(epoch) + '_layer_histograms.png'))

    def build_hist_gif(self, path=None, start=0, stop=None, freq=1, fps=5,
        final_img_frames=20):
        """
        Loop through self.histogram_weight_history and saves the images to a folder.
        :param path: Path to folder to save images. Folder will be created if it does not already exist.
        :param start: Epoch to start gif on. Default 0.
        :param stop: Epoch to end gif on. Default self.epoch (number of epochs trained so far).
        :param freq: Interval of skipping epochs. Defaults to 1 (no skipping).
        :param fps: Number of frames to display per second in gif. Defaults to 5.
        :param final_img_frames: Number of times to repeat final image of gif before it will restart. Defaults to 20 (4 seconds with 5 fps).
        :return: Saves a gif with the title net + _histogram_generation_animation.gif (as well as the images comprising the gif into the layer_histograms folder)
        """
        assert len(self.histogram_weight_history[self.layer_list[0]]['weight']
            ) > 1, 'Model not yet trained'
        if path is None:
            path = self.path
        if stop is None:
            stop = self.epoch
        ims = []
        for epoch in range(start, stop + freq, freq):
            self.plot_layer_hists(epoch=epoch, show=False, save=path)
            img_name = os.path.join(path, 'layer_histograms', self.name +
                '_epoch_' + str(epoch) + '_layer_histograms.png')
            ims.append(imageio.imread(img_name))
            plt.close()
            if epoch == stop + freq:
                for i in range(final_img_frames):
                    ims.append(imageio.imread(img_name))
                    plt.close()
        imageio.mimsave(os.path.join(path, self.name +
            '_histogram_generation_animation.gif'), ims, fps=fps)

    @torch.utils.hooks.unserializable_hook
    def activations_hook(self, grad):
        """
        Used for Grad CAM
        Hook for the gradients of the activations
        Used on the final convolutional layer
        """
        self.gradients = grad

    def get_activations_gradient(self):
        """Grad CAM Helper Function"""
        return self.gradients

    def get_activations(self):
        """Grad CAM Helper Function"""
        return self.final_conv_output


class TabularNetDNew(nn.Module, NetUtils):

    def __init__(self, device, H, out_dim, nc, noise, lr=0.0002, beta1=0.5,
        beta2=0.999, wd=0):
        super().__init__()
        NetUtils.__init__(self)
        self.name = 'Discriminator'
        self.device = device
        self.loss_real = None
        self.loss_fake = None
        self.noise = GaussianNoise(device=self.device, sigma=noise)
        self.fc1 = nn.Linear(out_dim + nc, H, bias=True)
        self.output = nn.Linear(H, 1, bias=True)
        self.act = nn.LeakyReLU(0.2)
        self.m = nn.Sigmoid()
        self.loss_fn = nn.BCELoss()
        self.opt = optim.Adam(self.parameters(), lr=lr, betas=(beta1, beta2
            ), weight_decay=wd)
        self.init_layer_list()
        self.init_history()
        self.update_hist_list()
        self.D_x = []
        self.Avg_D_reals = []
        self.D_G_z1 = []
        self.Avg_D_fakes = []
        self.weights_init()

    def train_one_step_real(self, output, label):
        self.zero_grad()
        self.loss_real = self.loss_fn(output, label)
        self.loss_real.backward()
        self.D_x.append(output.mean().item())

    def train_one_step_fake(self, output, label):
        self.loss_fake = self.loss_fn(output, label)
        self.loss_fake.backward()
        self.D_G_z1.append(output.mean().item())

    def combine_and_update_opt(self):
        self.loss.append(self.loss_real.item() + self.loss_fake.item())
        self.opt.step()
        self.store_weight_and_grad_norms()

    def next_epoch_discrim(self):
        """Discriminator specific actions"""
        self.Avg_D_reals.append(np.mean(self.D_x))
        self.D_x = []
        self.Avg_D_fakes.append(np.mean(self.D_G_z1))
        self.D_G_z1 = []

    def forward(self, input_0, input_1):
        primals_3 = self.fc1.weight
        primals_4 = self.fc1.bias
        primals_5 = self.output.weight
        primals_6 = self.output.bias
        primals_1 = input_0
        primals_2 = input_1
        output = call([primals_1, primals_2, primals_3, primals_4,
            primals_5, primals_6])
        return output[0]
