[Python] AttributeError: 'torch.Size' object has no attribute 'size'

Discussão em 'Python' iniciado por Stack, Julho 2, 2025.

  1. Stack

    Stack Membro Participativo

    I'm working on an OCR inference pipeline using a custom PyTorch decoder that returns a variable called weights and includes a models_faster_dan.py file defining the model. Initially, I was calling .size() on weights like this: print(weights.size()) which gave me the error: AttributeError: 'torch.Size' object has no attribute 'size'. I learned that weights is actually a torch.Size object, and calling .size() on it is invalid because torch.Size itself represents the shape.

    So, I replaced the call with: print(len(weights)) But I get an error like: AttributeError: 'torch.Size' object has no attribute 'size'.

    What I've done so far:

    Added checks to verify if weights is None before using it.

    Tried replacing .size() calls with len(weights).

    Added debug prints of type(weights) and found sometimes it is <class 'torch.Size'>.

    In the decoder, when weights is None, I replace it with torch.zeros(1, device=output.device) to avoid crashes.

    Why does this AttributeError persist even after I avoid calling .size() on weights?

    Could weights sometimes be a tensor and other times a torch.Size object?

    The decoder code snippet:

    for i, dec_layer in enumerate(self.decoder_layers):
    output, weights, weights_self = dec_layer(...)
    if weights is None:
    weights = torch.zeros(1, device=output.device) # prevent .size() crash
    else:
    print(f"[DEBUG] Decoder layer {i}: weights type: {type(weights)}, shape: {len(weights)}")


    The error occurs at:

    if not keep_all_weights and weights is not None:
    weights = weights.reshape(weights.size(0), weights.size(1), features_size[2], features_size[3])

    Continue reading...

Compartilhe esta Página