{% set devices = states | map(attribute='entity_id') | map('device_id') | unique | reject('eq',None) | list %}

{%- set ns = namespace(devices = []) %}
{%- for device in devices %}
  {%- set entities = device_entities(device) | list %}
  {%- if entities %}
    {%- set ns.devices = ns.devices +  [ {device: {"name": device_attr(device, "name"), "entities": entities }} ] %}
  {%- endif %}
{%- endfor %}

{%- set ns_group = namespace(entities = []) %}
{%- for state in states %}
  {%- if device_id(state.entity_id) == None %}
    {%- set ns_group.entities = ns_group.entities + [state.entity_id] %}
  {%- endif %}
{%- endfor %}
{%- set ns.devices = ns.devices +  [ {"other": {"name": "Other", "entities": ns_group.entities }} ] %}

{{ ns.devices }}