I) For a general Lagrangian $L(q,v,t)$, the Legendre transformation may be singular, i.e. the velocities $v^i$ in the momentum relations
$$\tag{1} p_i~:=~\frac{\partial L(q,v,t)}{\partial v^i}$$
cannot be isolated. How to perform a singular Legendre transformation to achieve the corresponding Hamiltonian formulation goes under the name Dirac-Bergmann analysis, cf. Refs. 1 and 2.
II) Example. OP is evidently considering Hopfields's EM model with polarization also studied in this Phys.SE post. Its Lagrangian density$^1$
$$\tag{2} {\cal L}(A_{\mu},{\bf P})
~=~-\frac{1}{16\pi}F_{\mu\nu}F^{\mu\nu} +A_{\mu} J^{\mu}_b
+\frac{1}{2\beta}\left(\frac{1}{\omega_0^2}\dot{\bf P}^2 -{\bf P}^2\right)$$
leads to a singular Legendre transformation. The momentum
$$\tag{3} \pi^0~:=~\frac{\partial {\cal L}}{\partial \dot{A}_0}~=~0$$
corresponding to the $A_0$ field vanishes! Eq. (3) is a primary constraint in Dirac's terminology. One may show that there also is a secondary constraint, namely Gauss's law
$$\tag{4} {\bf \nabla}\cdot {\bf D}~=~0,$$
where ${\bf D}={\bf E}+4\pi{\bf P}$. (There are no free charges in this model.) The momentum ${\bf \pi}=-\frac{1}{4\pi}{\bf E}$ for the magnetic vector potential ${\bf A}$ is essentially the electric field ${\bf E}$. Let ${\bf \Pi}$ be the momentum for the polarization ${\bf P}$. One may show that the Hamiltonian density becomes
$$\tag{5} {\cal H}(A_{\mu},{\bf E},{\bf P},{\bf \Pi})
~=~ \frac{1}{8\pi}({\bf E}^2+{\bf B}^2)
+\frac{1}{4\pi}A_0 {\bf \nabla}\cdot {\bf D}
+\frac{\beta\omega_0^2}{2}({\bf \Pi}-{\bf A})^2 +\frac{1}{2\beta}{\bf P}^2,$$
after dropping a total divergence term and eliminating the $\pi^0$ field.
III) Technically, what OP writes in his second equation is not the Hamiltonian density ${\cal H}$ but the Lagrangian energy density function
$$ \tag{6} {\cal h}(A_{\mu},\dot{\bf A},{\bf P},\dot{\bf P})
~:=~\dot{A}_{\mu} \frac{\partial {\cal L}}{\partial \dot{A}_{\mu}}
+ \dot{\bf P}\cdot \frac{\partial {\cal L}}{\partial \dot{\bf P}}-{\cal L}.$$
IV) More generally, the point is that the Lagrangian energy function $h$ depends on velocities $v$, while the Hamiltonian $H$ depends on momenta $p$. If the Lagrangian is of the form
$$ \tag{7} L~=~\sum_{n=0}^{2}L_n,$$
where $L_n$ is homogeneous in velocities $v$ with weight $n$ (i.e. the Lagrangian (7) depends on the velocities up to quadratic order), then the Lagrangian energy function is
$$\tag{8} h~:=~~\left(v^i\frac{\partial}{\partial v^i}-1\right) L ~=~\sum_{n=0}^{2}(n-1)L_n ~=~ L_2 - L_0. $$
In words: The quadratic terms $L_2$ are preserved, the linear terms $L_1$ disappear, and the constant terms $L_0$ flip signs.
References:
P.A.M. Dirac, Lectures on Quantum Mechanics, 1964.
M. Henneaux and C. Teitelboim, Quantization of Gauge Systems, 1994.
--
$^1$ In this answer we work with cgs units where the speed of light in vacuum is $c=1$, and Minkowski signature $(-,+,+,+)$, cf. this Phys.SE answer.