forked from ccf-ai-infra/GPUCodeForces
44 lines
1.1 KiB
Python
44 lines
1.1 KiB
Python
import torch
|
||
import torch.nn as nn
|
||
|
||
class Model(nn.Module):
|
||
"""
|
||
合理优化的PyTorch L1 Loss实现
|
||
使用PyTorch内置函数,避免不必要的中间张量创建
|
||
"""
|
||
def __init__(self):
|
||
super(Model, self).__init__()
|
||
|
||
def forward(self, input: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
|
||
"""
|
||
使用PyTorch内置的l1_loss函数
|
||
L1 Loss = |input - target|
|
||
|
||
Args:
|
||
input (torch.Tensor): 预测值
|
||
target (torch.Tensor): 真实值
|
||
|
||
Returns:
|
||
torch.Tensor: L1 Loss标量值
|
||
"""
|
||
# 直接使用内置函数,让PyTorch处理优化
|
||
return torch.nn.functional.l1_loss(
|
||
input,
|
||
target,
|
||
reduction='sum'
|
||
)
|
||
|
||
batch_size = 128
|
||
num_features = 2000
|
||
|
||
def get_inputs():
|
||
"""
|
||
生成合理的测试数据
|
||
"""
|
||
input_vals = torch.randn(batch_size, num_features)
|
||
target_vals = torch.randn(batch_size, num_features)
|
||
return [input_vals, target_vals]
|
||
|
||
def get_init_inputs():
|
||
return [] # 没有特殊的初始化输入需求
|