Callbacks in FastAI v2

I am exploring callbacks in v2. Here is the code:

class TestCallback(LearnerCallback):

def __init__(self,learn:Learner,weights:torch.Tensor=None):
    super().__init__(learn)
    self.weights = weights
    print('Init')

def on_train_begin(self, **kwargs):
  print('Inside Train Begin')

learn = cnn_learner( dl, resnet34, metrics=error_rate)
cb = TestCallback(learn) #this prints “Init”
learn.add_cb(cb) #AttributeError: ‘Learner’ object has no attribute ‘name’

Questions:

  1. Is my function within the callback class (on_train_begin) right or do I need to change the name of the function?

  2. How do I add a custom callback to the cnn_learner object? My way of adding gives ‘Atttribute Error’. Further, this line too seems to not work: learn.fit_one_cycle(2, cbs = cb)

  3. When creating a cnn_learner object, I see there is a property called “cbs”. When creating a cnn_learner object, the callbacks I pass to this cbs property should be the ones that do not require a learner object?

learner = cnn_learner(DL, resnet34, metrics=error_rate, cbs= ??)

learner = cnn_learner(DL, resnet34, metrics=error_rate, cbs=[TestCallback] )

you don’t need to pass learn to the callback, it can access via self.learn.

Hi @all, I am trying to use the pseudo labels before putting them in forward function. I am trying to use callbacks for it:

class PseudoLabelling(Callback):
    "A Callback that sends targ to model and adjusts teacher forcing ratio"
    #def __init__(self): self.teacher_forcing_ratio = teacher_forcing_ratio
    def before_batch(self):
        x,y = self.x, self.y
        with torch.no_grad():
          preds=self.learn.model(x)
          preds=self.learn.loss_func.activation(preds)
          preds=self.learn.loss_func.decodes(preds)

        preds=TensorCategory(preds)

But I am having this error:

TypeError: forward() takes 2 positional arguments but 3 were given

If I assign separately to self.learn.yb, then error is that 5 arguments are given, while 2 are expected.

Kindly help me out with it.
Thanks