1- The Imams have been granted full knowledge. Their source of knowledge is the Prophet (s) and also divine inspiration.
2- There is some knowledge that Allah only knows, and no creation knows. The Imams have the maximum knowledge and creation can have.
3- As for the event of the bed, we say the following:
One: he knew he would not die. Him having this knowledge, and the status he had which gave him such knowledge, is more virtuous than sleeping in the bed. When we talk about this virtue, in reality we remind ourselves of his higher virtues. Now since the virtue of the bed is something every person can grasp, it has been highlighted a lot. Otherwise, the Imam being chosen by Allah and having knowledge of the unseen is more virtuous.
Two: he knew he would not die, but maybe het gets wounded badly. He still showed courage.
Three: Some say at that very moment Allah blocked him from knowing his fate. So he really sacrificed.
Four: Allah praises him for that act. So whatever it was, Allah found it praiseworthy.
4- They are taught through miraculous ways, not normal methods of learning. In one hour, they can be taught thousands of doors of knowledge. This occurred with the power of Allah. Hence, at age 5 they would have massive knowledge.