GPUCodeForces/S1/wut0n_#9/l1_torchcode.py

44 lines
1.1 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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 [] # 没有特殊的初始化输入需求