TypeError: view(): argument 'size' failed to unpack the object at pos 4 with error "type must be tuple of ints,but got float"
Assistant
The error message you're encountering indicates that there's a problem with the view() method's size argument in your code. Specifically, you are passing a float value where a tuple of integers is expected. This can commonly occur when using PyTorch's tensor manipulation methods, such as view(), which are used to reshape tensors.
Let's address the error based on its components:
TypeError: view(): This part indicates that the error occurred with the view() method, which is commonly used in PyTorch for tensor reshaping or viewing the tensor in a different shape without changing its data.
argument 'size' failed to unpack the object at pos 4 with error: This tells you that the method expected the 'size' argument to be unpacked as a tuple of integers, but it encountered an issue at the 4th position in your argument list.
"type must be tuple of ints, but got float": The crux of the error message. You've supplied a float (a number with a decimal) where the method expected a tuple of integers (whole numbers without decimals).
This error most likely arises from calculations or operations resulting in a float value being passed to view() where integer values are required. Let's look at a couple of possible scenarios and solutions:
Example Problem
You might have code similar to this, inadvertently passing a float to view():
python
import torch
# Example tensor
tensor = torch.randn(16, 4)
# Mistakenly calculated size, ending up with a float
new_shape = (4, tensor.numel() / 4) # This division could result in a float.
# Attempt to reshape the tensor
reshaped_tensor = tensor.view(new_shape)
Solution 1: Ensure Integer Division
Make sure that any division operation used to calculate the size results in integer output. In Python, you can use the floor division // operator to achieve this.
python
new_shape = (4, tensor.numel() // 4) # Using '//' ensures an integer result.
reshaped_tensor = tensor.view(new_shape)
Solution 2: Explicit Conversion to Integers
Alternatively, especially if you're dealing with float calculations for the new shape, explicitly convert the result to integers using the int() function.
python
new_shape = (4, int(tensor.numel() / 4)) # Convert to int explicitly
reshaped_tensor = tensor.view(new_shape)
General Tip
Always ensure that the sizes you pass to PyTorch's view(), reshape(), or similar methods are integers, as these methods require integer dimensions to function correctly. If you're performing calculations to determine the new shape, use the appropriate method to ensure the results are integers.
设计选择:在Transformer架构中,这个位置前馈网络(PositionwiseFeedForward)的设计是遵循原始论文 "Attention is All You Need" 中的设定的。作者可能没有在第二个线性变换后使用激活函数,因为目标是让这个层能够进行简单的线性变换而不引入额外的非线性。这样做旨在为模型增加容量,同时保持其相对的简易性。