Search code examples
luatorchresnet

The grammar explanation of torch[cpuType]


I first see the usage in lua like torch[cpuType] in the file dataloader.lua of fb.resnest.torch:

batch = torch[cpuType](sz, nCrops, table.unpack(imageSize))

I didn't find any grammar explanation of it. How to understand it?

PS: cpuType is defined in the file, namely self.cpuType, I guess.

Update: From my test, torch['FloatTensor'] is equivalent to torch.FloatTensor.


Solution

  • I think that torch[cpuType] is the same as torch.cpuType.

    The code (https://github.com/facebook/fb.resnet.torch/blob/master/dataloader.lua#L51-L57) seems to say that cpuType can take several different values, namely DoubleTensor, FloatTensor or HalfTensor. Consequently this notation creates a torch.DoubleTensor or torch.FloatTensor or torch.HalfTensor. It is a more compact notation for something like

    if cpuType == 'torch.DoubleTensor' then
        batch = torch.DoubleTensor(sz, nCrops, table.unpack(imageSize))
    elseif cpuType == 'torch.FloatTensor' then
        batch = torch.FloatTensor(sz, nCrops, table.unpack(imageSize))
    elseif cpuType == 'torch.HalfTensor' then
        batch = torch.HalfTensor(sz, nCrops, table.unpack(imageSize))