This happened to me when I went to university, and I went from being lauded as top of the class to distinctly average. I would detest myself for not being able to match up to my peers, but I realised that this self-doubt was causing me to approach my studies with a bit of carelessness (as in, 'what's the point of putting effort in if I won't be top of the class anyway?'). When I started viewing it as a challenge, and used it as motivation, I did my best work, but I still couldn't reach their level. I just began to accept that I couldn't match them in academic ability, and realised that as long as I was proud of my work, as long as I was achieving what I was personally capable of, then I was perfectly happy.
It's easier said than done, but try and avoid comparison with your peers as much as possible. It's incredibly self-destructive. Push yourself to achieve what you're capable of, use your own past grades as motivation.