# Iterating in a sample from a batch

**URL:** <https://discuss.pytorch.org/t/iterating-in-a-sample-from-a-batch/20547>\
**Category:** nlp\
**Created:** [July 1, 2018, 8:38pm UTC](https://discuss.pytorch.org/t/iterating-in-a-sample-from-a-batch/20547 "2018-07-01T20:38:47Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![cherry](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/cherry/32/5697_2.png) [@cherry](https://discuss.pytorch.org/u/cherry)\
**Post date:** [July 1, 2018, 8:38pm UTC](https://discuss.pytorch.org/t/iterating-in-a-sample-from-a-batch/20547/1 "2018-07-01T20:38:47Z")

</div>

Hi;

I am new to nlp and pytorch.

I understand (I think) how to build ‘forward’ method, but if I want to iterate over each item in a batch inside _forward_, how do I incorporated that?

Thanks!

---

<div class="post-metadata">

**Author:** ![ptrblck](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/ptrblck/32/1823_2.png) [@ptrblck](https://discuss.pytorch.org/u/ptrblck)\
**Post date:** [July 2, 2018, 8:55am UTC](https://discuss.pytorch.org/t/iterating-in-a-sample-from-a-batch/20547/2 "2018-07-02T08:55:00Z")

</div>

You could just iterate the input `x`:

```python
class MyModel(nn.Module):
    def __init__ (self):
        super(MyModel, self). __init__ ()
        self.fc1 = nn.Linear(20, 10)
        self.fc2 = nn.Linear(10, 2)
        
    def forward(self, x):
        for x_ in x:
            print(x_.shape)
        
        x = F.relu(self.fc1(x))
        x = self.fc2(x)
        return x

model = MyModel()
x = torch.randn(2, 20)
output = model(x)

```

What is your use case? Since the batch size is usually varying, you shouldn’t assume to get a specific batch size.  
The most common approach is to write code that works with different batch sizes.
