# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.

# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
# --------------------------------------------------------
# References:
# timm: https://github.com/rwightman/pytorch-image-models/tree/master/timm
# DeiT: https://github.com/facebookresearch/deit
# --------------------------------------------------------

from functools import partial

import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from timm.models.vision_transformer import PatchEmbed, Block
from util.pos_embed import get_2d_sincos_pos_embed, get_1d_sincos_pos_embed_from_grid
from layers.tcn import f_embed, tcn_embed, DepthwiseSeparableConv
from layers.tcn import DepthwiseSeparableConv1 as DSConv
# decomposition

class moving_avg(nn.Module):
    """
    Moving average block to highlight the trend of time series
    """
    def __init__(self, kernel_size, stride):
        super(moving_avg, self).__init__()
        self.kernel_size = kernel_size
        self.avg = nn.AvgPool1d(kernel_size=kernel_size, stride=stride, padding=0)

    def forward(self, x):
        # padding on the both ends of time series
        front = x[:, 0:1, :].repeat(1, (self.kernel_size - 1) // 2, 1)
        end = x[:, -1:, :].repeat(1, (self.kernel_size - 1) // 2, 1)
        x = torch.cat([front, x, end], dim=1)
        x = self.avg(x.permute(0, 2, 1))
        x = x.permute(0, 2, 1)
        return x


class series_decomp(nn.Module):
    """
    Series decomposition block
    """
    def __init__(self, kernel_size):
        super(series_decomp, self).__init__()
        self.moving_avg = moving_avg(kernel_size, stride=1)

    def forward(self, x):
        moving_mean = self.moving_avg(x)
        res = x - moving_mean
        return res, moving_mean


class Transpose(nn.Module):
    """ Wrapper class of torch.transpose() for Sequential module. """
    def __init__(self, shape: tuple):
        super(Transpose, self).__init__()
        self.shape = shape

    def forward(self, x):
        return x.transpose(*self.shape)
    

class TrendBlock(nn.Module):
    """
    Model trend of time series using the polynomial regressor.
    """
    def __init__(self, in_dim, out_dim, in_feat, out_feat, act):
        super(TrendBlock, self).__init__()
        trend_poly = 3
        self.trend = nn.Sequential(
            nn.Conv1d(in_channels=in_dim, out_channels=trend_poly, kernel_size=3, padding=1),
            act,
            Transpose(shape=(1, 2)),
            nn.Conv1d(in_feat, out_feat, 3, stride=1, padding=1)
        )

        lin_space = torch.arange(1, out_dim + 1, 1) / (out_dim + 1)
        self.poly_space = torch.stack([lin_space ** float(p + 1) for p in range(trend_poly)], dim=0)

    def forward(self, input):
        # input = input.transpose(2,1)
        b, c, h = input.shape
        # print(input.shape)
        x = self.trend(input).transpose(1, 2)
        trend_vals = torch.matmul(x.transpose(1, 2), self.poly_space.to(x.device))
        trend_vals = trend_vals.transpose(1, 2)
        return trend_vals


class TPC(nn.Module):
    """ Masked Autoencoder with VisionTransformer backbone
    """

    def __init__(self, img_size=32, patch_size=32, in_chans=7,
                 embed_dim=1024, depth=24, num_heads=16,
                 decoder_embed_dim=512, decoder_depth=8, decoder_num_heads=16,
                 mlp_ratio=4., norm_layer=nn.LayerNorm, norm_pix_loss=False):
        super().__init__()
        # 压缩倍数
        img_size = patch_size
        if in_chans <=7 :
            tcn_embed_dim = embed_dim // 8
            dec_times = 4
            dpk = 128
            self.event_num = img_size**2//16
            patch_l = 2
        elif in_chans >7 and in_chans <=10:
            tcn_embed_dim = embed_dim // 8
            dec_times = 4
            dpk = 128
            self.event_num = img_size**2//16
            patch_l = 2
        elif in_chans >10 :
            tcn_embed_dim = embed_dim // 8
            dec_times = 4
            dpk = 128
            self.event_num = img_size**2//4
            patch_l = 1
        
        
        self.restore_times = img_size**2//self.event_num
        self.in_chans = in_chans
        enc_ly = 3 # etth 3  2
        dec_ly = 1 # etth 1  2
        # --------------------------------------------------------------------------
        # MAE encoder specifics
        self.te_patch = f_embed(in_chans, tcn_embed_dim, patch_l)
        self.tcn = tcn_embed(in_chans, tcn_embed_dim, patch_l)

        self.Linear = nn.Linear(in_chans, (self.event_num)*(tcn_embed_dim//4), bias=True)
        self.expend = nn.Sequential(
            nn.Linear(tcn_embed_dim // 4, tcn_embed_dim, bias=True),
            nn.ReLU(True),
            nn.Linear(tcn_embed_dim, tcn_embed_dim, bias=True),
        )
        
        self.expend1 = nn.Linear(tcn_embed_dim, embed_dim, bias=True)
        self.expend2 = nn.Conv1d(tcn_embed_dim, embed_dim, 1,1)
        self.expend3 = nn.Conv1d(tcn_embed_dim, embed_dim, 1,1)

        num_patches = self.event_num
        self.decomp_module = series_decomp(2+1)
        self.dsconv_e3 = DepthwiseSeparableConv(tcn_embed_dim, tcn_embed_dim, 1 + 4, ds_kernel_size=8,
                                             depth_multiplier=dpk, layers=enc_ly)
        self.dsconv_e2 = DepthwiseSeparableConv(tcn_embed_dim, tcn_embed_dim, 1 + 4,
                                             depth_multiplier=dpk, layers=enc_ly+1)
        self.dsconv_e1 = DepthwiseSeparableConv(tcn_embed_dim, tcn_embed_dim, 1 + 4,
                                             depth_multiplier=dpk, layers=enc_ly)
        self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim))
        self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + 1, embed_dim),
                                      requires_grad=False)  # fixed sin-cos embedding

        self.blocks = nn.ModuleList([
            Block(embed_dim, num_heads, mlp_ratio, qkv_bias=True, qk_scale=None, norm_layer=norm_layer, attn_drop=0.1, drop=0.1)
            for i in range(depth)])
        self.norm = norm_layer(embed_dim)
        self.ffn = nn.Sequential(
            nn.Linear(embed_dim, embed_dim//4, bias=True),
            nn.Linear(embed_dim//4, embed_dim, bias=True)
        )
        self.blocks.append(self.norm)
        self.blocks.append(self.ffn)
        # --------------------------------------------------------------------------
        self.bridge = nn.Sequential(
            nn.Linear(embed_dim, embed_dim, bias=True),
            nn.ReLU(True),
            nn.Linear(embed_dim, embed_dim, bias=True),
        )
        # --------------------------------------------------------------------------
        
        tcn_decoder_embed_dim = decoder_embed_dim//dec_times
        self.decoder_embed = nn.Linear(embed_dim, tcn_decoder_embed_dim, bias=True)
        self.expend4 = nn.Conv1d(tcn_decoder_embed_dim, decoder_embed_dim, 1,1)
        self.expend5 = nn.Conv1d(decoder_embed_dim, tcn_decoder_embed_dim, 1,1)
        self.decomp_module1 = series_decomp(8+1)
        self.decomp_module2 = series_decomp(4+1)
        self.dsconv_d1 = DepthwiseSeparableConv(tcn_decoder_embed_dim, tcn_decoder_embed_dim, 1 + 8, 
                                              ds_kernel_size=16, depth_multiplier=32,
                                              layers=dec_ly)
        self.dsconv_d2 = DepthwiseSeparableConv(tcn_decoder_embed_dim, tcn_decoder_embed_dim, 1 + 4,
                                              ds_kernel_size=16, depth_multiplier=32,
                                              layers=dec_ly)
        self.dsconv_d3 = DepthwiseSeparableConv(tcn_decoder_embed_dim, tcn_decoder_embed_dim, 1 + 8,
                                              ds_kernel_size=16, depth_multiplier=32,
                                              layers=dec_ly)
        self.dsconv_d4 = DepthwiseSeparableConv(tcn_decoder_embed_dim, tcn_decoder_embed_dim, 1 + 4, 
                                              ds_kernel_size=16, depth_multiplier=32,
                                              layers=dec_ly)
        self.mask_token = nn.Parameter(torch.zeros(1, 1, tcn_decoder_embed_dim))

        self.decoder_pos_embed = nn.Parameter(torch.zeros(1, self.event_num + 1, decoder_embed_dim),
                                              requires_grad=False)  # fixed sin-cos embedding

        self.decoder_blocks = nn.ModuleList([
            Block(decoder_embed_dim, decoder_num_heads, mlp_ratio, qkv_bias=True, qk_scale=None, norm_layer=norm_layer, attn_drop=0.1, drop=0.1)
            for i in range(decoder_depth)])
        self.decoder_norm = norm_layer(decoder_embed_dim)
        self.ffn1 = nn.Sequential(
            nn.Linear(decoder_embed_dim, decoder_embed_dim*4, bias=True),
            nn.Linear(decoder_embed_dim*4, decoder_embed_dim, bias=True)
        )
        self.decoder_pred = nn.Linear(tcn_decoder_embed_dim, in_chans*self.restore_times, bias=True)  # decoder to patch
        self.decoder_blocks.append(self.decoder_norm)
        # --------------------------------------------------------------------------
        self.norm_pix_loss = norm_pix_loss

        self.initialize_weights()

    def initialize_weights(self):
        # initialization
        # initialize (and freeze) pos_embed by sin-cos embedding
        pos_embed = get_1d_sincos_pos_embed_from_grid(self.pos_embed.shape[-1], int(self.event_num)+1)
        self.pos_embed.data.copy_(torch.from_numpy(pos_embed).float().unsqueeze(0))

        decoder_pos_embed = get_1d_sincos_pos_embed_from_grid(self.decoder_pos_embed.shape[-1],
                                                              int(self.restore_times*self.event_num)+1)
        self.decoder_pos_embed.data.copy_(torch.from_numpy(decoder_pos_embed).float().unsqueeze(0))

        # initialize patch_embed like nn.Linear (instead of nn.Conv2d)
        # w = self.patch_embed.proj.weight.data
        # torch.nn.init.xavier_uniform_(w.view([w.shape[0], -1]))

        # timm's trunc_normal_(std=.02) is effectively normal_(std=0.02) as cutoff is too big (2.)
        torch.nn.init.normal_(self.cls_token, std=.02)
        torch.nn.init.normal_(self.mask_token, std=.02)

        # initialize nn.Linear and nn.LayerNorm
        self.apply(self._init_weights)

    def _init_weights(self, m):
        if isinstance(m, nn.Linear):
            # we use xavier_uniform following official JAX ViT:
            torch.nn.init.xavier_uniform_(m.weight)
            if isinstance(m, nn.Linear) and m.bias is not None:
                nn.init.constant_(m.bias, 0)
        elif isinstance(m, nn.LayerNorm):
            nn.init.constant_(m.bias, 0)
            nn.init.constant_(m.weight, 1.0)

    def random_masking(self, x,x_r, mask_ratio):
        """
        Perform per-sample random masking by per-sample shuffling.
        Per-sample shuffling is done by argsort random noise.
        x: [N, L, D], sequence
        """
        N, L, D = x.shape  # batch, length, dim
        noise = torch.rand(N, L, device=x.device)  # noise in [0, 1]
        len_keep = int(L * (1 - mask_ratio))
        # sort noise for each sample
        ids_shuffle = torch.argsort(noise, dim=1)  # ascend: small is keep, large is remove
        ids_restore = torch.argsort(ids_shuffle, dim=1)
        # keep the first subset
        ids_keep = ids_shuffle[:, :len_keep]
        x_masked = torch.gather(x, dim=1, index=ids_keep.unsqueeze(-1).repeat(1, 1, D))
        xr_masked = torch.gather(x_r, dim=1, index=ids_keep.unsqueeze(-1).repeat(1, 1, D))
        
        # generate the binary mask: 0 is keep, 1 is remove
        mask = torch.ones([N, L], device=x.device)
        mask[:, :len_keep] = 0
        # unshuffle to get the binary mask
        mask = torch.gather(mask, dim=1, index=ids_restore)

        return x_masked, xr_masked, mask, ids_restore

    def forward_encoder(self, x, mask_ratio):
        
        # embed patches
        B, L, N = x.shape
        x0 = self.te_patch(x.permute(0, 2, 1)).permute(0, 2, 1)
        x1 = self.expend(self.Linear(x).reshape(B, self.event_num, -1))
        x2 = self.tcn(x.permute(0, 2, 1)).permute(0, 2, 1)
        x = x0 + x2 + x1

        x_r, x_t = self.decomp_module(x)
        x_r = self.dsconv_e1(x_r.permute(0, 2, 1)).permute(0, 2, 1)
        x_rr, x_rt = self.decomp_module(x_r)
        x_rt = self.expend2(self.dsconv_e2(x_rt.permute(0, 2, 1))).permute(0, 2, 1)
        x_rr = self.expend3(self.dsconv_e3(x_rr.permute(0, 2, 1))).permute(0, 2, 1)
        
        # add pos embed w/o cls token
        x = self.pos_embed[:, 1:, :] + self.expend1(x_t)
        # append cls token
        cls_token = self.cls_token + self.pos_embed[:, :1, :]
        cls_tokens = cls_token.expand(x.shape[0], -1, -1)

        # masking: length -> length * mask_ratio
        x, x_r, mask, ids_restore = self.random_masking(x, x_rr + x_rt, mask_ratio)
        x_r = torch.cat((cls_tokens, x_r), dim=1)
        x = torch.cat((cls_tokens, x), dim=1)

        
        # apply Transformer blocks
        for blk in self.blocks:
            x = blk(x)
        
        x = self.bridge(x + x_r)
        x = self.decoder_embed(x)
        mask_tokens = self.mask_token.repeat(x.shape[0], ids_restore.shape[1] + 1 - x.shape[1], 1)
        x_ = torch.cat([x[:, 1:, :], mask_tokens], dim=1)  # no cls token
        x_ = torch.gather(x_, dim=1, index=ids_restore.unsqueeze(-1).repeat(1, 1, x.shape[2]))  # unshuffle
        x_l = torch.cat([x[:, :1, :],x_], dim=1)
        return x_l, mask, ids_restore, None

    def forward_decoder(self, x, ids_restore):
        # embed tokens
        x_l = x
        x_ = x[:,1:,:]
        x_r, x_t = self.decomp_module1(x_)
    
        # append mask tokens to sequence
        x_r = self.dsconv_d1(x_r.permute(0,2,1)).permute(0,2,1)
        x_rr, x_rt = self.decomp_module2(x_r)
        x_rt = self.dsconv_d2(x_rt.permute(0,2,1)).permute(0,2,1)
        x_rt = torch.cat([x[:, :1, :], x_rt], dim=1)  # append cls token
        
        x_ =  self.dsconv_d3(x_rr.permute(0, 2, 1)).permute(0, 2, 1)#.permute(0, 2, 1)
        x_rr = torch.cat([x[:, :1, :], x_], dim=1)  # append cls token

        x_t = self.dsconv_d4(x_t.permute(0,2,1)).permute(0,2,1)
        x_t = torch.cat([x[:, :1, :], x_t], dim=1)  # append cls token

        # add pos embed
        x_t = self.expend4(x_t.permute(0,2,1)).permute(0,2,1) + self.decoder_pos_embed
        # apply Transformer blocks
        for blk in self.decoder_blocks:
            x_t = blk(x_t)
        x_t = self.expend5(x_t.permute(0,2,1)).permute(0,2,1)
        # predictor projection
        x_out = (self.decoder_pred(x_t + x_rt+x_rr)[:,1:,:])
        x_out = x_out.reshape(x.shape[0],(x_t.shape[1]-1)*self.restore_times, -1)

        # remove cls token
        return x_out, x_l

    def encoder(self, x):
       with torch.no_grad():
        self.eval()
        B, L, N = x.shape
        x0 = self.te_patch(x.permute(0, 2, 1)).permute(0, 2, 1)
        x1 = self.expend(self.Linear(x).reshape(B, self.event_num, -1))
        x2 = self.tcn(x.permute(0, 2, 1)).permute(0, 2, 1)
        x = x0 + x2 + x1

        x_r, x_t = self.decomp_module(x)
        x_r = self.dsconv_e1(x_r.permute(0, 2, 1)).permute(0, 2, 1)
        x_rr, x_rt = self.decomp_module(x_r)
        x_rt = self.expend2(self.dsconv_e2(x_rt.permute(0, 2, 1))).permute(0, 2, 1)
        x_rr = self.expend3(self.dsconv_e3(x_rr.permute(0, 2, 1))).permute(0, 2, 1)
        
        # add pos embed w/o cls token
        x = self.pos_embed[:, 1:, :] + self.expend1(x_t)
        # append cls token
        cls_token = self.cls_token + self.pos_embed[:, :1, :]
        cls_tokens = cls_token.expand(x.shape[0], -1, -1)

        # masking: length -> length * mask_ratio
        x, x_r, mask, ids_restore = self.random_masking(x, x_rr + x_rt, 0.00005)
        x_r = torch.cat((cls_tokens, x_r), dim=1)
        x = torch.cat((cls_tokens, x), dim=1)

        
        # apply Transformer blocks
        for blk in self.blocks:
            x = blk(x)
        x = self.bridge(x + x_r)
        x = self.decoder_embed(x)
        mask_tokens = self.mask_token.repeat(x.shape[0], ids_restore.shape[1] + 1 - x.shape[1], 1)
        x_ = torch.cat([x[:, 1:, :], mask_tokens], dim=1)  # no cls token
        x_ = torch.gather(x_, dim=1, index=ids_restore.unsqueeze(-1).repeat(1, 1, x.shape[2]))  # unshuffle
        x_l = torch.cat([x[:, :1, :],x_], dim=1)
        
        return x_l

    def decoder(self, x):
        with torch.no_grad():
            self.eval()
            # embed tokens
            x_ = x[:,1:,:]
            x_r, x_t = self.decomp_module1(x_)
        
            # append mask tokens to sequence
            x_r = self.dsconv_d1(x_r.permute(0,2,1)).permute(0,2,1)
            x_rr, x_rt = self.decomp_module2(x_r)
            x_rt = self.dsconv_d2(x_rt.permute(0,2,1)).permute(0,2,1)
            x_rt = torch.cat([x[:, :1, :], x_rt], dim=1)  # append cls token
            
            x_ =  self.dsconv_d3(x_rr.permute(0, 2, 1)).permute(0, 2, 1)#.permute(0, 2, 1)
            x_rr = torch.cat([x[:, :1, :], x_], dim=1)  # append cls token

            x_t = self.dsconv_d4(x_t.permute(0,2,1)).permute(0,2,1)
            x_t = torch.cat([x[:, :1, :], x_t], dim=1)  # append cls token

            # add pos embed
            x_t = self.expend4(x_t.permute(0,2,1)).permute(0,2,1) + self.decoder_pos_embed
            # apply Transformer blocks
            for blk in self.decoder_blocks:
                x_t = blk(x_t)
            x_t = self.expend5(x_t.permute(0,2,1)).permute(0,2,1)
            # predictor projection
            x_out = (self.decoder_pred(x_t + x_rt+x_rr)[:,1:,:])
            x_out = x_out.reshape(x.shape[0],(x_t.shape[1]-1)*self.restore_times, -1)

            # remove cls token

        return x_out

    def forward_loss(self, x, pred, mask):
        loss = F.mse_loss(pred, x)
        return loss
    
    def dif_loss(self, y_true, y_pred):
        # 计算真实值和预测值的梯度
        grad_true = y_true[:, 1:, :] - y_true[:, :-1, :]  # y_t+1 - y_t
        grad_pred = y_pred[:, 1:, :] - y_pred[:, :-1, :]  # y_hat_t+1 - y_hat_t
        
        # 计算梯度差的绝对值
        grad_loss = torch.mean(torch.abs(grad_true - grad_pred))
        
        return grad_loss

    def forward(self, x, mask_ratio=0.75):
        B, L, N = x.shape
        x_noise = 0.0 *x* torch.rand_like(x).to(x.device)
        x_lable = x + x_noise
        
        latent, mask, ids_restore, _= self.forward_encoder(x_lable, mask_ratio)
        
        pred, x_l = self.forward_decoder(latent, ids_restore)
        loss_rec = self.forward_loss(x, pred, mask)
        # loss_peak = self.dif_loss(x, pred)
        loss = loss_rec #+ 0.1*loss_peak
        return loss, [pred, x_l], loss_rec.item()

    def test(self, x, mask_ratio=0.75):
        with torch.no_grad():
            B, L, N = x.shape
            x_noise = 0.0 *((x).std())* torch.rand_like(x).to(x.device)
            x_lable = x + x_noise
            
            x_ = x_lable.reshape(B, int(L**.5), int(L**.5), N).permute(0, 3, 1, 2)
            latent, mask, ids_restore, _ = self.forward_encoder(x_, mask_ratio)
            pred, x_l = self.forward_decoder(latent, ids_restore)  # [N, L, p*p*3]
            loss = self.forward_loss(x, pred, mask)
        return loss, [pred,x_l], latent
       

class TransferTS(nn.Module):
    def __init__(self, img_size=32, patch_size=32, in_chans=7,
                 embed_dim=1024, depth=24, num_heads=16,
                 decoder_embed_dim=512, decoder_depth=8, decoder_num_heads=16,
                 mlp_ratio=4., norm_layer=nn.LayerNorm, norm_pix_loss=False):
        super().__init__()
        self.block = TPC(patch_size=patch_size, in_chans=7, embed_dim=embed_dim, depth=depth, num_heads=num_heads,
            decoder_embed_dim=decoder_embed_dim, decoder_depth=decoder_depth, decoder_num_heads=decoder_num_heads,
            mlp_ratio=mlp_ratio, norm_layer=norm_layer)
        self.load_block()
        self.dsconv_emb = nn.Sequential(
                DSConv(in_chans, 128, 1+8, depth_multiplier=128, layers=1),
                nn.Conv1d(128, 7, kernel_size=3, stride=1, padding=1, groups=1)
                )
        self.dsconv_out = nn.Sequential(
                DSConv(7, 32, 1+8, depth_multiplier=32, layers=1),
                nn.Conv1d(32, in_chans, kernel_size=3, stride=1, padding=1, groups=1)
                )
        
    def load_block(self, path=None):
        if path is None:
            # path = './output_dir/checkpoint-pretrain.pth'
            return
        checkpoint = torch.load(path, map_location='cpu')
        msg = self.block.load_state_dict(checkpoint['model'], strict=False)
        return
    
    def forward_loss(self, sq, rec):
        loss = F.mse_loss(rec,sq)
        return loss
    
    def forward(self, x, mask_ratio=0.75):
        input = x
        x = self.dsconv_emb(x).permute(0, 2, 1)
        _, [x, x_l], _ = self.block(x, mask_ratio)
        x = self.dsconv_out(x).permute(0, 2, 1)
        loss = self.forward_loss(input, x)
        return loss, x, loss.item()
    
    def test(self, x, mask_ratio=0.75):
        with torch.no_grad():
            input = x
            x = self.dsconv_emb(x).permute(0, 2, 1)
            _, [x,x_l], latent = self.block.test(x, mask_ratio)
            x = self.dsconv_out(x).permute(0, 2, 1)
            loss = self.forward_loss(input, x)
        return loss, x, latent
        
    def encoder(self, x):
        with torch.no_grad():
            x = self.dsconv_emb(x).permute(0, 2, 1)
            x = self.block.encoder(x)
        return x
    
    def decoder(self, x):
        with torch.no_grad():
            x = self.block.decoder(x)
            x = self.dsconv_out(x).permute(0, 2, 1)
        return x


def p32_c7_e256h16l1_d128h8l1(**kwargs):
    model = TPC(
        patch_size=32, in_chans=7, embed_dim=256, depth=1, num_heads=16,
        decoder_embed_dim=128, decoder_depth=1, decoder_num_heads=8,
        mlp_ratio=4, norm_layer=partial(nn.LayerNorm, eps=1e-6), **kwargs)
    return model


def p32_c28_e256h16l1_d128h8l1_transfer(**kwargs):
    model = TransferTS(
        patch_size=32, in_chans=28, embed_dim=256, depth=1, num_heads=16,
        decoder_embed_dim=128, decoder_depth=1, decoder_num_heads=8,
        mlp_ratio=4, norm_layer=partial(nn.LayerNorm, eps=1e-6), **kwargs)
    return model



# set recommended archs
etth_1024 = p32_c7_e256h16l1_d128h8l1 
energy_1024 = p32_c28_e256h16l1_d128h8l1_transfer
