Any Duke that has a city within their duchy can announce the creation of a new realm and proclaim themselves its ruler. In order to secede a duke must be in a city within their duchy, although they can choose any of their cities as capital of the new realm. When a duke secedes, all of the regions of their duchy will join the new realm along with all its knights and standing militia.
It is possible for dukes to secede even if their duchy contains the capital city of their current realm. However, if that city is the only remaining city region within the realm a duke will not be able announce a secession.
Although margraves command city regions, they cannot secede from the realm unless they have also been appointed duke.